blob: b4de21c707c80ec6e0535f820fd592909943bf96 [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
Steve Naroffd82a9ab2008-03-15 00:55:56 +000055 unsigned NumObjCStringLiterals;
56
Steve Naroffebf2b562007-10-23 23:50:29 +000057 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000058 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000059 FunctionDecl *MsgSendStretFunctionDecl;
60 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000061 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000062 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000063 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000064 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000065 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000066 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000067 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000068
Steve Naroffbeaf2992007-11-03 11:27:19 +000069 // ObjC string constant support.
70 FileVarDecl *ConstantStringClassReference;
71 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000072
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000073 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000074 int BcLabelCount;
75
Steve Naroff874e2322007-11-15 10:28:18 +000076 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000077 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000078 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000079 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000080
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000081 // Needed for header files being rewritten
82 bool IsHeader;
83
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000084 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000085 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000086 void Initialize(ASTContext &context);
87
Chris Lattner8a12c272007-10-11 18:38:32 +000088
Chris Lattnerf04da132007-10-24 17:06:59 +000089 // Top Level Driver code.
90 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000091 void HandleDeclInMainFile(Decl *D);
Steve Naroff4f943c22008-03-10 20:43:59 +000092 RewriteTest(bool isHeader, Diagnostic &D, const LangOptions &LOpts) :
93 Diags(D), LangOpts(LOpts) {
Steve Narofff69cc5d2008-01-30 19:17:43 +000094 IsHeader = isHeader;
Steve Naroff0113c9d2008-01-28 21:34:52 +000095 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
96 "rewriting sub-expression within a macro (may not be correct)");
Steve Narofff69cc5d2008-01-30 19:17:43 +000097 }
Chris Lattnerf04da132007-10-24 17:06:59 +000098 ~RewriteTest();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000099
100 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000101 // If replacement succeeded or warning disabled return with no warning.
102 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000103 return;
104
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000105 SourceRange Range = Old->getSourceRange();
106 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
107 0, 0, &Range, 1);
108 }
109
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000110 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000111 // If insertion succeeded or warning disabled return with no warning.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000112 if (!Rewrite.InsertText(Loc, StrData, StrLen) ||
113 SilenceRewriteMacroWarning)
114 return;
115
116 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
117 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000118
Chris Lattneraadaf782008-01-31 19:51:04 +0000119 void RemoveText(SourceLocation Loc, unsigned StrLen) {
120 // If removal succeeded or warning disabled return with no warning.
121 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
122 return;
123
124 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
125 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000126
Chris Lattneraadaf782008-01-31 19:51:04 +0000127 void ReplaceText(SourceLocation Start, unsigned OrigLength,
128 const char *NewStr, unsigned NewLength) {
129 // If removal succeeded or warning disabled return with no warning.
130 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
131 SilenceRewriteMacroWarning)
132 return;
133
134 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
135 }
136
Chris Lattnerf04da132007-10-24 17:06:59 +0000137 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000138 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000139 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000140 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000141 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
142 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000143 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000144 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
145 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
146 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
147 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
148 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
149 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000150 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000151 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000152 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000153 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000154 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000155 QualType getConstantStringStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000156
Chris Lattnerf04da132007-10-24 17:06:59 +0000157 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000158 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000159 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000160 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000161 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000162 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000163 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000164 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000165 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000166 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000167 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
168 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
169 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000170 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
171 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000172 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
173 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000174 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000175 Stmt *RewriteBreakStmt(BreakStmt *S);
176 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000177 void SynthCountByEnumWithState(std::string &buf);
178
Steve Naroff09b266e2007-10-30 23:14:51 +0000179 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000180 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000181 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000182 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000183 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000184 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000185 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000186 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000187 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000188 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000189
Chris Lattnerf04da132007-10-24 17:06:59 +0000190 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000191 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
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 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000195 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000196
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000197 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
198 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000199 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000200 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000201 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000202 const char *ClassName,
203 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000204
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000205 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000206 int NumProtocols,
207 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000208 const char *ClassName,
209 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000210 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000211 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000212 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
213 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000214 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000215 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000216 };
217}
218
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000219static bool IsHeaderFile(const std::string &Filename) {
220 std::string::size_type DotPos = Filename.rfind('.');
221
222 if (DotPos == std::string::npos) {
223 // no file extension
224 return false;
225 }
226
227 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
228 // C header: .h
229 // C++ header: .hh or .H;
230 return Ext == "h" || Ext == "hh" || Ext == "H";
231}
232
233ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000234 Diagnostic &Diags,
235 const LangOptions &LOpts) {
236 return new RewriteTest(IsHeaderFile(InFile), Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000237}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000238
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000239void RewriteTest::Initialize(ASTContext &context) {
240 Context = &context;
241 SM = &Context->getSourceManager();
242 MsgSendFunctionDecl = 0;
243 MsgSendSuperFunctionDecl = 0;
244 MsgSendStretFunctionDecl = 0;
245 MsgSendSuperStretFunctionDecl = 0;
246 MsgSendFpretFunctionDecl = 0;
247 GetClassFunctionDecl = 0;
248 GetMetaClassFunctionDecl = 0;
249 SelGetUidFunctionDecl = 0;
250 CFStringFunctionDecl = 0;
251 GetProtocolFunctionDecl = 0;
252 ConstantStringClassReference = 0;
253 NSStringRecord = 0;
254 CurMethodDecl = 0;
255 SuperStructDecl = 0;
256 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000257 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000258 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000259
260 // Get the ID and start/end of the main file.
261 MainFileID = SM->getMainFileID();
262 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
263 MainFileStart = MainBuf->getBufferStart();
264 MainFileEnd = MainBuf->getBufferEnd();
265
266
267 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000268
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000269 // declaring objc_selector outside the parameter list removes a silly
270 // scope related warning...
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000271 std::string S = "#pragma once\n";
272 S += "struct objc_selector; struct objc_class;\n";
273 S += "#ifndef OBJC_SUPER\n";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000274 S += "struct objc_super { struct objc_object *object; ";
275 S += "struct objc_object *superClass; ";
276 if (LangOpts.Microsoft) {
277 // Add a constructor for creating temporary objects.
278 S += "objc_super(struct objc_object *o, struct objc_object *s) : ";
279 S += "object(o), superClass(s) {} ";
280 }
281 S += "};\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000282 S += "#define OBJC_SUPER\n";
283 S += "#endif\n";
284 S += "#ifndef _REWRITER_typedef_Protocol\n";
285 S += "typedef struct objc_object Protocol;\n";
286 S += "#define _REWRITER_typedef_Protocol\n";
287 S += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000288 if (LangOpts.Microsoft)
289 S += "extern \"C\" {\n";
290 S += "struct objc_object *objc_msgSend";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000291 S += "(struct objc_object *, struct objc_selector *, ...);\n";
292 S += "extern struct objc_object *objc_msgSendSuper";
293 S += "(struct objc_super *, struct objc_selector *, ...);\n";
294 S += "extern struct objc_object *objc_msgSend_stret";
295 S += "(struct objc_object *, struct objc_selector *, ...);\n";
296 S += "extern struct objc_object *objc_msgSendSuper_stret";
297 S += "(struct objc_super *, struct objc_selector *, ...);\n";
298 S += "extern struct objc_object *objc_msgSend_fpret";
299 S += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000300 S += "struct objc_object *objc_getClass";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000301 S += "(const char *);\n";
302 S += "extern struct objc_object *objc_getMetaClass";
303 S += "(const char *);\n";
304 S += "extern void objc_exception_throw(struct objc_object *);\n";
305 S += "extern void objc_exception_try_enter(void *);\n";
306 S += "extern void objc_exception_try_exit(void *);\n";
307 S += "extern struct objc_object *objc_exception_extract(void *);\n";
308 S += "extern int objc_exception_match";
309 S += "(struct objc_class *, struct objc_object *, ...);\n";
310 S += "extern Protocol *objc_getProtocol(const char *);\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000311 if (LangOpts.Microsoft)
312 S += "} // end extern \"C\"\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000313 S += "#include <objc/objc.h>\n";
314 S += "#ifndef __FASTENUMERATIONSTATE\n";
315 S += "struct __objcFastEnumerationState {\n\t";
316 S += "unsigned long state;\n\t";
317 S += "id *itemsPtr;\n\t";
318 S += "unsigned long *mutationsPtr;\n\t";
319 S += "unsigned long extra[5];\n};\n";
320 S += "#define __FASTENUMERATIONSTATE\n";
321 S += "#endif\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000322 S += "#ifndef __NSCONSTANTSTRINGIMPL\n";
323 S += "struct __NSConstantStringImpl {\n";
324 S += " struct objc_object *isa;\n";
325 S += " int flags;\n";
326 S += " char *str;\n";
327 S += " long length;\n";
328 S += " __NSConstantStringImpl(char *s, long l) :\n";
329 S += " flags(0), str(s), length(l)\n";
Steve Naroff3652c2d2008-03-15 01:36:04 +0000330 S += " { extern int __CFConstantStringClassReference[];\n";
331 S += " isa = (struct objc_object *)__CFConstantStringClassReference;}\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000332 S += "};\n";
333 S += "#define __NSCONSTANTSTRINGIMPL\n";
334 S += "#endif\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000335#if 0
336 if (LangOpts.Microsoft)
Steve Naroff4f943c22008-03-10 20:43:59 +0000337 S += "#define __attribute__(X)\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000338#endif
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000339 if (IsHeader) {
340 // insert the whole string when rewriting a header file
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000341 InsertText(SourceLocation::getFileLoc(MainFileID, 0), S.c_str(), S.size());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000342 }
343 else {
344 // Not rewriting header, exclude the #pragma once pragma
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000345 const char *p = S.c_str() + strlen("#pragma once\n");
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000346 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000347 }
348}
349
350
Chris Lattnerf04da132007-10-24 17:06:59 +0000351//===----------------------------------------------------------------------===//
352// Top Level Driver Code
353//===----------------------------------------------------------------------===//
354
Chris Lattner8a12c272007-10-11 18:38:32 +0000355void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000356 // Two cases: either the decl could be in the main file, or it could be in a
357 // #included file. If the former, rewrite it now. If the later, check to see
358 // if we rewrote the #include/#import.
359 SourceLocation Loc = D->getLocation();
360 Loc = SM->getLogicalLoc(Loc);
361
362 // If this is for a builtin, ignore it.
363 if (Loc.isInvalid()) return;
364
Steve Naroffebf2b562007-10-23 23:50:29 +0000365 // Look for built-in declarations that we need to refer during the rewrite.
366 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000367 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000368 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
369 // declared in <Foundation/NSString.h>
370 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
371 ConstantStringClassReference = FVD;
372 return;
373 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000374 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000375 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000376 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000377 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000378 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000379 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000380 } else if (ObjCForwardProtocolDecl *FP =
381 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000382 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000383 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000384 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000385 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
386 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000387}
388
Chris Lattnerf04da132007-10-24 17:06:59 +0000389/// HandleDeclInMainFile - This is called for each top-level decl defined in the
390/// main file of the input.
391void RewriteTest::HandleDeclInMainFile(Decl *D) {
392 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
393 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000394 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000395
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000396 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000397 if (Stmt *Body = MD->getBody()) {
398 //Body->dump();
399 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000400 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000401 CurMethodDecl = 0;
402 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000403 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000404 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000405 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000406 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000407 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000408 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000409 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000410 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000411 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000412 if (VD->getInit())
413 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
414 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000415 // Nothing yet.
416}
417
418RewriteTest::~RewriteTest() {
419 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000420
421 // Rewrite tabs if we care.
422 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000423
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000424 RewriteInclude();
425
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000426 // Rewrite Objective-c meta data*
427 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000428 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000429
Chris Lattnerf04da132007-10-24 17:06:59 +0000430 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
431 // we are done.
432 if (const RewriteBuffer *RewriteBuf =
433 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000434 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000435 std::string S(RewriteBuf->begin(), RewriteBuf->end());
436 printf("%s\n", S.c_str());
437 } else {
438 printf("No changes\n");
439 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000440 // Emit metadata.
441 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000442}
443
Chris Lattnerf04da132007-10-24 17:06:59 +0000444//===----------------------------------------------------------------------===//
445// Syntactic (non-AST) Rewriting Code
446//===----------------------------------------------------------------------===//
447
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000448void RewriteTest::RewriteInclude() {
449 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
450 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
451 const char *MainBufStart = MainBuf.first;
452 const char *MainBufEnd = MainBuf.second;
453 size_t ImportLen = strlen("import");
454 size_t IncludeLen = strlen("include");
455
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000456 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000457 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
458 if (*BufPtr == '#') {
459 if (++BufPtr == MainBufEnd)
460 return;
461 while (*BufPtr == ' ' || *BufPtr == '\t')
462 if (++BufPtr == MainBufEnd)
463 return;
464 if (!strncmp(BufPtr, "import", ImportLen)) {
465 // replace import with include
466 SourceLocation ImportLoc =
467 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000468 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000469 BufPtr += ImportLen;
470 }
471 }
472 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000473}
474
Chris Lattnerf04da132007-10-24 17:06:59 +0000475void RewriteTest::RewriteTabs() {
476 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
477 const char *MainBufStart = MainBuf.first;
478 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000479
Chris Lattnerf04da132007-10-24 17:06:59 +0000480 // Loop over the whole file, looking for tabs.
481 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
482 if (*BufPtr != '\t')
483 continue;
484
485 // Okay, we found a tab. This tab will turn into at least one character,
486 // but it depends on which 'virtual column' it is in. Compute that now.
487 unsigned VCol = 0;
488 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
489 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
490 ++VCol;
491
492 // Okay, now that we know the virtual column, we know how many spaces to
493 // insert. We assume 8-character tab-stops.
494 unsigned Spaces = 8-(VCol & 7);
495
496 // Get the location of the tab.
497 SourceLocation TabLoc =
498 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
499
500 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000501 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000502 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000503}
504
505
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000506void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000507 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000508 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000509
510 // Get the start location and compute the semi location.
511 SourceLocation startLoc = ClassDecl->getLocation();
512 const char *startBuf = SM->getCharacterData(startLoc);
513 const char *semiPtr = strchr(startBuf, ';');
514
515 // Translate to typedef's that forward reference structs with the same name
516 // as the class. As a convenience, we include the original declaration
517 // as a comment.
518 std::string typedefString;
519 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000520 typedefString.append(startBuf, semiPtr-startBuf+1);
521 typedefString += "\n";
522 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000523 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000524 typedefString += "#ifndef _REWRITER_typedef_";
525 typedefString += ForwardDecl->getName();
526 typedefString += "\n";
527 typedefString += "#define _REWRITER_typedef_";
528 typedefString += ForwardDecl->getName();
529 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000530 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000531 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000532 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000533 }
534
535 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000536 ReplaceText(startLoc, semiPtr-startBuf+1,
537 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000538}
539
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000540void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000541 SourceLocation LocStart = Method->getLocStart();
542 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000543
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000544 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000545 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000546 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000547 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000548 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000549 }
550}
551
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000552void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000553{
554 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000555 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000556 SourceLocation Loc = Property->getLocation();
557
Chris Lattneraadaf782008-01-31 19:51:04 +0000558 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000559
560 // FIXME: handle properties that are declared across multiple lines.
561 }
562}
563
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000564void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000565 SourceLocation LocStart = CatDecl->getLocStart();
566
567 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000568 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000569
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000570 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000571 E = CatDecl->instmeth_end(); I != E; ++I)
572 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000573 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000574 E = CatDecl->classmeth_end(); I != E; ++I)
575 RewriteMethodDeclaration(*I);
576
Steve Naroff423cb562007-10-30 13:30:57 +0000577 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000578 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000579}
580
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000581void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000582 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000583
Steve Naroff752d6ef2007-10-30 16:42:30 +0000584 SourceLocation LocStart = PDecl->getLocStart();
585
586 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000587 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000588
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000589 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000590 E = PDecl->instmeth_end(); I != E; ++I)
591 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000592 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000593 E = PDecl->classmeth_end(); I != E; ++I)
594 RewriteMethodDeclaration(*I);
595
Steve Naroff752d6ef2007-10-30 16:42:30 +0000596 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000597 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000598 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000599
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000600 // Must comment out @optional/@required
601 const char *startBuf = SM->getCharacterData(LocStart);
602 const char *endBuf = SM->getCharacterData(LocEnd);
603 for (const char *p = startBuf; p < endBuf; p++) {
604 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
605 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000606 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000607 ReplaceText(OptionalLoc, strlen("@optional"),
608 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000609
610 }
611 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
612 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000613 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000614 ReplaceText(OptionalLoc, strlen("@required"),
615 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000616
617 }
618 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000619}
620
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000621void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000622 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000623 if (LocStart.isInvalid())
624 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000625 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000626 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000627}
628
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000629void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000630 std::string &ResultStr) {
631 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000632 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000633 ResultStr += "id";
634 else
635 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000636 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000637
638 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000639 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000640
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000641 if (OMD->isInstance())
642 NameStr += "_I_";
643 else
644 NameStr += "_C_";
645
646 NameStr += OMD->getClassInterface()->getName();
647 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000648
649 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000650 if (ObjCCategoryImplDecl *CID =
651 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000652 NameStr += CID->getName();
653 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000654 }
655 // Append selector names, replacing ':' with '_'
656 const char *selName = OMD->getSelector().getName().c_str();
657 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000658 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000659 else {
660 std::string selString = OMD->getSelector().getName();
661 int len = selString.size();
662 for (int i = 0; i < len; i++)
663 if (selString[i] == ':')
664 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000665 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000666 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000667 // Remember this name for metadata emission
668 MethodInternalNames[OMD] = NameStr;
669 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000670
671 // Rewrite arguments
672 ResultStr += "(";
673
674 // invisible arguments
675 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000676 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000677 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000678 if (!LangOpts.Microsoft) {
679 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
680 ResultStr += "struct ";
681 }
682 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000683 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000684 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000685 }
686 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000687 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000688
689 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000690 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000691 ResultStr += " _cmd";
692
693 // Method arguments.
694 for (int i = 0; i < OMD->getNumParams(); i++) {
695 ParmVarDecl *PDecl = OMD->getParamDecl(i);
696 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000697 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000698 ResultStr += "id";
699 else
700 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000701 ResultStr += " ";
702 ResultStr += PDecl->getName();
703 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000704 if (OMD->isVariadic())
705 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000706 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000707
708}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000709void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000710 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
711 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000712
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000713 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000714 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000715 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000716 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000717
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000718 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000719 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
720 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000721 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000722 ObjCMethodDecl *OMD = *I;
723 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000724 SourceLocation LocStart = OMD->getLocStart();
725 SourceLocation LocEnd = OMD->getBody()->getLocStart();
726
727 const char *startBuf = SM->getCharacterData(LocStart);
728 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000729 ReplaceText(LocStart, endBuf-startBuf,
730 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000731 }
732
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000733 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000734 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
735 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000736 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000737 ObjCMethodDecl *OMD = *I;
738 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000739 SourceLocation LocStart = OMD->getLocStart();
740 SourceLocation LocEnd = OMD->getBody()->getLocStart();
741
742 const char *startBuf = SM->getCharacterData(LocStart);
743 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000744 ReplaceText(LocStart, endBuf-startBuf,
745 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000746 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000747 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000748 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000749 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000750 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000751}
752
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000753void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000754 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000755 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000756 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000757 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000758 ResultStr += ClassDecl->getName();
759 ResultStr += "\n";
760 ResultStr += "#define _REWRITER_typedef_";
761 ResultStr += ClassDecl->getName();
762 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000763 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000764 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000765 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000766 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000767 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000768 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000769 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000770
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000771 RewriteProperties(ClassDecl->getNumPropertyDecl(),
772 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000773 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000774 E = ClassDecl->instmeth_end(); I != E; ++I)
775 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000776 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000777 E = ClassDecl->classmeth_end(); I != E; ++I)
778 RewriteMethodDeclaration(*I);
779
Steve Naroff2feac5e2007-10-30 03:43:13 +0000780 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000781 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000782}
783
Steve Naroff7e3411b2007-11-15 02:58:25 +0000784Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000785 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000786 if (CurMethodDecl) {
787 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
788 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
789 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000790 // lookup which class implements the instance variable.
791 ObjCInterfaceDecl *clsDeclared = 0;
792 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
793 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5518e7c2008-03-12 23:15:19 +0000794
795 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000796 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff05b8c782008-03-12 00:25:36 +0000797 RecName += "_IMPL";
798 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Chris Lattnerc63e6602008-03-15 21:32:50 +0000799 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct,
800 SourceLocation(), II, 0);
Steve Naroff05b8c782008-03-12 00:25:36 +0000801 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
802 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
803 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
804 // Don't forget the parens to enforce the proper binding.
805 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
806 if (IV->isFreeIvar()) {
807 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
808 ReplaceStmt(IV, ME);
809 delete IV;
810 return ME;
811 } else {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000812 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5518e7c2008-03-12 23:15:19 +0000813 // Cannot delete IV->getBase(), since PE points to it.
814 // Replace the old base with the cast. This is important when doing
815 // embedded rewrites. For example, [newInv->_container addObject:0].
816 IV->setBase(PE);
817 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000818 }
819 }
820 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000821 }
Steve Naroff5518e7c2008-03-12 23:15:19 +0000822 // FIXME: Implement public ivar access from a function.
Steve Naroff05b8c782008-03-12 00:25:36 +0000823 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
824 IV->getLocation(), D->getType());
825 ReplaceStmt(IV, Replacement);
826 delete IV;
827 return Replacement;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000828}
829
Chris Lattnerf04da132007-10-24 17:06:59 +0000830//===----------------------------------------------------------------------===//
831// Function Body / Expression rewriting
832//===----------------------------------------------------------------------===//
833
Steve Narofff3473a72007-11-09 15:20:18 +0000834Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000835 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
836 isa<DoStmt>(S) || isa<ForStmt>(S))
837 Stmts.push_back(S);
838 else if (isa<ObjCForCollectionStmt>(S)) {
839 Stmts.push_back(S);
840 ObjCBcLabelNo.push_back(++BcLabelCount);
841 }
842
Chris Lattner338d1e22008-01-31 05:10:40 +0000843 SourceLocation OrigStmtEnd = S->getLocEnd();
844
845 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000846 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
847 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000848 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000849 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000850 if (newStmt)
851 *CI = newStmt;
852 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000853
854 // Handle specific things.
855 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
856 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000857
858 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
859 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000860
861 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
862 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000863
Steve Naroffbeaf2992007-11-03 11:27:19 +0000864 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
865 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000866
Steve Naroff934f2762007-10-24 22:48:43 +0000867 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
868 // Before we rewrite it, put the original message expression in a comment.
869 SourceLocation startLoc = MessExpr->getLocStart();
870 SourceLocation endLoc = MessExpr->getLocEnd();
871
872 const char *startBuf = SM->getCharacterData(startLoc);
873 const char *endBuf = SM->getCharacterData(endLoc);
874
875 std::string messString;
876 messString += "// ";
877 messString.append(startBuf, endBuf-startBuf+1);
878 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000879
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000880 // FIXME: Missing definition of
881 // InsertText(clang::SourceLocation, char const*, unsigned int).
882 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000883 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000884 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000885 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000886 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000887
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000888 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
889 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000890
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000891 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
892 return RewriteObjCSynchronizedStmt(StmtTry);
893
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000894 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
895 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000896
897 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
898 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000899
900 if (ObjCForCollectionStmt *StmtForCollection =
901 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000902 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000903 if (BreakStmt *StmtBreakStmt =
904 dyn_cast<BreakStmt>(S))
905 return RewriteBreakStmt(StmtBreakStmt);
906 if (ContinueStmt *StmtContinueStmt =
907 dyn_cast<ContinueStmt>(S))
908 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000909
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000910 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
911 isa<DoStmt>(S) || isa<ForStmt>(S)) {
912 assert(!Stmts.empty() && "Statement stack is empty");
913 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
914 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
915 && "Statement stack mismatch");
916 Stmts.pop_back();
917 }
Steve Naroff874e2322007-11-15 10:28:18 +0000918#if 0
919 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
920 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
921 // Get the new text.
922 std::ostringstream Buf;
923 Replacement->printPretty(Buf);
924 const std::string &Str = Buf.str();
925
926 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000927 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000928 delete S;
929 return Replacement;
930 }
931#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000932 // Return this stmt unmodified.
933 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000934}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000935
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000936/// SynthCountByEnumWithState - To print:
937/// ((unsigned int (*)
938/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
939/// (void *)objc_msgSend)((id)l_collection,
940/// sel_registerName(
941/// "countByEnumeratingWithState:objects:count:"),
942/// &enumState,
943/// (id *)items, (unsigned int)16)
944///
945void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
946 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
947 "id *, unsigned int))(void *)objc_msgSend)";
948 buf += "\n\t\t";
949 buf += "((id)l_collection,\n\t\t";
950 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
951 buf += "\n\t\t";
952 buf += "&enumState, "
953 "(id *)items, (unsigned int)16)";
954}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000955
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000956/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
957/// statement to exit to its outer synthesized loop.
958///
959Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
960 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
961 return S;
962 // replace break with goto __break_label
963 std::string buf;
964
965 SourceLocation startLoc = S->getLocStart();
966 buf = "goto __break_label_";
967 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000968 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000969
970 return 0;
971}
972
973/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
974/// statement to continue with its inner synthesized loop.
975///
976Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
977 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
978 return S;
979 // replace continue with goto __continue_label
980 std::string buf;
981
982 SourceLocation startLoc = S->getLocStart();
983 buf = "goto __continue_label_";
984 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000985 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000986
987 return 0;
988}
989
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000990/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000991/// It rewrites:
992/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000993
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000994/// Into:
995/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000996/// type elem;
997/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000998/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000999/// id l_collection = (id)collection;
1000/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1001/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001002/// if (limit) {
1003/// unsigned long startMutations = *enumState.mutationsPtr;
1004/// do {
1005/// unsigned long counter = 0;
1006/// do {
1007/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001008/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001009/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001010/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001011/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001012/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001013/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1014/// objects:items count:16]);
1015/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001016/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001017/// }
1018/// else
1019/// elem = nil;
1020/// }
1021///
Chris Lattner338d1e22008-01-31 05:10:40 +00001022Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1023 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001024 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1025 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1026 "ObjCForCollectionStmt Statement stack mismatch");
1027 assert(!ObjCBcLabelNo.empty() &&
1028 "ObjCForCollectionStmt - Label No stack empty");
1029
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001030 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001031 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001032 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001033 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001034 std::string buf;
1035 buf = "\n{\n\t";
1036 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1037 // type elem;
1038 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001039 elementTypeAsString = ElementType.getAsString();
1040 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001041 buf += " ";
1042 elementName = DS->getDecl()->getName();
1043 buf += elementName;
1044 buf += ";\n\t";
1045 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001046 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001047 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001048 elementTypeAsString = DR->getDecl()->getType().getAsString();
1049 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001050 else
1051 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1052
1053 // struct __objcFastEnumerationState enumState = { 0 };
1054 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1055 // id items[16];
1056 buf += "id items[16];\n\t";
1057 // id l_collection = (id)
1058 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001059 // Find start location of 'collection' the hard way!
1060 const char *startCollectionBuf = startBuf;
1061 startCollectionBuf += 3; // skip 'for'
1062 startCollectionBuf = strchr(startCollectionBuf, '(');
1063 startCollectionBuf++; // skip '('
1064 // find 'in' and skip it.
1065 while (*startCollectionBuf != ' ' ||
1066 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1067 (*(startCollectionBuf+3) != ' ' &&
1068 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1069 startCollectionBuf++;
1070 startCollectionBuf += 3;
1071
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001072 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001073 ReplaceText(startLoc, startCollectionBuf - startBuf,
1074 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001075 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001076 SourceLocation rightParenLoc = S->getRParenLoc();
1077 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1078 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001079 buf = ";\n\t";
1080
1081 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1082 // objects:items count:16];
1083 // which is synthesized into:
1084 // unsigned int limit =
1085 // ((unsigned int (*)
1086 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1087 // (void *)objc_msgSend)((id)l_collection,
1088 // sel_registerName(
1089 // "countByEnumeratingWithState:objects:count:"),
1090 // (struct __objcFastEnumerationState *)&state,
1091 // (id *)items, (unsigned int)16);
1092 buf += "unsigned long limit =\n\t\t";
1093 SynthCountByEnumWithState(buf);
1094 buf += ";\n\t";
1095 /// if (limit) {
1096 /// unsigned long startMutations = *enumState.mutationsPtr;
1097 /// do {
1098 /// unsigned long counter = 0;
1099 /// do {
1100 /// if (startMutations != *enumState.mutationsPtr)
1101 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001102 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001103 buf += "if (limit) {\n\t";
1104 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1105 buf += "do {\n\t\t";
1106 buf += "unsigned long counter = 0;\n\t\t";
1107 buf += "do {\n\t\t\t";
1108 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1109 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1110 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001111 buf += " = (";
1112 buf += elementTypeAsString;
1113 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001114 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001115 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001116
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001117 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001118 /// } while (counter < limit);
1119 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1120 /// objects:items count:16]);
1121 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001122 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001123 /// }
1124 /// else
1125 /// elem = nil;
1126 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001127 ///
1128 buf = ";\n\t";
1129 buf += "__continue_label_";
1130 buf += utostr(ObjCBcLabelNo.back());
1131 buf += ": ;";
1132 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001133 buf += "} while (counter < limit);\n\t";
1134 buf += "} while (limit = ";
1135 SynthCountByEnumWithState(buf);
1136 buf += ");\n\t";
1137 buf += elementName;
1138 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001139 buf += "__break_label_";
1140 buf += utostr(ObjCBcLabelNo.back());
1141 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001142 buf += "}\n\t";
1143 buf += "else\n\t\t";
1144 buf += elementName;
1145 buf += " = nil;\n";
1146 buf += "}\n";
1147 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001148 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001149 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001150 Stmts.pop_back();
1151 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001152 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001153}
1154
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001155/// RewriteObjCSynchronizedStmt -
1156/// This routine rewrites @synchronized(expr) stmt;
1157/// into:
1158/// objc_sync_enter(expr);
1159/// @try stmt @finally { objc_sync_exit(expr); }
1160///
1161Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1162 // Get the start location and compute the semi location.
1163 SourceLocation startLoc = S->getLocStart();
1164 const char *startBuf = SM->getCharacterData(startLoc);
1165
1166 assert((*startBuf == '@') && "bogus @synchronized location");
1167
1168 std::string buf;
1169 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001170 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001171 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1172 const char *endBuf = SM->getCharacterData(endLoc);
1173 endBuf++;
1174 const char *rparenBuf = strchr(endBuf, ')');
1175 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1176 buf = ");\n";
1177 // declare a new scope with two variables, _stack and _rethrow.
1178 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1179 buf += "int buf[18/*32-bit i386*/];\n";
1180 buf += "char *pointers[4];} _stack;\n";
1181 buf += "id volatile _rethrow = 0;\n";
1182 buf += "objc_exception_try_enter(&_stack);\n";
1183 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001184 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001185 startLoc = S->getSynchBody()->getLocEnd();
1186 startBuf = SM->getCharacterData(startLoc);
1187
1188 assert((*startBuf == '}') && "bogus @try block");
1189 SourceLocation lastCurlyLoc = startLoc;
1190 buf = "}\nelse {\n";
1191 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1192 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1193 // FIXME: This must be objc_sync_exit(syncExpr);
1194 buf += " objc_sync_exit();\n";
1195 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1196 buf += "}\n";
1197 buf += "}";
1198
Chris Lattneraadaf782008-01-31 19:51:04 +00001199 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001200 return 0;
1201}
1202
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001203Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001204 // Get the start location and compute the semi location.
1205 SourceLocation startLoc = S->getLocStart();
1206 const char *startBuf = SM->getCharacterData(startLoc);
1207
1208 assert((*startBuf == '@') && "bogus @try location");
1209
1210 std::string buf;
1211 // declare a new scope with two variables, _stack and _rethrow.
1212 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1213 buf += "int buf[18/*32-bit i386*/];\n";
1214 buf += "char *pointers[4];} _stack;\n";
1215 buf += "id volatile _rethrow = 0;\n";
1216 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001217 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001218
Chris Lattneraadaf782008-01-31 19:51:04 +00001219 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001220
1221 startLoc = S->getTryBody()->getLocEnd();
1222 startBuf = SM->getCharacterData(startLoc);
1223
1224 assert((*startBuf == '}') && "bogus @try block");
1225
1226 SourceLocation lastCurlyLoc = startLoc;
1227
1228 startLoc = startLoc.getFileLocWithOffset(1);
1229 buf = " /* @catch begin */ else {\n";
1230 buf += " id _caught = objc_exception_extract(&_stack);\n";
1231 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001232 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001233 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1234 buf += " else { /* @catch continue */";
1235
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001236 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001237
1238 bool sawIdTypedCatch = false;
1239 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001240 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001241 while (catchList) {
1242 Stmt *catchStmt = catchList->getCatchParamStmt();
1243
1244 if (catchList == S->getCatchStmts())
1245 buf = "if ("; // we are generating code for the first catch clause
1246 else
1247 buf = "else if (";
1248 startLoc = catchList->getLocStart();
1249 startBuf = SM->getCharacterData(startLoc);
1250
1251 assert((*startBuf == '@') && "bogus @catch location");
1252
1253 const char *lParenLoc = strchr(startBuf, '(');
1254
Steve Naroffbe4b3332008-02-01 22:08:12 +00001255 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001256 // Now rewrite the body...
1257 lastCatchBody = catchList->getCatchBody();
1258 SourceLocation rParenLoc = catchList->getRParenLoc();
1259 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1260 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1261 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1262 assert((*rParenBuf == ')') && "bogus @catch paren location");
1263 assert((*bodyBuf == '{') && "bogus @catch body location");
1264
1265 buf += "1) { id _tmp = _caught;";
1266 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1267 buf.c_str(), buf.size());
1268 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001269 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001270 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001271 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001272 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001273 sawIdTypedCatch = true;
1274 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001275 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001276
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001277 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001278 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001279 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001280 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001281 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001282 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001283 }
1284 }
1285 // Now rewrite the body...
1286 lastCatchBody = catchList->getCatchBody();
1287 SourceLocation rParenLoc = catchList->getRParenLoc();
1288 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1289 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1290 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1291 assert((*rParenBuf == ')') && "bogus @catch paren location");
1292 assert((*bodyBuf == '{') && "bogus @catch body location");
1293
1294 buf = " = _caught;";
1295 // Here we replace ") {" with "= _caught;" (which initializes and
1296 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001297 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001298 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001299 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001300 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001301 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001302 catchList = catchList->getNextCatchStmt();
1303 }
1304 // Complete the catch list...
1305 if (lastCatchBody) {
1306 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1307 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1308 assert((*bodyBuf == '}') && "bogus @catch body location");
1309 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1310 buf = " } } /* @catch end */\n";
1311
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001312 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001313
1314 // Set lastCurlyLoc
1315 lastCurlyLoc = lastCatchBody->getLocEnd();
1316 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001317 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001318 startLoc = finalStmt->getLocStart();
1319 startBuf = SM->getCharacterData(startLoc);
1320 assert((*startBuf == '@') && "bogus @finally start");
1321
1322 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001323 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001324
1325 Stmt *body = finalStmt->getFinallyBody();
1326 SourceLocation startLoc = body->getLocStart();
1327 SourceLocation endLoc = body->getLocEnd();
1328 const char *startBuf = SM->getCharacterData(startLoc);
1329 const char *endBuf = SM->getCharacterData(endLoc);
1330 assert((*startBuf == '{') && "bogus @finally body location");
1331 assert((*endBuf == '}') && "bogus @finally body location");
1332
1333 startLoc = startLoc.getFileLocWithOffset(1);
1334 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001335 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001336 endLoc = endLoc.getFileLocWithOffset(-1);
1337 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001338 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001339
1340 // Set lastCurlyLoc
1341 lastCurlyLoc = body->getLocEnd();
1342 }
1343 // Now emit the final closing curly brace...
1344 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1345 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001346 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001347 return 0;
1348}
1349
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001350Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001351 return 0;
1352}
1353
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001354Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001355 return 0;
1356}
1357
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001358// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001359// the throw expression is typically a message expression that's already
1360// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001361Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001362 // Get the start location and compute the semi location.
1363 SourceLocation startLoc = S->getLocStart();
1364 const char *startBuf = SM->getCharacterData(startLoc);
1365
1366 assert((*startBuf == '@') && "bogus @throw location");
1367
1368 std::string buf;
1369 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001370 if (S->getThrowExpr())
1371 buf = "objc_exception_throw(";
1372 else // add an implicit argument
1373 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001374 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001375 const char *semiBuf = strchr(startBuf, ';');
1376 assert((*semiBuf == ';') && "@throw: can't find ';'");
1377 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1378 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001379 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001380 return 0;
1381}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001382
Chris Lattnere64b7772007-10-24 16:57:36 +00001383Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001384 // Create a new string expression.
1385 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001386 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001387 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1388 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001389 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1390 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001391 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001392 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001393
Chris Lattner07506182007-11-30 22:53:43 +00001394 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001395 delete Exp;
1396 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001397}
1398
Steve Naroffb42f8412007-11-05 14:50:49 +00001399Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1400 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1401 // Create a call to sel_registerName("selName").
1402 llvm::SmallVector<Expr*, 8> SelExprs;
1403 QualType argType = Context->getPointerType(Context->CharTy);
1404 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1405 Exp->getSelector().getName().size(),
1406 false, argType, SourceLocation(),
1407 SourceLocation()));
1408 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1409 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001410 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001411 delete Exp;
1412 return SelExp;
1413}
1414
Steve Naroff934f2762007-10-24 22:48:43 +00001415CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1416 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001417 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001418 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001419
1420 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001421 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001422
1423 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001424 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001425 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1426
1427 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001428
Steve Naroff934f2762007-10-24 22:48:43 +00001429 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1430}
1431
Steve Naroffd5255f52007-11-01 13:24:47 +00001432static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1433 const char *&startRef, const char *&endRef) {
1434 while (startBuf < endBuf) {
1435 if (*startBuf == '<')
1436 startRef = startBuf; // mark the start.
1437 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001438 if (startRef && *startRef == '<') {
1439 endRef = startBuf; // mark the end.
1440 return true;
1441 }
1442 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001443 }
1444 startBuf++;
1445 }
1446 return false;
1447}
1448
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001449static void scanToNextArgument(const char *&argRef) {
1450 int angle = 0;
1451 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1452 if (*argRef == '<')
1453 angle++;
1454 else if (*argRef == '>')
1455 angle--;
1456 argRef++;
1457 }
1458 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1459}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001460
Steve Naroffd5255f52007-11-01 13:24:47 +00001461bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001462
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001463 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001464 return true;
1465
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001466 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001467 return true;
1468
Steve Naroffd5255f52007-11-01 13:24:47 +00001469 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001470 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001471 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001472 return true; // we have "Class <Protocol> *".
1473 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001474 return false;
1475}
1476
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001477void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001478 SourceLocation Loc;
1479 QualType Type;
1480 const FunctionTypeProto *proto = 0;
1481 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1482 Loc = VD->getLocation();
1483 Type = VD->getType();
1484 }
1485 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1486 Loc = FD->getLocation();
1487 // Check for ObjC 'id' and class types that have been adorned with protocol
1488 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1489 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1490 assert(funcType && "missing function type");
1491 proto = dyn_cast<FunctionTypeProto>(funcType);
1492 if (!proto)
1493 return;
1494 Type = proto->getResultType();
1495 }
1496 else
1497 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001498
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001499 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001500 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001501
1502 const char *endBuf = SM->getCharacterData(Loc);
1503 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001504 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001505 startBuf--; // scan backward (from the decl location) for return type.
1506 const char *startRef = 0, *endRef = 0;
1507 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1508 // Get the locations of the startRef, endRef.
1509 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1510 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1511 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001512 InsertText(LessLoc, "/*", 2);
1513 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001514 }
1515 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001516 if (!proto)
1517 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001518 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001519 const char *startBuf = SM->getCharacterData(Loc);
1520 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001521 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1522 if (needToScanForQualifiers(proto->getArgType(i))) {
1523 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001524
Steve Naroffd5255f52007-11-01 13:24:47 +00001525 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001526 // scan forward (from the decl location) for argument types.
1527 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001528 const char *startRef = 0, *endRef = 0;
1529 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1530 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001531 SourceLocation LessLoc =
1532 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1533 SourceLocation GreaterLoc =
1534 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001535 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001536 InsertText(LessLoc, "/*", 2);
1537 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001538 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001539 startBuf = ++endBuf;
1540 }
1541 else {
1542 while (*startBuf != ')' && *startBuf != ',')
1543 startBuf++; // scan forward (from the decl location) for argument types.
1544 startBuf++;
1545 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001546 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001547}
1548
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001549// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1550void RewriteTest::SynthSelGetUidFunctionDecl() {
1551 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1552 llvm::SmallVector<QualType, 16> ArgTys;
1553 ArgTys.push_back(Context->getPointerType(
1554 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001555 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001556 &ArgTys[0], ArgTys.size(),
1557 false /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001558 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001559 SelGetUidIdent, getFuncType,
1560 FunctionDecl::Extern, false, 0);
1561}
1562
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001563// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1564void RewriteTest::SynthGetProtocolFunctionDecl() {
1565 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1566 llvm::SmallVector<QualType, 16> ArgTys;
1567 ArgTys.push_back(Context->getPointerType(
1568 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001569 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001570 &ArgTys[0], ArgTys.size(),
1571 false /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001572 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001573 SelGetProtoIdent, getFuncType,
1574 FunctionDecl::Extern, false, 0);
1575}
1576
Steve Naroff09b266e2007-10-30 23:14:51 +00001577void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1578 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001579 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001580 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001581 return;
1582 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001583 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001584}
1585
Steve Naroffc0a123c2008-03-11 17:37:02 +00001586// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1587void RewriteTest::SynthSuperContructorFunctionDecl() {
1588 if (SuperContructorFunctionDecl)
1589 return;
1590 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1591 llvm::SmallVector<QualType, 16> ArgTys;
1592 QualType argT = Context->getObjCIdType();
1593 assert(!argT.isNull() && "Can't find 'id' type");
1594 ArgTys.push_back(argT);
1595 ArgTys.push_back(argT);
1596 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1597 &ArgTys[0], ArgTys.size(),
1598 false);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001599 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001600 msgSendIdent, msgSendType,
1601 FunctionDecl::Extern, false, 0);
1602}
1603
Steve Naroff09b266e2007-10-30 23:14:51 +00001604// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1605void RewriteTest::SynthMsgSendFunctionDecl() {
1606 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1607 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001608 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001609 assert(!argT.isNull() && "Can't find 'id' type");
1610 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001611 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001612 assert(!argT.isNull() && "Can't find 'SEL' type");
1613 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001614 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001615 &ArgTys[0], ArgTys.size(),
1616 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001617 MsgSendFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001618 msgSendIdent, msgSendType,
1619 FunctionDecl::Extern, false, 0);
1620}
1621
Steve Naroff874e2322007-11-15 10:28:18 +00001622// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1623void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1624 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1625 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattnerc63e6602008-03-15 21:32:50 +00001626 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, SourceLocation(),
1627 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001628 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1629 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1630 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001631 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001632 assert(!argT.isNull() && "Can't find 'SEL' type");
1633 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001634 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001635 &ArgTys[0], ArgTys.size(),
1636 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001637 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001638 msgSendIdent, msgSendType,
1639 FunctionDecl::Extern, false, 0);
1640}
1641
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001642// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1643void RewriteTest::SynthMsgSendStretFunctionDecl() {
1644 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1645 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001646 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001647 assert(!argT.isNull() && "Can't find 'id' type");
1648 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001649 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001650 assert(!argT.isNull() && "Can't find 'SEL' type");
1651 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001652 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001653 &ArgTys[0], ArgTys.size(),
1654 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001655 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001656 msgSendIdent, msgSendType,
1657 FunctionDecl::Extern, false, 0);
1658}
1659
1660// SynthMsgSendSuperStretFunctionDecl -
1661// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1662void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1663 IdentifierInfo *msgSendIdent =
1664 &Context->Idents.get("objc_msgSendSuper_stret");
1665 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattnerc63e6602008-03-15 21:32:50 +00001666 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, SourceLocation(),
1667 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001668 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1669 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1670 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001671 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001672 assert(!argT.isNull() && "Can't find 'SEL' type");
1673 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001674 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001675 &ArgTys[0], ArgTys.size(),
1676 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001677 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context,
1678 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001679 msgSendIdent, msgSendType,
1680 FunctionDecl::Extern, false, 0);
1681}
1682
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001683// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1684void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1685 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1686 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001687 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001688 assert(!argT.isNull() && "Can't find 'id' type");
1689 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001690 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001691 assert(!argT.isNull() && "Can't find 'SEL' type");
1692 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001693 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001694 &ArgTys[0], ArgTys.size(),
1695 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001696 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001697 msgSendIdent, msgSendType,
1698 FunctionDecl::Extern, false, 0);
1699}
1700
Steve Naroff09b266e2007-10-30 23:14:51 +00001701// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1702void RewriteTest::SynthGetClassFunctionDecl() {
1703 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1704 llvm::SmallVector<QualType, 16> ArgTys;
1705 ArgTys.push_back(Context->getPointerType(
1706 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001707 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001708 &ArgTys[0], ArgTys.size(),
1709 false /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001710 GetClassFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001711 getClassIdent, getClassType,
1712 FunctionDecl::Extern, false, 0);
1713}
1714
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001715// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1716void RewriteTest::SynthGetMetaClassFunctionDecl() {
1717 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1718 llvm::SmallVector<QualType, 16> ArgTys;
1719 ArgTys.push_back(Context->getPointerType(
1720 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001721 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001722 &ArgTys[0], ArgTys.size(),
1723 false /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001724 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001725 getClassIdent, getClassType,
1726 FunctionDecl::Extern, false, 0);
1727}
1728
Steve Naroffbeaf2992007-11-03 11:27:19 +00001729Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001730 QualType strType = getConstantStringStructType();
1731
1732 std::string S = "__NSConstantStringImpl_";
1733 S += utostr(NumObjCStringLiterals++);
1734
1735 std::string StrObjDecl = "static __NSConstantStringImpl " + S;
1736 StrObjDecl += " = __NSConstantStringImpl(";
1737 // The pretty printer for StringLiteral handles escape characters properly.
1738 std::ostringstream prettyBuf;
1739 Exp->getString()->printPretty(prettyBuf);
1740 StrObjDecl += prettyBuf.str();
1741 StrObjDecl += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001742 // The minus 2 removes the begin/end double quotes.
1743 StrObjDecl += utostr(prettyBuf.str().size()-2) + ");\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001744 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
1745 StrObjDecl.c_str(), StrObjDecl.size());
1746
Chris Lattnerc63e6602008-03-15 21:32:50 +00001747 FileVarDecl *NewVD = FileVarDecl::Create(*Context, SourceLocation(),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001748 &Context->Idents.get(S.c_str()), strType,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001749 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001750 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1751 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1752 Context->getPointerType(DRE->getType()),
1753 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001754 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001755 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001756 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001757 delete Exp;
1758 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001759}
1760
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001761ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001762 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001763 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1764
1765 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1766 if (!CE) return 0;
1767
1768 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1769 if (!DRE) return 0;
1770
1771 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1772 if (!PVD) return 0;
1773
1774 if (strcmp(PVD->getName(), "self") != 0)
1775 return 0;
1776
1777 // is this id<P1..> type?
1778 if (CE->getType()->isObjCQualifiedIdType())
1779 return 0;
1780 const PointerType *PT = CE->getType()->getAsPointerType();
1781 if (!PT) return 0;
1782
1783 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1784 if (!IT) return 0;
1785
1786 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1787 return 0;
1788
1789 return IT->getDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001790}
1791
1792// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1793QualType RewriteTest::getSuperStructType() {
1794 if (!SuperStructDecl) {
Chris Lattnerc63e6602008-03-15 21:32:50 +00001795 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct,
1796 SourceLocation(),
1797 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001798 QualType FieldTypes[2];
1799
1800 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001801 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001802 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001803 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001804 // Create fields
1805 FieldDecl *FieldDecls[2];
1806
1807 for (unsigned i = 0; i < 2; ++i)
1808 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1809
1810 SuperStructDecl->defineBody(FieldDecls, 4);
1811 }
1812 return Context->getTagDeclType(SuperStructDecl);
1813}
1814
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001815QualType RewriteTest::getConstantStringStructType() {
1816 if (!ConstantStringDecl) {
Chris Lattnerc63e6602008-03-15 21:32:50 +00001817 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct,
1818 SourceLocation(),
1819 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001820 QualType FieldTypes[4];
1821
1822 // struct objc_object *receiver;
1823 FieldTypes[0] = Context->getObjCIdType();
1824 // int flags;
1825 FieldTypes[1] = Context->IntTy;
1826 // char *str;
1827 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1828 // long length;
1829 FieldTypes[3] = Context->LongTy;
1830 // Create fields
1831 FieldDecl *FieldDecls[2];
1832
1833 for (unsigned i = 0; i < 4; ++i)
1834 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1835
1836 ConstantStringDecl->defineBody(FieldDecls, 4);
1837 }
1838 return Context->getTagDeclType(ConstantStringDecl);
1839}
1840
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001841Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001842 if (!SelGetUidFunctionDecl)
1843 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001844 if (!MsgSendFunctionDecl)
1845 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001846 if (!MsgSendSuperFunctionDecl)
1847 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001848 if (!MsgSendStretFunctionDecl)
1849 SynthMsgSendStretFunctionDecl();
1850 if (!MsgSendSuperStretFunctionDecl)
1851 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001852 if (!MsgSendFpretFunctionDecl)
1853 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001854 if (!GetClassFunctionDecl)
1855 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001856 if (!GetMetaClassFunctionDecl)
1857 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001858
Steve Naroff874e2322007-11-15 10:28:18 +00001859 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001860 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1861 // May need to use objc_msgSend_stret() as well.
1862 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001863 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001864 QualType resultType = mDecl->getResultType();
1865 if (resultType.getCanonicalType()->isStructureType()
1866 || resultType.getCanonicalType()->isUnionType())
1867 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001868 else if (resultType.getCanonicalType()->isRealFloatingType())
1869 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001870 }
Steve Naroff874e2322007-11-15 10:28:18 +00001871
Steve Naroff934f2762007-10-24 22:48:43 +00001872 // Synthesize a call to objc_msgSend().
1873 llvm::SmallVector<Expr*, 8> MsgExprs;
1874 IdentifierInfo *clsName = Exp->getClassName();
1875
1876 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1877 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001878 if (!strcmp(clsName->getName(), "super")) {
1879 MsgSendFlavor = MsgSendSuperFunctionDecl;
1880 if (MsgSendStretFlavor)
1881 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1882 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1883
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001884 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001885 CurMethodDecl->getClassInterface()->getSuperClass();
1886
1887 llvm::SmallVector<Expr*, 4> InitExprs;
1888
1889 // set the receiver to self, the first argument to all methods.
1890 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001891 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001892 SourceLocation()));
1893 llvm::SmallVector<Expr*, 8> ClsExprs;
1894 QualType argType = Context->getPointerType(Context->CharTy);
1895 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1896 SuperDecl->getIdentifier()->getLength(),
1897 false, argType, SourceLocation(),
1898 SourceLocation()));
1899 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1900 &ClsExprs[0],
1901 ClsExprs.size());
1902 // To turn off a warning, type-cast to 'id'
1903 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001904 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001905 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1906 // struct objc_super
1907 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001908 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001909
Steve Naroff23f41272008-03-11 18:14:26 +00001910 if (LangOpts.Microsoft) {
1911 SynthSuperContructorFunctionDecl();
1912 // Simulate a contructor call...
1913 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1914 superType, SourceLocation());
1915 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1916 superType, SourceLocation());
1917 } else {
1918 // (struct objc_super) { <exprs from above> }
1919 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1920 &InitExprs[0], InitExprs.size(),
1921 SourceLocation());
1922 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1923 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001924 // struct objc_super *
1925 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1926 Context->getPointerType(SuperRep->getType()),
1927 SourceLocation());
1928 MsgExprs.push_back(Unop);
1929 } else {
1930 llvm::SmallVector<Expr*, 8> ClsExprs;
1931 QualType argType = Context->getPointerType(Context->CharTy);
1932 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1933 clsName->getLength(),
1934 false, argType, SourceLocation(),
1935 SourceLocation()));
1936 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1937 &ClsExprs[0],
1938 ClsExprs.size());
1939 MsgExprs.push_back(Cls);
1940 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001941 } else { // instance message.
1942 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001943
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001944 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001945 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001946 if (MsgSendStretFlavor)
1947 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001948 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1949
1950 llvm::SmallVector<Expr*, 4> InitExprs;
1951
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001952 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001953 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001954 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001955
1956 llvm::SmallVector<Expr*, 8> ClsExprs;
1957 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001958 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1959 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001960 false, argType, SourceLocation(),
1961 SourceLocation()));
1962 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001963 &ClsExprs[0],
1964 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001965 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001966 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001967 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001968 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001969 // struct objc_super
1970 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00001971 Expr *SuperRep;
1972
1973 if (LangOpts.Microsoft) {
1974 SynthSuperContructorFunctionDecl();
1975 // Simulate a contructor call...
1976 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1977 superType, SourceLocation());
1978 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1979 superType, SourceLocation());
1980 } else {
1981 // (struct objc_super) { <exprs from above> }
1982 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1983 &InitExprs[0], InitExprs.size(),
1984 SourceLocation());
1985 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1986 }
Steve Naroff874e2322007-11-15 10:28:18 +00001987 // struct objc_super *
1988 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1989 Context->getPointerType(SuperRep->getType()),
1990 SourceLocation());
1991 MsgExprs.push_back(Unop);
1992 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001993 // Remove all type-casts because it may contain objc-style types; e.g.
1994 // Foo<Proto> *.
1995 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1996 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001997 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001998 MsgExprs.push_back(recExpr);
1999 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002000 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002001 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002002 llvm::SmallVector<Expr*, 8> SelExprs;
2003 QualType argType = Context->getPointerType(Context->CharTy);
2004 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2005 Exp->getSelector().getName().size(),
2006 false, argType, SourceLocation(),
2007 SourceLocation()));
2008 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2009 &SelExprs[0], SelExprs.size());
2010 MsgExprs.push_back(SelExp);
2011
2012 // Now push any user supplied arguments.
2013 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002014 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002015 // Make all implicit casts explicit...ICE comes in handy:-)
2016 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2017 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002018 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2019 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002020 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002021 }
2022 // Make id<P...> cast into an 'id' cast.
2023 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002024 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002025 while ((CE = dyn_cast<CastExpr>(userExpr)))
2026 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002027 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002028 userExpr, SourceLocation());
2029 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002030 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002031 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002032 // We've transferred the ownership to MsgExprs. Null out the argument in
2033 // the original expression, since we will delete it below.
2034 Exp->setArg(i, 0);
2035 }
Steve Naroffab972d32007-11-04 22:37:50 +00002036 // Generate the funky cast.
2037 CastExpr *cast;
2038 llvm::SmallVector<QualType, 8> ArgTypes;
2039 QualType returnType;
2040
2041 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002042 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2043 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2044 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002045 ArgTypes.push_back(Context->getObjCIdType());
2046 ArgTypes.push_back(Context->getObjCSelType());
2047 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002048 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00002049 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002050 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2051 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002052 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002053 ArgTypes.push_back(t);
2054 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002055 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2056 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002057 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002058 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002059 }
2060 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002061 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002062
2063 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002064 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2065 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002066
2067 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2068 // If we don't do this cast, we get the following bizarre warning/note:
2069 // xx.m:13: warning: function called through a non-compatible type
2070 // xx.m:13: note: if this code is reached, the program will abort
2071 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2072 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002073
Steve Naroffab972d32007-11-04 22:37:50 +00002074 // Now do the "normal" pointer to function cast.
2075 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002076 &ArgTypes[0], ArgTypes.size(),
2077 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00002078 castType = Context->getPointerType(castType);
2079 cast = new CastExpr(castType, cast, SourceLocation());
2080
2081 // Don't forget the parens to enforce the proper binding.
2082 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2083
2084 const FunctionType *FT = msgSendType->getAsFunctionType();
2085 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2086 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002087 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002088 if (MsgSendStretFlavor) {
2089 // We have the method which returns a struct/union. Must also generate
2090 // call to objc_msgSend_stret and hang both varieties on a conditional
2091 // expression which dictate which one to envoke depending on size of
2092 // method's return type.
2093
2094 // Create a reference to the objc_msgSend_stret() declaration.
2095 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2096 SourceLocation());
2097 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2098 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2099 SourceLocation());
2100 // Now do the "normal" pointer to function cast.
2101 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002102 &ArgTypes[0], ArgTypes.size(),
2103 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002104 castType = Context->getPointerType(castType);
2105 cast = new CastExpr(castType, cast, SourceLocation());
2106
2107 // Don't forget the parens to enforce the proper binding.
2108 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2109
2110 FT = msgSendType->getAsFunctionType();
2111 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2112 FT->getResultType(), SourceLocation());
2113
2114 // Build sizeof(returnType)
2115 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2116 returnType, Context->getSizeType(),
2117 SourceLocation(), SourceLocation());
2118 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2119 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2120 // For X86 it is more complicated and some kind of target specific routine
2121 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002122 unsigned IntSize =
2123 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002124 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2125 Context->IntTy,
2126 SourceLocation());
2127 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2128 BinaryOperator::LE,
2129 Context->IntTy,
2130 SourceLocation());
2131 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2132 ConditionalOperator *CondExpr =
2133 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002134 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002135 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002136 return ReplacingStmt;
2137}
2138
2139Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2140 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002141 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002142 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002143
Chris Lattnere64b7772007-10-24 16:57:36 +00002144 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002145 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002146}
2147
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002148/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2149/// call to objc_getProtocol("proto-name").
2150Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2151 if (!GetProtocolFunctionDecl)
2152 SynthGetProtocolFunctionDecl();
2153 // Create a call to objc_getProtocol("ProtocolName").
2154 llvm::SmallVector<Expr*, 8> ProtoExprs;
2155 QualType argType = Context->getPointerType(Context->CharTy);
2156 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2157 strlen(Exp->getProtocol()->getName()),
2158 false, argType, SourceLocation(),
2159 SourceLocation()));
2160 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2161 &ProtoExprs[0],
2162 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002163 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002164 delete Exp;
2165 return ProtoExp;
2166
2167}
2168
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002169/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002170/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002171void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002172 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002173 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2174 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002175 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002176 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002177 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002178 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00002179 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00002180 SourceLocation LocStart = CDecl->getLocStart();
2181 SourceLocation LocEnd = CDecl->getLocEnd();
2182
2183 const char *startBuf = SM->getCharacterData(LocStart);
2184 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002185 // If no ivars and no root or if its root, directly or indirectly,
2186 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002187 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002188 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002189 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002190 return;
2191 }
2192
2193 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002194 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002195 Result += "\nstruct ";
2196 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002197 if (LangOpts.Microsoft)
2198 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002199
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002200 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002201 const char *cursor = strchr(startBuf, '{');
2202 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002203 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002204
2205 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002206 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002207 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002208 Result = "\n struct ";
2209 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002210 Result += "_IMPL ";
2211 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002212 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002213
2214 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002215 SourceLocation OnePastCurly =
2216 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2217 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002218 }
2219 cursor++; // past '{'
2220
2221 // Now comment out any visibility specifiers.
2222 while (cursor < endBuf) {
2223 if (*cursor == '@') {
2224 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002225 // Skip whitespace.
2226 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2227 /*scan*/;
2228
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002229 // FIXME: presence of @public, etc. inside comment results in
2230 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002231 if (!strncmp(cursor, "public", strlen("public")) ||
2232 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002233 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002234 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002235 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002236 // FIXME: If there are cases where '<' is used in ivar declaration part
2237 // of user code, then scan the ivar list and use needToScanForQualifiers
2238 // for type checking.
2239 else if (*cursor == '<') {
2240 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002241 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002242 cursor = strchr(cursor, '>');
2243 cursor++;
2244 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002245 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002246 }
Steve Narofffea763e82007-11-14 19:25:57 +00002247 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002248 }
Steve Narofffea763e82007-11-14 19:25:57 +00002249 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002250 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002251 } else { // we don't have any instance variables - insert super struct.
2252 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2253 Result += " {\n struct ";
2254 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002255 Result += "_IMPL ";
2256 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002257 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002258 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002259 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002260 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002261 if (!ObjCSynthesizedStructs.insert(CDecl))
2262 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002263}
2264
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002265// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002266/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002267void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002268 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002269 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002270 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002271 const char *ClassName,
2272 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002273 if (MethodBegin == MethodEnd) return;
2274
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002275 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002276 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002277 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002278 SEL _cmd;
2279 char *method_types;
2280 void *_imp;
2281 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002282 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002283 Result += "\nstruct _objc_method {\n";
2284 Result += "\tSEL _cmd;\n";
2285 Result += "\tchar *method_types;\n";
2286 Result += "\tvoid *_imp;\n";
2287 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002288
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002289 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002290 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002291
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002292 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002293
2294 /* struct {
2295 struct _objc_method_list *next_method;
2296 int method_count;
2297 struct _objc_method method_list[];
2298 }
2299 */
2300 Result += "\nstatic struct {\n";
2301 Result += "\tstruct _objc_method_list *next_method;\n";
2302 Result += "\tint method_count;\n";
2303 Result += "\tstruct _objc_method method_list[";
2304 Result += utostr(MethodEnd-MethodBegin);
2305 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002306 Result += prefix;
2307 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2308 Result += "_METHODS_";
2309 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002310 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002311 Result += IsInstanceMethod ? "inst" : "cls";
2312 Result += "_meth\")))= ";
2313 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002314
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002315 Result += "\t,{{(SEL)\"";
2316 Result += (*MethodBegin)->getSelector().getName().c_str();
2317 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002318 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002319 Result += "\", \"";
2320 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002321 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002322 Result += MethodInternalNames[*MethodBegin];
2323 Result += "}\n";
2324 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2325 Result += "\t ,{(SEL)\"";
2326 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002327 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002328 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002329 Result += "\", \"";
2330 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002331 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002332 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002333 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002334 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002335 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002336}
2337
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002338/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2339void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002340 int NumProtocols,
2341 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002342 const char *ClassName,
2343 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002344 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002345 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002346 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002347 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002348 // Output struct protocol_methods holder of method selector and type.
2349 if (!objc_protocol_methods &&
2350 (PDecl->getNumInstanceMethods() > 0
2351 || PDecl->getNumClassMethods() > 0)) {
2352 /* struct protocol_methods {
2353 SEL _cmd;
2354 char *method_types;
2355 }
2356 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002357 Result += "\nstruct protocol_methods {\n";
2358 Result += "\tSEL _cmd;\n";
2359 Result += "\tchar *method_types;\n";
2360 Result += "};\n";
2361
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002362 objc_protocol_methods = true;
2363 }
2364 int NumMethods = PDecl->getNumInstanceMethods();
2365 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002366 /* struct _objc_protocol_method_list {
2367 int protocol_method_count;
2368 struct protocol_methods protocols[];
2369 }
2370 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002371 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002372 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002373 Result += "\tstruct protocol_methods protocols[";
2374 Result += utostr(NumMethods);
2375 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002376 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002377 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002378 "{\n\t" + utostr(NumMethods) + "\n";
2379
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002380 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002381 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002382 E = PDecl->instmeth_end(); I != E; ++I) {
2383 if (I == PDecl->instmeth_begin())
2384 Result += "\t ,{{(SEL)\"";
2385 else
2386 Result += "\t ,{(SEL)\"";
2387 Result += (*I)->getSelector().getName().c_str();
2388 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002389 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002390 Result += "\", \"";
2391 Result += MethodTypeString;
2392 Result += "\"}\n";
2393 }
2394 Result += "\t }\n};\n";
2395 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002396
2397 // Output class methods declared in this protocol.
2398 NumMethods = PDecl->getNumClassMethods();
2399 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002400 /* struct _objc_protocol_method_list {
2401 int protocol_method_count;
2402 struct protocol_methods protocols[];
2403 }
2404 */
2405 Result += "\nstatic struct {\n";
2406 Result += "\tint protocol_method_count;\n";
2407 Result += "\tstruct protocol_methods protocols[";
2408 Result += utostr(NumMethods);
2409 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002410 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002411 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002412 "{\n\t";
2413 Result += utostr(NumMethods);
2414 Result += "\n";
2415
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002416 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002417 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002418 E = PDecl->classmeth_end(); I != E; ++I) {
2419 if (I == PDecl->classmeth_begin())
2420 Result += "\t ,{{(SEL)\"";
2421 else
2422 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002423 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002424 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002425 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002426 Result += "\", \"";
2427 Result += MethodTypeString;
2428 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002429 }
2430 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002431 }
2432 // Output:
2433 /* struct _objc_protocol {
2434 // Objective-C 1.0 extensions
2435 struct _objc_protocol_extension *isa;
2436 char *protocol_name;
2437 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002438 struct _objc_protocol_method_list *instance_methods;
2439 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002440 };
2441 */
2442 static bool objc_protocol = false;
2443 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002444 Result += "\nstruct _objc_protocol {\n";
2445 Result += "\tstruct _objc_protocol_extension *isa;\n";
2446 Result += "\tchar *protocol_name;\n";
2447 Result += "\tstruct _objc_protocol **protocol_list;\n";
2448 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2449 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2450 Result += "};\n";
2451
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002452 objc_protocol = true;
2453 }
2454
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002455 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2456 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002457 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002458 "{\n\t0, \"";
2459 Result += PDecl->getName();
2460 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002461 if (PDecl->getNumInstanceMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002462 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002463 Result += PDecl->getName();
2464 Result += ", ";
2465 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002466 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002467 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002468 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002469 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002470 Result += PDecl->getName();
2471 Result += "\n";
2472 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002473 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002474 Result += "0\n";
2475 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002476 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002477 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002478 /* struct _objc_protocol_list {
2479 struct _objc_protocol_list *next;
2480 int protocol_count;
2481 struct _objc_protocol *class_protocols[];
2482 }
2483 */
2484 Result += "\nstatic struct {\n";
2485 Result += "\tstruct _objc_protocol_list *next;\n";
2486 Result += "\tint protocol_count;\n";
2487 Result += "\tstruct _objc_protocol *class_protocols[";
2488 Result += utostr(NumProtocols);
2489 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002490 Result += prefix;
2491 Result += "_PROTOCOLS_";
2492 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002493 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002494 "{\n\t0, ";
2495 Result += utostr(NumProtocols);
2496 Result += "\n";
2497
2498 Result += "\t,{&_OBJC_PROTOCOL_";
2499 Result += Protocols[0]->getName();
2500 Result += " \n";
2501
2502 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002503 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002504 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002505 Result += PDecl->getName();
2506 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002507 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002508 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002509 }
2510}
2511
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002512/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002513/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002514void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002515 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002516 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002517 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002518 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002519 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2520 CDecl = CDecl->getNextClassCategory())
2521 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2522 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002523
Chris Lattnereb44eee2007-12-23 01:40:15 +00002524 std::string FullCategoryName = ClassDecl->getName();
2525 FullCategoryName += '_';
2526 FullCategoryName += IDecl->getName();
2527
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002528 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002529 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002530 true, "CATEGORY_", FullCategoryName.c_str(),
2531 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002532
2533 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002534 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002535 false, "CATEGORY_", FullCategoryName.c_str(),
2536 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002537
2538 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002539 // Null CDecl is case of a category implementation with no category interface
2540 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002541 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002542 CDecl->getNumReferencedProtocols(),
2543 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002544 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002545
2546 /* struct _objc_category {
2547 char *category_name;
2548 char *class_name;
2549 struct _objc_method_list *instance_methods;
2550 struct _objc_method_list *class_methods;
2551 struct _objc_protocol_list *protocols;
2552 // Objective-C 1.0 extensions
2553 uint32_t size; // sizeof (struct _objc_category)
2554 struct _objc_property_list *instance_properties; // category's own
2555 // @property decl.
2556 };
2557 */
2558
2559 static bool objc_category = false;
2560 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002561 Result += "\nstruct _objc_category {\n";
2562 Result += "\tchar *category_name;\n";
2563 Result += "\tchar *class_name;\n";
2564 Result += "\tstruct _objc_method_list *instance_methods;\n";
2565 Result += "\tstruct _objc_method_list *class_methods;\n";
2566 Result += "\tstruct _objc_protocol_list *protocols;\n";
2567 Result += "\tunsigned int size;\n";
2568 Result += "\tstruct _objc_property_list *instance_properties;\n";
2569 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002570 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002571 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002572 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2573 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002574 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002575 Result += IDecl->getName();
2576 Result += "\"\n\t, \"";
2577 Result += ClassDecl->getName();
2578 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002579
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002580 if (IDecl->getNumInstanceMethods() > 0) {
2581 Result += "\t, (struct _objc_method_list *)"
2582 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2583 Result += FullCategoryName;
2584 Result += "\n";
2585 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002586 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002587 Result += "\t, 0\n";
2588 if (IDecl->getNumClassMethods() > 0) {
2589 Result += "\t, (struct _objc_method_list *)"
2590 "&_OBJC_CATEGORY_CLASS_METHODS_";
2591 Result += FullCategoryName;
2592 Result += "\n";
2593 }
2594 else
2595 Result += "\t, 0\n";
2596
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002597 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002598 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2599 Result += FullCategoryName;
2600 Result += "\n";
2601 }
2602 else
2603 Result += "\t, 0\n";
2604 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002605}
2606
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002607/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2608/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002609void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2610 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002611 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002612 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002613 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002614 if (LangOpts.Microsoft)
2615 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002616 Result += ", ";
2617 Result += ivar->getName();
2618 Result += ")";
2619}
2620
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002621//===----------------------------------------------------------------------===//
2622// Meta Data Emission
2623//===----------------------------------------------------------------------===//
2624
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002625void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002626 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002627 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002628
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002629 // Explictly declared @interface's are already synthesized.
2630 if (CDecl->ImplicitInterfaceDecl()) {
2631 // FIXME: Implementation of a class with no @interface (legacy) doese not
2632 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002633 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002634 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002635
Chris Lattnerbe6df082007-12-12 07:56:42 +00002636 // Build _objc_ivar_list metadata for classes ivars if needed
2637 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2638 ? IDecl->getImplDeclNumIvars()
2639 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002640 if (NumIvars > 0) {
2641 static bool objc_ivar = false;
2642 if (!objc_ivar) {
2643 /* struct _objc_ivar {
2644 char *ivar_name;
2645 char *ivar_type;
2646 int ivar_offset;
2647 };
2648 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002649 Result += "\nstruct _objc_ivar {\n";
2650 Result += "\tchar *ivar_name;\n";
2651 Result += "\tchar *ivar_type;\n";
2652 Result += "\tint ivar_offset;\n";
2653 Result += "};\n";
2654
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002655 objc_ivar = true;
2656 }
2657
Steve Naroff946a6932008-03-11 00:12:29 +00002658 /* struct {
2659 int ivar_count;
2660 struct _objc_ivar ivar_list[nIvars];
2661 };
2662 */
2663 Result += "\nstatic struct {\n";
2664 Result += "\tint ivar_count;\n";
2665 Result += "\tstruct _objc_ivar ivar_list[";
2666 Result += utostr(NumIvars);
2667 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002668 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002669 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002670 "{\n\t";
2671 Result += utostr(NumIvars);
2672 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002673
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002674 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002675 if (IDecl->getImplDeclNumIvars() > 0) {
2676 IVI = IDecl->ivar_begin();
2677 IVE = IDecl->ivar_end();
2678 } else {
2679 IVI = CDecl->ivar_begin();
2680 IVE = CDecl->ivar_end();
2681 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002682 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002683 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002684 Result += "\", \"";
2685 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002686 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2687 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002688 Result += StrEncoding;
2689 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002690 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002691 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002692 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002693 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002694 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002695 Result += "\", \"";
2696 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002697 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2698 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002699 Result += StrEncoding;
2700 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002701 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002702 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002703 }
2704
2705 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002706 }
2707
2708 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002709 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002710 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002711
2712 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002713 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002714 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002715
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002716 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002717 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002718 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002719 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002720
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002721
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002722 // Declaration of class/meta-class metadata
2723 /* struct _objc_class {
2724 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002725 const char *super_class_name;
2726 char *name;
2727 long version;
2728 long info;
2729 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002730 struct _objc_ivar_list *ivars;
2731 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002732 struct objc_cache *cache;
2733 struct objc_protocol_list *protocols;
2734 const char *ivar_layout;
2735 struct _objc_class_ext *ext;
2736 };
2737 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002738 static bool objc_class = false;
2739 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002740 Result += "\nstruct _objc_class {\n";
2741 Result += "\tstruct _objc_class *isa;\n";
2742 Result += "\tconst char *super_class_name;\n";
2743 Result += "\tchar *name;\n";
2744 Result += "\tlong version;\n";
2745 Result += "\tlong info;\n";
2746 Result += "\tlong instance_size;\n";
2747 Result += "\tstruct _objc_ivar_list *ivars;\n";
2748 Result += "\tstruct _objc_method_list *methods;\n";
2749 Result += "\tstruct objc_cache *cache;\n";
2750 Result += "\tstruct _objc_protocol_list *protocols;\n";
2751 Result += "\tconst char *ivar_layout;\n";
2752 Result += "\tstruct _objc_class_ext *ext;\n";
2753 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002754 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002755 }
2756
2757 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002758 ObjCInterfaceDecl *RootClass = 0;
2759 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002760 while (SuperClass) {
2761 RootClass = SuperClass;
2762 SuperClass = SuperClass->getSuperClass();
2763 }
2764 SuperClass = CDecl->getSuperClass();
2765
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002766 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2767 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002768 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002769 "{\n\t(struct _objc_class *)\"";
2770 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2771 Result += "\"";
2772
2773 if (SuperClass) {
2774 Result += ", \"";
2775 Result += SuperClass->getName();
2776 Result += "\", \"";
2777 Result += CDecl->getName();
2778 Result += "\"";
2779 }
2780 else {
2781 Result += ", 0, \"";
2782 Result += CDecl->getName();
2783 Result += "\"";
2784 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002785 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002786 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002787 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002788 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002789 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002790 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002791 Result += "\n";
2792 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002793 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002794 Result += ", 0\n";
2795 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002796 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002797 Result += CDecl->getName();
2798 Result += ",0,0\n";
2799 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002800 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002801 Result += "\t,0,0,0,0\n";
2802 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002803
2804 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002805 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2806 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002807 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002808 "{\n\t&_OBJC_METACLASS_";
2809 Result += CDecl->getName();
2810 if (SuperClass) {
2811 Result += ", \"";
2812 Result += SuperClass->getName();
2813 Result += "\", \"";
2814 Result += CDecl->getName();
2815 Result += "\"";
2816 }
2817 else {
2818 Result += ", 0, \"";
2819 Result += CDecl->getName();
2820 Result += "\"";
2821 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002822 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002823 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002824 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002825 Result += ",0";
2826 else {
2827 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002828 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002829 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002830 if (LangOpts.Microsoft)
2831 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002832 Result += ")";
2833 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002834 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002835 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002836 Result += CDecl->getName();
2837 Result += "\n\t";
2838 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002839 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002840 Result += ",0";
2841 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002842 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002843 Result += CDecl->getName();
2844 Result += ", 0\n\t";
2845 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002846 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002847 Result += ",0,0";
2848 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002849 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002850 Result += CDecl->getName();
2851 Result += ", 0,0\n";
2852 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002853 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002854 Result += ",0,0,0\n";
2855 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002856}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002857
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002858/// RewriteImplementations - This routine rewrites all method implementations
2859/// and emits meta-data.
2860
2861void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002862 int ClsDefCount = ClassImplementation.size();
2863 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002864
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002865 if (ClsDefCount == 0 && CatDefCount == 0)
2866 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002867 // Rewrite implemented methods
2868 for (int i = 0; i < ClsDefCount; i++)
2869 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002870
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002871 for (int i = 0; i < CatDefCount; i++)
2872 RewriteImplementationDecl(CategoryImplementation[i]);
2873
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002874 // This is needed for use of offsetof
2875 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002876
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002877 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002878 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002879 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002880
2881 // For each implemented category, write out all its meta data.
2882 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002883 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002884
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002885 // Write objc_symtab metadata
2886 /*
2887 struct _objc_symtab
2888 {
2889 long sel_ref_cnt;
2890 SEL *refs;
2891 short cls_def_cnt;
2892 short cat_def_cnt;
2893 void *defs[cls_def_cnt + cat_def_cnt];
2894 };
2895 */
2896
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002897 Result += "\nstruct _objc_symtab {\n";
2898 Result += "\tlong sel_ref_cnt;\n";
2899 Result += "\tSEL *refs;\n";
2900 Result += "\tshort cls_def_cnt;\n";
2901 Result += "\tshort cat_def_cnt;\n";
2902 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2903 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002904
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002905 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002906 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002907 Result += "\t0, 0, " + utostr(ClsDefCount)
2908 + ", " + utostr(CatDefCount) + "\n";
2909 for (int i = 0; i < ClsDefCount; i++) {
2910 Result += "\t,&_OBJC_CLASS_";
2911 Result += ClassImplementation[i]->getName();
2912 Result += "\n";
2913 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002914
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002915 for (int i = 0; i < CatDefCount; i++) {
2916 Result += "\t,&_OBJC_CATEGORY_";
2917 Result += CategoryImplementation[i]->getClassInterface()->getName();
2918 Result += "_";
2919 Result += CategoryImplementation[i]->getName();
2920 Result += "\n";
2921 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002922
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002923 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002924
2925 // Write objc_module metadata
2926
2927 /*
2928 struct _objc_module {
2929 long version;
2930 long size;
2931 const char *name;
2932 struct _objc_symtab *symtab;
2933 }
2934 */
2935
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002936 Result += "\nstruct _objc_module {\n";
2937 Result += "\tlong version;\n";
2938 Result += "\tlong size;\n";
2939 Result += "\tconst char *name;\n";
2940 Result += "\tstruct _objc_symtab *symtab;\n";
2941 Result += "};\n\n";
2942 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00002943 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002944 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2945 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002946 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002947
2948 if (LangOpts.Microsoft) {
2949 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2950 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2951 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2952 Result += "&_OBJC_MODULES;\n";
2953 Result += "#pragma data_seg(pop)\n\n";
2954 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002955}
Chris Lattner311ff022007-10-16 22:36:42 +00002956