blob: 74fbab76cd1618f166727ecfdc4cefd71a5eaa75 [file] [log] [blame]
Chris Lattnerb429ae42007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb429ae42007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff1c46cf12008-01-28 21:34:52 +000025#include "llvm/Support/CommandLine.h"
Chris Lattner673f2bd2008-03-22 00:08:40 +000026#include "llvm/System/Path.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000027#include <sstream>
Chris Lattner673f2bd2008-03-22 00:08:40 +000028#include <fstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000029using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000031
Steve Naroff1c46cf12008-01-28 21:34:52 +000032static llvm::cl::opt<bool>
33SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
34 llvm::cl::desc("Silence ObjC rewriting warnings"));
35
Chris Lattnerb429ae42007-10-11 00:43:27 +000036namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000037 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000038 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000039 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000040 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000041 unsigned RewriteFailedDiag;
42
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000043 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000044 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000045 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000046 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000047 SourceLocation LastIncLoc;
Ted Kremenek42730c52008-01-07 19:49:32 +000048 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
49 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
50 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
51 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
52 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000053 llvm::SmallVector<Stmt *, 32> Stmts;
54 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian248db262008-01-22 22:44:46 +000055 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffe9780582007-10-23 23:50:29 +000056
Steve Naroff47e7fa22008-03-15 00:55:56 +000057 unsigned NumObjCStringLiterals;
58
Steve Naroffe9780582007-10-23 23:50:29 +000059 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000060 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000061 FunctionDecl *MsgSendStretFunctionDecl;
62 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000063 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000064 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000065 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000066 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000067 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000068 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000069 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000070
Steve Naroff0add5d22007-11-03 11:27:19 +000071 // ObjC string constant support.
72 FileVarDecl *ConstantStringClassReference;
73 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000074
Fariborz Jahanian22277422008-01-16 00:09:11 +000075 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000076 int BcLabelCount;
77
Steve Naroff764c1ae2007-11-15 10:28:18 +000078 // Needed for super.
Ted Kremenek42730c52008-01-07 19:49:32 +000079 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000080 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000081 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000082
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000083 // Needed for header files being rewritten
84 bool IsHeader;
85
Chris Lattner673f2bd2008-03-22 00:08:40 +000086 std::ostream &OutFile;
87
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000088 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000089 public:
Chris Lattner12499682008-01-31 19:38:44 +000090 void Initialize(ASTContext &context);
91
Chris Lattner569faa62007-10-11 18:38:32 +000092
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000093 // Top Level Driver code.
94 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +000095 void HandleDeclInMainFile(Decl *D);
Chris Lattner673f2bd2008-03-22 00:08:40 +000096 RewriteTest(bool isHeader, std::ostream &outFile,
97 Diagnostic &D, const LangOptions &LOpts)
98 : Diags(D), LangOpts(LOpts), OutFile(outFile) {
Steve Naroff53b6f4c2008-01-30 19:17:43 +000099 IsHeader = isHeader;
Steve Naroff1c46cf12008-01-28 21:34:52 +0000100 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
101 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000102 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000103 ~RewriteTest();
Chris Lattnerb1548372008-01-31 19:37:57 +0000104
105 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattner6216f292008-01-31 19:42:41 +0000106 // If replacement succeeded or warning disabled return with no warning.
107 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerb1548372008-01-31 19:37:57 +0000108 return;
109
Chris Lattnerb1548372008-01-31 19:37:57 +0000110 SourceRange Range = Old->getSourceRange();
111 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
112 0, 0, &Range, 1);
113 }
114
Chris Lattner6216f292008-01-31 19:42:41 +0000115 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000116 // If insertion succeeded or warning disabled return with no warning.
Chris Lattner6216f292008-01-31 19:42:41 +0000117 if (!Rewrite.InsertText(Loc, StrData, StrLen) ||
118 SilenceRewriteMacroWarning)
119 return;
120
121 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
122 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000123
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000124 void RemoveText(SourceLocation Loc, unsigned StrLen) {
125 // If removal succeeded or warning disabled return with no warning.
126 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
127 return;
128
129 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
130 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000131
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000132 void ReplaceText(SourceLocation Start, unsigned OrigLength,
133 const char *NewStr, unsigned NewLength) {
134 // If removal succeeded or warning disabled return with no warning.
135 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
136 SilenceRewriteMacroWarning)
137 return;
138
139 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
140 }
141
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000142 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000143 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000144 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000145 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000146 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
147 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000148 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000149 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
150 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
151 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
152 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
153 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattnercffe3662008-03-16 21:23:50 +0000154 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000155 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000156 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000157 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000158 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000159 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000160 QualType getConstantStringStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000161
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000162 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000163 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000164 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000165 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000166 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000167 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000168 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000169 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000170 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000171 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000172 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
173 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
174 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000175 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
176 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000177 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
178 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000179 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000180 Stmt *RewriteBreakStmt(BreakStmt *S);
181 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000182 void SynthCountByEnumWithState(std::string &buf);
183
Steve Naroff02a82aa2007-10-30 23:14:51 +0000184 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000185 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000186 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000187 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000188 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000189 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000190 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000191 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000192 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000193 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000194
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000195 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000196 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000197 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000198
Ted Kremenek42730c52008-01-07 19:49:32 +0000199 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000200 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000201
Ted Kremenek42730c52008-01-07 19:49:32 +0000202 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
203 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000204 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000205 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000206 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000207 const char *ClassName,
208 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000209
Ted Kremenek42730c52008-01-07 19:49:32 +0000210 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000211 int NumProtocols,
212 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000213 const char *ClassName,
214 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000215 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000216 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000217 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
218 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000219 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000220 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000221 };
222}
223
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000224static bool IsHeaderFile(const std::string &Filename) {
225 std::string::size_type DotPos = Filename.rfind('.');
226
227 if (DotPos == std::string::npos) {
228 // no file extension
229 return false;
230 }
231
232 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
233 // C header: .h
234 // C++ header: .hh or .H;
235 return Ext == "h" || Ext == "hh" || Ext == "H";
236}
237
238ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000239 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000240 Diagnostic &Diags,
241 const LangOptions &LOpts) {
Chris Lattner673f2bd2008-03-22 00:08:40 +0000242 // Create the output file.
243
244 std::ostream *Out;
245 if (OutFile == "-") {
246 Out = llvm::cout.stream();
247 } else if (!OutFile.empty()) {
248 Out = new std::ofstream(OutFile.c_str(),
249 std::ios_base::binary|std::ios_base::out);
250 } else if (InFile == "-") {
251 Out = llvm::cout.stream();
252 } else {
253 llvm::sys::Path Path(InFile);
254 Path.eraseSuffix();
255 Path.appendSuffix("cpp");
256 Out = new std::ofstream(Path.toString().c_str(),
257 std::ios_base::binary|std::ios_base::out);
258 }
259
260 return new RewriteTest(IsHeaderFile(InFile), *Out, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000261}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000262
Chris Lattner12499682008-01-31 19:38:44 +0000263void RewriteTest::Initialize(ASTContext &context) {
264 Context = &context;
265 SM = &Context->getSourceManager();
266 MsgSendFunctionDecl = 0;
267 MsgSendSuperFunctionDecl = 0;
268 MsgSendStretFunctionDecl = 0;
269 MsgSendSuperStretFunctionDecl = 0;
270 MsgSendFpretFunctionDecl = 0;
271 GetClassFunctionDecl = 0;
272 GetMetaClassFunctionDecl = 0;
273 SelGetUidFunctionDecl = 0;
274 CFStringFunctionDecl = 0;
275 GetProtocolFunctionDecl = 0;
276 ConstantStringClassReference = 0;
277 NSStringRecord = 0;
278 CurMethodDecl = 0;
279 SuperStructDecl = 0;
280 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000281 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000282 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000283
284 // Get the ID and start/end of the main file.
285 MainFileID = SM->getMainFileID();
286 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
287 MainFileStart = MainBuf->getBufferStart();
288 MainFileEnd = MainBuf->getBufferEnd();
289
290
291 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000292
Chris Lattner12499682008-01-31 19:38:44 +0000293 // declaring objc_selector outside the parameter list removes a silly
294 // scope related warning...
Steve Naroffde0da102008-03-10 23:16:54 +0000295 std::string S = "#pragma once\n";
296 S += "struct objc_selector; struct objc_class;\n";
297 S += "#ifndef OBJC_SUPER\n";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000298 S += "struct objc_super { struct objc_object *object; ";
299 S += "struct objc_object *superClass; ";
300 if (LangOpts.Microsoft) {
301 // Add a constructor for creating temporary objects.
302 S += "objc_super(struct objc_object *o, struct objc_object *s) : ";
303 S += "object(o), superClass(s) {} ";
304 }
305 S += "};\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000306 S += "#define OBJC_SUPER\n";
307 S += "#endif\n";
308 S += "#ifndef _REWRITER_typedef_Protocol\n";
309 S += "typedef struct objc_object Protocol;\n";
310 S += "#define _REWRITER_typedef_Protocol\n";
311 S += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000312 if (LangOpts.Microsoft)
313 S += "extern \"C\" {\n";
314 S += "struct objc_object *objc_msgSend";
Steve Naroffde0da102008-03-10 23:16:54 +0000315 S += "(struct objc_object *, struct objc_selector *, ...);\n";
316 S += "extern struct objc_object *objc_msgSendSuper";
317 S += "(struct objc_super *, struct objc_selector *, ...);\n";
318 S += "extern struct objc_object *objc_msgSend_stret";
319 S += "(struct objc_object *, struct objc_selector *, ...);\n";
320 S += "extern struct objc_object *objc_msgSendSuper_stret";
321 S += "(struct objc_super *, struct objc_selector *, ...);\n";
322 S += "extern struct objc_object *objc_msgSend_fpret";
323 S += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000324 S += "struct objc_object *objc_getClass";
Steve Naroffde0da102008-03-10 23:16:54 +0000325 S += "(const char *);\n";
326 S += "extern struct objc_object *objc_getMetaClass";
327 S += "(const char *);\n";
328 S += "extern void objc_exception_throw(struct objc_object *);\n";
329 S += "extern void objc_exception_try_enter(void *);\n";
330 S += "extern void objc_exception_try_exit(void *);\n";
331 S += "extern struct objc_object *objc_exception_extract(void *);\n";
332 S += "extern int objc_exception_match";
333 S += "(struct objc_class *, struct objc_object *, ...);\n";
334 S += "extern Protocol *objc_getProtocol(const char *);\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000335 if (LangOpts.Microsoft)
336 S += "} // end extern \"C\"\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000337 S += "#include <objc/objc.h>\n";
338 S += "#ifndef __FASTENUMERATIONSTATE\n";
339 S += "struct __objcFastEnumerationState {\n\t";
340 S += "unsigned long state;\n\t";
341 S += "id *itemsPtr;\n\t";
342 S += "unsigned long *mutationsPtr;\n\t";
343 S += "unsigned long extra[5];\n};\n";
344 S += "#define __FASTENUMERATIONSTATE\n";
345 S += "#endif\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +0000346 S += "#ifndef __NSCONSTANTSTRINGIMPL\n";
347 S += "struct __NSConstantStringImpl {\n";
Steve Naroffe0766ed2008-03-18 01:47:18 +0000348 S += " int *isa;\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +0000349 S += " int flags;\n";
350 S += " char *str;\n";
351 S += " long length;\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +0000352 S += "};\n";
Steve Naroffe0766ed2008-03-18 01:47:18 +0000353 S += "extern int __CFConstantStringClassReference[];\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +0000354 S += "#define __NSCONSTANTSTRINGIMPL\n";
355 S += "#endif\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000356 if (LangOpts.Microsoft)
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000357 S += "#define __attribute__(X)\n";
Chris Lattner12499682008-01-31 19:38:44 +0000358 if (IsHeader) {
359 // insert the whole string when rewriting a header file
Steve Naroffde0da102008-03-10 23:16:54 +0000360 InsertText(SourceLocation::getFileLoc(MainFileID, 0), S.c_str(), S.size());
Chris Lattner12499682008-01-31 19:38:44 +0000361 }
362 else {
363 // Not rewriting header, exclude the #pragma once pragma
Steve Naroffde0da102008-03-10 23:16:54 +0000364 const char *p = S.c_str() + strlen("#pragma once\n");
Chris Lattner6216f292008-01-31 19:42:41 +0000365 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner12499682008-01-31 19:38:44 +0000366 }
367}
368
369
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000370//===----------------------------------------------------------------------===//
371// Top Level Driver Code
372//===----------------------------------------------------------------------===//
373
Chris Lattner569faa62007-10-11 18:38:32 +0000374void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000375 // Two cases: either the decl could be in the main file, or it could be in a
376 // #included file. If the former, rewrite it now. If the later, check to see
377 // if we rewrote the #include/#import.
378 SourceLocation Loc = D->getLocation();
379 Loc = SM->getLogicalLoc(Loc);
380
381 // If this is for a builtin, ignore it.
382 if (Loc.isInvalid()) return;
383
Steve Naroffe9780582007-10-23 23:50:29 +0000384 // Look for built-in declarations that we need to refer during the rewrite.
385 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000386 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000387 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
388 // declared in <Foundation/NSString.h>
389 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
390 ConstantStringClassReference = FVD;
391 return;
392 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000393 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000394 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000395 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000396 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000397 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000398 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000399 } else if (ObjCForwardProtocolDecl *FP =
400 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000401 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000402 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000403 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000404 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
405 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000406}
407
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000408/// HandleDeclInMainFile - This is called for each top-level decl defined in the
409/// main file of the input.
410void RewriteTest::HandleDeclInMainFile(Decl *D) {
411 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
412 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000413 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000414
Ted Kremenek42730c52008-01-07 19:49:32 +0000415 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000416 if (Stmt *Body = MD->getBody()) {
417 //Body->dump();
418 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000419 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000420 CurMethodDecl = 0;
421 }
Steve Naroff18c83382007-11-13 23:01:27 +0000422 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000423 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000424 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000425 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000426 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000427 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000428 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000429 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000430 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000431 if (VD->getInit())
432 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
433 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000434 // Nothing yet.
435}
436
437RewriteTest::~RewriteTest() {
438 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000439
440 // Rewrite tabs if we care.
441 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000442
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000443 RewriteInclude();
444
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000445 // Rewrite Objective-c meta data*
446 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000447 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000448
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000449 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
450 // we are done.
451 if (const RewriteBuffer *RewriteBuf =
452 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000453 //printf("Changed:\n");
Chris Lattner673f2bd2008-03-22 00:08:40 +0000454 OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000455 } else {
Chris Lattner673f2bd2008-03-22 00:08:40 +0000456 fprintf(stderr, "No changes\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000457 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000458 // Emit metadata.
Chris Lattner673f2bd2008-03-22 00:08:40 +0000459 OutFile << ResultStr;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000460}
461
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000462//===----------------------------------------------------------------------===//
463// Syntactic (non-AST) Rewriting Code
464//===----------------------------------------------------------------------===//
465
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000466void RewriteTest::RewriteInclude() {
467 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
468 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
469 const char *MainBufStart = MainBuf.first;
470 const char *MainBufEnd = MainBuf.second;
471 size_t ImportLen = strlen("import");
472 size_t IncludeLen = strlen("include");
473
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000474 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000475 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
476 if (*BufPtr == '#') {
477 if (++BufPtr == MainBufEnd)
478 return;
479 while (*BufPtr == ' ' || *BufPtr == '\t')
480 if (++BufPtr == MainBufEnd)
481 return;
482 if (!strncmp(BufPtr, "import", ImportLen)) {
483 // replace import with include
484 SourceLocation ImportLoc =
485 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000486 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000487 BufPtr += ImportLen;
488 }
489 }
490 }
Chris Lattner74db1682007-10-16 21:07:07 +0000491}
492
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000493void RewriteTest::RewriteTabs() {
494 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
495 const char *MainBufStart = MainBuf.first;
496 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000497
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000498 // Loop over the whole file, looking for tabs.
499 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
500 if (*BufPtr != '\t')
501 continue;
502
503 // Okay, we found a tab. This tab will turn into at least one character,
504 // but it depends on which 'virtual column' it is in. Compute that now.
505 unsigned VCol = 0;
506 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
507 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
508 ++VCol;
509
510 // Okay, now that we know the virtual column, we know how many spaces to
511 // insert. We assume 8-character tab-stops.
512 unsigned Spaces = 8-(VCol & 7);
513
514 // Get the location of the tab.
515 SourceLocation TabLoc =
516 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
517
518 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000519 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000520 }
Chris Lattner569faa62007-10-11 18:38:32 +0000521}
522
523
Ted Kremenek42730c52008-01-07 19:49:32 +0000524void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000525 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000526 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000527
528 // Get the start location and compute the semi location.
529 SourceLocation startLoc = ClassDecl->getLocation();
530 const char *startBuf = SM->getCharacterData(startLoc);
531 const char *semiPtr = strchr(startBuf, ';');
532
533 // Translate to typedef's that forward reference structs with the same name
534 // as the class. As a convenience, we include the original declaration
535 // as a comment.
536 std::string typedefString;
537 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000538 typedefString.append(startBuf, semiPtr-startBuf+1);
539 typedefString += "\n";
540 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000541 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000542 typedefString += "#ifndef _REWRITER_typedef_";
543 typedefString += ForwardDecl->getName();
544 typedefString += "\n";
545 typedefString += "#define _REWRITER_typedef_";
546 typedefString += ForwardDecl->getName();
547 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000548 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000549 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000550 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000551 }
552
553 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000554 ReplaceText(startLoc, semiPtr-startBuf+1,
555 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000556}
557
Ted Kremenek42730c52008-01-07 19:49:32 +0000558void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000559 SourceLocation LocStart = Method->getLocStart();
560 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000561
Steve Naroff2ce399a2007-12-14 23:37:57 +0000562 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattner6216f292008-01-31 19:42:41 +0000563 InsertText(LocStart, "/* ", 3);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000564 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000565 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000566 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000567 }
568}
569
Chris Lattnercffe3662008-03-16 21:23:50 +0000570void RewriteTest::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000571{
Chris Lattnercffe3662008-03-16 21:23:50 +0000572 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000573 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000574 SourceLocation Loc = Property->getLocation();
575
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000576 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000577
578 // FIXME: handle properties that are declared across multiple lines.
579 }
580}
581
Ted Kremenek42730c52008-01-07 19:49:32 +0000582void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000583 SourceLocation LocStart = CatDecl->getLocStart();
584
585 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000586 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000587
Ted Kremenek42730c52008-01-07 19:49:32 +0000588 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000589 E = CatDecl->instmeth_end(); I != E; ++I)
590 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000591 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000592 E = CatDecl->classmeth_end(); I != E; ++I)
593 RewriteMethodDeclaration(*I);
594
Steve Naroff667f1682007-10-30 13:30:57 +0000595 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000596 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000597}
598
Ted Kremenek42730c52008-01-07 19:49:32 +0000599void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000600 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000601
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000602 SourceLocation LocStart = PDecl->getLocStart();
603
604 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000605 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000606
Ted Kremenek42730c52008-01-07 19:49:32 +0000607 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000608 E = PDecl->instmeth_end(); I != E; ++I)
609 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000610 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000611 E = PDecl->classmeth_end(); I != E; ++I)
612 RewriteMethodDeclaration(*I);
613
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000614 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000615 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000616 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000617
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000618 // Must comment out @optional/@required
619 const char *startBuf = SM->getCharacterData(LocStart);
620 const char *endBuf = SM->getCharacterData(LocEnd);
621 for (const char *p = startBuf; p < endBuf; p++) {
622 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
623 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000624 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000625 ReplaceText(OptionalLoc, strlen("@optional"),
626 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000627
628 }
629 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
630 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000631 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000632 ReplaceText(OptionalLoc, strlen("@required"),
633 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000634
635 }
636 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000637}
638
Ted Kremenek42730c52008-01-07 19:49:32 +0000639void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000640 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000641 if (LocStart.isInvalid())
642 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000643 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000644 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000645}
646
Ted Kremenek42730c52008-01-07 19:49:32 +0000647void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000648 std::string &ResultStr) {
649 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000650 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000651 ResultStr += "id";
652 else
653 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000654 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000655
656 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000657 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000658
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000659 if (OMD->isInstance())
660 NameStr += "_I_";
661 else
662 NameStr += "_C_";
663
664 NameStr += OMD->getClassInterface()->getName();
665 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000666
667 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000668 if (ObjCCategoryImplDecl *CID =
669 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000670 NameStr += CID->getName();
671 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000672 }
673 // Append selector names, replacing ':' with '_'
674 const char *selName = OMD->getSelector().getName().c_str();
675 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000676 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000677 else {
678 std::string selString = OMD->getSelector().getName();
679 int len = selString.size();
680 for (int i = 0; i < len; i++)
681 if (selString[i] == ':')
682 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000683 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000684 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000685 // Remember this name for metadata emission
686 MethodInternalNames[OMD] = NameStr;
687 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000688
689 // Rewrite arguments
690 ResultStr += "(";
691
692 // invisible arguments
693 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000694 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000695 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000696 if (!LangOpts.Microsoft) {
697 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
698 ResultStr += "struct ";
699 }
700 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroffde0da102008-03-10 23:16:54 +0000701 ResultStr += OMD->getClassInterface()->getName();
Steve Naroffde0da102008-03-10 23:16:54 +0000702 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000703 }
704 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000705 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000706
707 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000708 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000709 ResultStr += " _cmd";
710
711 // Method arguments.
Chris Lattner685d7922008-03-16 01:07:14 +0000712 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000713 ParmVarDecl *PDecl = OMD->getParamDecl(i);
714 ResultStr += ", ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000715 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000716 ResultStr += "id";
717 else
718 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000719 ResultStr += " ";
720 ResultStr += PDecl->getName();
721 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000722 if (OMD->isVariadic())
723 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000724 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000725
726}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000727void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000728 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
729 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000730
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000731 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000732 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000733 else
Chris Lattner6216f292008-01-31 19:42:41 +0000734 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000735
Ted Kremenek42730c52008-01-07 19:49:32 +0000736 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000737 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
738 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000739 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000740 ObjCMethodDecl *OMD = *I;
741 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000742 SourceLocation LocStart = OMD->getLocStart();
743 SourceLocation LocEnd = OMD->getBody()->getLocStart();
744
745 const char *startBuf = SM->getCharacterData(LocStart);
746 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000747 ReplaceText(LocStart, endBuf-startBuf,
748 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000749 }
750
Ted Kremenek42730c52008-01-07 19:49:32 +0000751 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000752 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
753 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000754 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000755 ObjCMethodDecl *OMD = *I;
756 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000757 SourceLocation LocStart = OMD->getLocStart();
758 SourceLocation LocEnd = OMD->getBody()->getLocStart();
759
760 const char *startBuf = SM->getCharacterData(LocStart);
761 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000762 ReplaceText(LocStart, endBuf-startBuf,
763 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000764 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000765 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000766 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000767 else
Chris Lattner6216f292008-01-31 19:42:41 +0000768 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000769}
770
Ted Kremenek42730c52008-01-07 19:49:32 +0000771void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000772 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000773 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000774 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000775 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000776 ResultStr += ClassDecl->getName();
777 ResultStr += "\n";
778 ResultStr += "#define _REWRITER_typedef_";
779 ResultStr += ClassDecl->getName();
780 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000781 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000782 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000783 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000784 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000785 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000786 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000787 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000788
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000789 RewriteProperties(ClassDecl->getNumPropertyDecl(),
790 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000791 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000792 E = ClassDecl->instmeth_end(); I != E; ++I)
793 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000794 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000795 E = ClassDecl->classmeth_end(); I != E; ++I)
796 RewriteMethodDeclaration(*I);
797
Steve Naroff1ccf4632007-10-30 03:43:13 +0000798 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000799 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000800}
801
Steve Naroff6b759ce2007-11-15 02:58:25 +0000802Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000803 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000804 if (CurMethodDecl) {
805 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
806 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
807 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroffcbf88fe2008-03-12 21:09:20 +0000808 // lookup which class implements the instance variable.
809 ObjCInterfaceDecl *clsDeclared = 0;
810 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
811 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5d933112008-03-12 23:15:19 +0000812
813 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroffcbf88fe2008-03-12 21:09:20 +0000814 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000815 RecName += "_IMPL";
816 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Chris Lattner58114f02008-03-15 21:32:50 +0000817 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct,
818 SourceLocation(), II, 0);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000819 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
820 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
821 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
822 // Don't forget the parens to enforce the proper binding.
823 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
824 if (IV->isFreeIvar()) {
825 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
826 ReplaceStmt(IV, ME);
827 delete IV;
828 return ME;
829 } else {
Chris Lattnerb1548372008-01-31 19:37:57 +0000830 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5d933112008-03-12 23:15:19 +0000831 // Cannot delete IV->getBase(), since PE points to it.
832 // Replace the old base with the cast. This is important when doing
833 // embedded rewrites. For example, [newInv->_container addObject:0].
834 IV->setBase(PE);
835 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000836 }
837 }
838 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000839 }
Steve Naroff5d933112008-03-12 23:15:19 +0000840 // FIXME: Implement public ivar access from a function.
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000841 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
842 IV->getLocation(), D->getType());
843 ReplaceStmt(IV, Replacement);
844 delete IV;
845 return Replacement;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000846}
847
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000848//===----------------------------------------------------------------------===//
849// Function Body / Expression rewriting
850//===----------------------------------------------------------------------===//
851
Steve Naroff334fbc22007-11-09 15:20:18 +0000852Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000853 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
854 isa<DoStmt>(S) || isa<ForStmt>(S))
855 Stmts.push_back(S);
856 else if (isa<ObjCForCollectionStmt>(S)) {
857 Stmts.push_back(S);
858 ObjCBcLabelNo.push_back(++BcLabelCount);
859 }
860
Chris Lattner2c022162008-01-31 05:10:40 +0000861 SourceLocation OrigStmtEnd = S->getLocEnd();
862
863 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000864 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
865 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000866 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000867 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000868 if (newStmt)
869 *CI = newStmt;
870 }
Steve Naroffe9780582007-10-23 23:50:29 +0000871
872 // Handle specific things.
873 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
874 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000875
876 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
877 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000878
879 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
880 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000881
Steve Naroff0add5d22007-11-03 11:27:19 +0000882 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
883 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000884
Steve Naroff71226032007-10-24 22:48:43 +0000885 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
886 // Before we rewrite it, put the original message expression in a comment.
887 SourceLocation startLoc = MessExpr->getLocStart();
888 SourceLocation endLoc = MessExpr->getLocEnd();
889
890 const char *startBuf = SM->getCharacterData(startLoc);
891 const char *endBuf = SM->getCharacterData(endLoc);
892
893 std::string messString;
894 messString += "// ";
895 messString.append(startBuf, endBuf-startBuf+1);
896 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000897
Chris Lattner6216f292008-01-31 19:42:41 +0000898 // FIXME: Missing definition of
899 // InsertText(clang::SourceLocation, char const*, unsigned int).
900 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff71226032007-10-24 22:48:43 +0000901 // Tried this, but it didn't work either...
Chris Lattner6216f292008-01-31 19:42:41 +0000902 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000903 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000904 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000905
Ted Kremenek42730c52008-01-07 19:49:32 +0000906 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
907 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000908
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000909 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
910 return RewriteObjCSynchronizedStmt(StmtTry);
911
Ted Kremenek42730c52008-01-07 19:49:32 +0000912 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
913 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000914
915 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
916 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000917
918 if (ObjCForCollectionStmt *StmtForCollection =
919 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner2c022162008-01-31 05:10:40 +0000920 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000921 if (BreakStmt *StmtBreakStmt =
922 dyn_cast<BreakStmt>(S))
923 return RewriteBreakStmt(StmtBreakStmt);
924 if (ContinueStmt *StmtContinueStmt =
925 dyn_cast<ContinueStmt>(S))
926 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000927
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000928 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
929 isa<DoStmt>(S) || isa<ForStmt>(S)) {
930 assert(!Stmts.empty() && "Statement stack is empty");
931 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
932 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
933 && "Statement stack mismatch");
934 Stmts.pop_back();
935 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000936#if 0
937 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
938 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
939 // Get the new text.
940 std::ostringstream Buf;
941 Replacement->printPretty(Buf);
942 const std::string &Str = Buf.str();
943
944 printf("CAST = %s\n", &Str[0]);
Chris Lattner6216f292008-01-31 19:42:41 +0000945 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff764c1ae2007-11-15 10:28:18 +0000946 delete S;
947 return Replacement;
948 }
949#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000950 // Return this stmt unmodified.
951 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000952}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000953
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000954/// SynthCountByEnumWithState - To print:
955/// ((unsigned int (*)
956/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
957/// (void *)objc_msgSend)((id)l_collection,
958/// sel_registerName(
959/// "countByEnumeratingWithState:objects:count:"),
960/// &enumState,
961/// (id *)items, (unsigned int)16)
962///
963void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
964 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
965 "id *, unsigned int))(void *)objc_msgSend)";
966 buf += "\n\t\t";
967 buf += "((id)l_collection,\n\t\t";
968 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
969 buf += "\n\t\t";
970 buf += "&enumState, "
971 "(id *)items, (unsigned int)16)";
972}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000973
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000974/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
975/// statement to exit to its outer synthesized loop.
976///
977Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
978 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
979 return S;
980 // replace break with goto __break_label
981 std::string buf;
982
983 SourceLocation startLoc = S->getLocStart();
984 buf = "goto __break_label_";
985 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000986 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000987
988 return 0;
989}
990
991/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
992/// statement to continue with its inner synthesized loop.
993///
994Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
995 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
996 return S;
997 // replace continue with goto __continue_label
998 std::string buf;
999
1000 SourceLocation startLoc = S->getLocStart();
1001 buf = "goto __continue_label_";
1002 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001003 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001004
1005 return 0;
1006}
1007
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001008/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001009/// It rewrites:
1010/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001011
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001012/// Into:
1013/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001014/// type elem;
1015/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001016/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001017/// id l_collection = (id)collection;
1018/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1019/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001020/// if (limit) {
1021/// unsigned long startMutations = *enumState.mutationsPtr;
1022/// do {
1023/// unsigned long counter = 0;
1024/// do {
1025/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001026/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001027/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001028/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001029/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001030/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001031/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1032/// objects:items count:16]);
1033/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001034/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001035/// }
1036/// else
1037/// elem = nil;
1038/// }
1039///
Chris Lattner2c022162008-01-31 05:10:40 +00001040Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1041 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001042 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1043 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1044 "ObjCForCollectionStmt Statement stack mismatch");
1045 assert(!ObjCBcLabelNo.empty() &&
1046 "ObjCForCollectionStmt - Label No stack empty");
1047
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001048 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001049 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001050 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001051 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001052 std::string buf;
1053 buf = "\n{\n\t";
1054 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1055 // type elem;
1056 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001057 elementTypeAsString = ElementType.getAsString();
1058 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001059 buf += " ";
1060 elementName = DS->getDecl()->getName();
1061 buf += elementName;
1062 buf += ";\n\t";
1063 }
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001064 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001065 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001066 elementTypeAsString = DR->getDecl()->getType().getAsString();
1067 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001068 else
1069 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1070
1071 // struct __objcFastEnumerationState enumState = { 0 };
1072 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1073 // id items[16];
1074 buf += "id items[16];\n\t";
1075 // id l_collection = (id)
1076 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001077 // Find start location of 'collection' the hard way!
1078 const char *startCollectionBuf = startBuf;
1079 startCollectionBuf += 3; // skip 'for'
1080 startCollectionBuf = strchr(startCollectionBuf, '(');
1081 startCollectionBuf++; // skip '('
1082 // find 'in' and skip it.
1083 while (*startCollectionBuf != ' ' ||
1084 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1085 (*(startCollectionBuf+3) != ' ' &&
1086 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1087 startCollectionBuf++;
1088 startCollectionBuf += 3;
1089
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001090 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001091 ReplaceText(startLoc, startCollectionBuf - startBuf,
1092 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001093 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001094 SourceLocation rightParenLoc = S->getRParenLoc();
1095 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1096 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001097 buf = ";\n\t";
1098
1099 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1100 // objects:items count:16];
1101 // which is synthesized into:
1102 // unsigned int limit =
1103 // ((unsigned int (*)
1104 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1105 // (void *)objc_msgSend)((id)l_collection,
1106 // sel_registerName(
1107 // "countByEnumeratingWithState:objects:count:"),
1108 // (struct __objcFastEnumerationState *)&state,
1109 // (id *)items, (unsigned int)16);
1110 buf += "unsigned long limit =\n\t\t";
1111 SynthCountByEnumWithState(buf);
1112 buf += ";\n\t";
1113 /// if (limit) {
1114 /// unsigned long startMutations = *enumState.mutationsPtr;
1115 /// do {
1116 /// unsigned long counter = 0;
1117 /// do {
1118 /// if (startMutations != *enumState.mutationsPtr)
1119 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001120 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001121 buf += "if (limit) {\n\t";
1122 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1123 buf += "do {\n\t\t";
1124 buf += "unsigned long counter = 0;\n\t\t";
1125 buf += "do {\n\t\t\t";
1126 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1127 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1128 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001129 buf += " = (";
1130 buf += elementTypeAsString;
1131 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001132 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001133 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001134
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001135 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001136 /// } while (counter < limit);
1137 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1138 /// objects:items count:16]);
1139 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001140 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001141 /// }
1142 /// else
1143 /// elem = nil;
1144 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001145 ///
1146 buf = ";\n\t";
1147 buf += "__continue_label_";
1148 buf += utostr(ObjCBcLabelNo.back());
1149 buf += ": ;";
1150 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001151 buf += "} while (counter < limit);\n\t";
1152 buf += "} while (limit = ";
1153 SynthCountByEnumWithState(buf);
1154 buf += ");\n\t";
1155 buf += elementName;
1156 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001157 buf += "__break_label_";
1158 buf += utostr(ObjCBcLabelNo.back());
1159 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001160 buf += "}\n\t";
1161 buf += "else\n\t\t";
1162 buf += elementName;
1163 buf += " = nil;\n";
1164 buf += "}\n";
1165 // Insert all these *after* the statement body.
Chris Lattner2c022162008-01-31 05:10:40 +00001166 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattner6216f292008-01-31 19:42:41 +00001167 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001168 Stmts.pop_back();
1169 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001170 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001171}
1172
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001173/// RewriteObjCSynchronizedStmt -
1174/// This routine rewrites @synchronized(expr) stmt;
1175/// into:
1176/// objc_sync_enter(expr);
1177/// @try stmt @finally { objc_sync_exit(expr); }
1178///
1179Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1180 // Get the start location and compute the semi location.
1181 SourceLocation startLoc = S->getLocStart();
1182 const char *startBuf = SM->getCharacterData(startLoc);
1183
1184 assert((*startBuf == '@') && "bogus @synchronized location");
1185
1186 std::string buf;
1187 buf = "objc_sync_enter";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001188 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001189 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1190 const char *endBuf = SM->getCharacterData(endLoc);
1191 endBuf++;
1192 const char *rparenBuf = strchr(endBuf, ')');
1193 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1194 buf = ");\n";
1195 // declare a new scope with two variables, _stack and _rethrow.
1196 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1197 buf += "int buf[18/*32-bit i386*/];\n";
1198 buf += "char *pointers[4];} _stack;\n";
1199 buf += "id volatile _rethrow = 0;\n";
1200 buf += "objc_exception_try_enter(&_stack);\n";
1201 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001202 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001203 startLoc = S->getSynchBody()->getLocEnd();
1204 startBuf = SM->getCharacterData(startLoc);
1205
1206 assert((*startBuf == '}') && "bogus @try block");
1207 SourceLocation lastCurlyLoc = startLoc;
1208 buf = "}\nelse {\n";
1209 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1210 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1211 // FIXME: This must be objc_sync_exit(syncExpr);
1212 buf += " objc_sync_exit();\n";
1213 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1214 buf += "}\n";
1215 buf += "}";
1216
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001217 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001218 return 0;
1219}
1220
Ted Kremenek42730c52008-01-07 19:49:32 +00001221Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001222 // Get the start location and compute the semi location.
1223 SourceLocation startLoc = S->getLocStart();
1224 const char *startBuf = SM->getCharacterData(startLoc);
1225
1226 assert((*startBuf == '@') && "bogus @try location");
1227
1228 std::string buf;
1229 // declare a new scope with two variables, _stack and _rethrow.
1230 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1231 buf += "int buf[18/*32-bit i386*/];\n";
1232 buf += "char *pointers[4];} _stack;\n";
1233 buf += "id volatile _rethrow = 0;\n";
1234 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001235 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001236
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001237 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001238
1239 startLoc = S->getTryBody()->getLocEnd();
1240 startBuf = SM->getCharacterData(startLoc);
1241
1242 assert((*startBuf == '}') && "bogus @try block");
1243
1244 SourceLocation lastCurlyLoc = startLoc;
1245
1246 startLoc = startLoc.getFileLocWithOffset(1);
1247 buf = " /* @catch begin */ else {\n";
1248 buf += " id _caught = objc_exception_extract(&_stack);\n";
1249 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001250 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001251 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1252 buf += " else { /* @catch continue */";
1253
Chris Lattner6216f292008-01-31 19:42:41 +00001254 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001255
1256 bool sawIdTypedCatch = false;
1257 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001258 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001259 while (catchList) {
1260 Stmt *catchStmt = catchList->getCatchParamStmt();
1261
1262 if (catchList == S->getCatchStmts())
1263 buf = "if ("; // we are generating code for the first catch clause
1264 else
1265 buf = "else if (";
1266 startLoc = catchList->getLocStart();
1267 startBuf = SM->getCharacterData(startLoc);
1268
1269 assert((*startBuf == '@') && "bogus @catch location");
1270
1271 const char *lParenLoc = strchr(startBuf, '(');
1272
Steve Naroff397c4ce2008-02-01 22:08:12 +00001273 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001274 // Now rewrite the body...
1275 lastCatchBody = catchList->getCatchBody();
1276 SourceLocation rParenLoc = catchList->getRParenLoc();
1277 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1278 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1279 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1280 assert((*rParenBuf == ')') && "bogus @catch paren location");
1281 assert((*bodyBuf == '{') && "bogus @catch body location");
1282
1283 buf += "1) { id _tmp = _caught;";
1284 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1285 buf.c_str(), buf.size());
1286 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001287 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001288 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001289 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001290 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001291 sawIdTypedCatch = true;
1292 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001293 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001294
Ted Kremenek42730c52008-01-07 19:49:32 +00001295 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001296 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001297 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001298 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001299 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001300 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001301 }
1302 }
1303 // Now rewrite the body...
1304 lastCatchBody = catchList->getCatchBody();
1305 SourceLocation rParenLoc = catchList->getRParenLoc();
1306 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1307 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1308 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1309 assert((*rParenBuf == ')') && "bogus @catch paren location");
1310 assert((*bodyBuf == '{') && "bogus @catch body location");
1311
1312 buf = " = _caught;";
1313 // Here we replace ") {" with "= _caught;" (which initializes and
1314 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001315 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001316 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001317 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001318 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001319 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001320 catchList = catchList->getNextCatchStmt();
1321 }
1322 // Complete the catch list...
1323 if (lastCatchBody) {
1324 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1325 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1326 assert((*bodyBuf == '}') && "bogus @catch body location");
1327 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1328 buf = " } } /* @catch end */\n";
1329
Chris Lattner6216f292008-01-31 19:42:41 +00001330 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001331
1332 // Set lastCurlyLoc
1333 lastCurlyLoc = lastCatchBody->getLocEnd();
1334 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001335 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001336 startLoc = finalStmt->getLocStart();
1337 startBuf = SM->getCharacterData(startLoc);
1338 assert((*startBuf == '@') && "bogus @finally start");
1339
1340 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001341 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001342
1343 Stmt *body = finalStmt->getFinallyBody();
1344 SourceLocation startLoc = body->getLocStart();
1345 SourceLocation endLoc = body->getLocEnd();
1346 const char *startBuf = SM->getCharacterData(startLoc);
1347 const char *endBuf = SM->getCharacterData(endLoc);
1348 assert((*startBuf == '{') && "bogus @finally body location");
1349 assert((*endBuf == '}') && "bogus @finally body location");
1350
1351 startLoc = startLoc.getFileLocWithOffset(1);
1352 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001353 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001354 endLoc = endLoc.getFileLocWithOffset(-1);
1355 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001356 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001357
1358 // Set lastCurlyLoc
1359 lastCurlyLoc = body->getLocEnd();
1360 }
1361 // Now emit the final closing curly brace...
1362 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1363 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001364 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001365 return 0;
1366}
1367
Ted Kremenek42730c52008-01-07 19:49:32 +00001368Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001369 return 0;
1370}
1371
Ted Kremenek42730c52008-01-07 19:49:32 +00001372Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001373 return 0;
1374}
1375
Chris Lattnerb1548372008-01-31 19:37:57 +00001376// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001377// the throw expression is typically a message expression that's already
1378// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremenek42730c52008-01-07 19:49:32 +00001379Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001380 // Get the start location and compute the semi location.
1381 SourceLocation startLoc = S->getLocStart();
1382 const char *startBuf = SM->getCharacterData(startLoc);
1383
1384 assert((*startBuf == '@') && "bogus @throw location");
1385
1386 std::string buf;
1387 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001388 if (S->getThrowExpr())
1389 buf = "objc_exception_throw(";
1390 else // add an implicit argument
1391 buf = "objc_exception_throw(_caught";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001392 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001393 const char *semiBuf = strchr(startBuf, ';');
1394 assert((*semiBuf == ';') && "@throw: can't find ';'");
1395 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1396 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001397 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001398 return 0;
1399}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001400
Chris Lattner0021f452007-10-24 16:57:36 +00001401Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001402 // Create a new string expression.
1403 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001404 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001405 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1406 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001407 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1408 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001409 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001410 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001411
Chris Lattner4478db92007-11-30 22:53:43 +00001412 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001413 delete Exp;
1414 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001415}
1416
Steve Naroff296b74f2007-11-05 14:50:49 +00001417Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1418 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1419 // Create a call to sel_registerName("selName").
1420 llvm::SmallVector<Expr*, 8> SelExprs;
1421 QualType argType = Context->getPointerType(Context->CharTy);
1422 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1423 Exp->getSelector().getName().size(),
1424 false, argType, SourceLocation(),
1425 SourceLocation()));
1426 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1427 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001428 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001429 delete Exp;
1430 return SelExp;
1431}
1432
Steve Naroff71226032007-10-24 22:48:43 +00001433CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1434 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001435 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001436 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001437
1438 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001439 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001440
1441 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001442 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001443 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1444
1445 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001446
Steve Naroff71226032007-10-24 22:48:43 +00001447 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1448}
1449
Steve Naroffc8a92d12007-11-01 13:24:47 +00001450static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1451 const char *&startRef, const char *&endRef) {
1452 while (startBuf < endBuf) {
1453 if (*startBuf == '<')
1454 startRef = startBuf; // mark the start.
1455 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001456 if (startRef && *startRef == '<') {
1457 endRef = startBuf; // mark the end.
1458 return true;
1459 }
1460 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001461 }
1462 startBuf++;
1463 }
1464 return false;
1465}
1466
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001467static void scanToNextArgument(const char *&argRef) {
1468 int angle = 0;
1469 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1470 if (*argRef == '<')
1471 angle++;
1472 else if (*argRef == '>')
1473 angle--;
1474 argRef++;
1475 }
1476 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1477}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001478
Steve Naroffc8a92d12007-11-01 13:24:47 +00001479bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001480
Ted Kremenek42730c52008-01-07 19:49:32 +00001481 if (T == Context->getObjCIdType())
Steve Naroffc8a92d12007-11-01 13:24:47 +00001482 return true;
1483
Ted Kremenek42730c52008-01-07 19:49:32 +00001484 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001485 return true;
1486
Steve Naroffc8a92d12007-11-01 13:24:47 +00001487 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001488 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001489 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001490 return true; // we have "Class <Protocol> *".
1491 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001492 return false;
1493}
1494
Ted Kremenek42730c52008-01-07 19:49:32 +00001495void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001496 SourceLocation Loc;
1497 QualType Type;
1498 const FunctionTypeProto *proto = 0;
1499 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1500 Loc = VD->getLocation();
1501 Type = VD->getType();
1502 }
1503 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1504 Loc = FD->getLocation();
1505 // Check for ObjC 'id' and class types that have been adorned with protocol
1506 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1507 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1508 assert(funcType && "missing function type");
1509 proto = dyn_cast<FunctionTypeProto>(funcType);
1510 if (!proto)
1511 return;
1512 Type = proto->getResultType();
1513 }
1514 else
1515 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001516
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001517 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001518 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001519
1520 const char *endBuf = SM->getCharacterData(Loc);
1521 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001522 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001523 startBuf--; // scan backward (from the decl location) for return type.
1524 const char *startRef = 0, *endRef = 0;
1525 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1526 // Get the locations of the startRef, endRef.
1527 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1528 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1529 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001530 InsertText(LessLoc, "/*", 2);
1531 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001532 }
1533 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001534 if (!proto)
1535 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001536 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001537 const char *startBuf = SM->getCharacterData(Loc);
1538 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001539 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1540 if (needToScanForQualifiers(proto->getArgType(i))) {
1541 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001542
Steve Naroffc8a92d12007-11-01 13:24:47 +00001543 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001544 // scan forward (from the decl location) for argument types.
1545 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001546 const char *startRef = 0, *endRef = 0;
1547 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1548 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001549 SourceLocation LessLoc =
1550 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1551 SourceLocation GreaterLoc =
1552 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001553 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001554 InsertText(LessLoc, "/*", 2);
1555 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001556 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001557 startBuf = ++endBuf;
1558 }
1559 else {
1560 while (*startBuf != ')' && *startBuf != ',')
1561 startBuf++; // scan forward (from the decl location) for argument types.
1562 startBuf++;
1563 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001564 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001565}
1566
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001567// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1568void RewriteTest::SynthSelGetUidFunctionDecl() {
1569 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1570 llvm::SmallVector<QualType, 16> ArgTys;
1571 ArgTys.push_back(Context->getPointerType(
1572 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001573 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001574 &ArgTys[0], ArgTys.size(),
1575 false /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001576 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001577 SelGetUidIdent, getFuncType,
1578 FunctionDecl::Extern, false, 0);
1579}
1580
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001581// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1582void RewriteTest::SynthGetProtocolFunctionDecl() {
1583 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1584 llvm::SmallVector<QualType, 16> ArgTys;
1585 ArgTys.push_back(Context->getPointerType(
1586 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001587 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001588 &ArgTys[0], ArgTys.size(),
1589 false /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001590 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001591 SelGetProtoIdent, getFuncType,
1592 FunctionDecl::Extern, false, 0);
1593}
1594
Steve Naroff02a82aa2007-10-30 23:14:51 +00001595void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1596 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001597 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001598 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001599 return;
1600 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001601 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001602}
1603
Steve Naroffbec4bf52008-03-11 17:37:02 +00001604// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1605void RewriteTest::SynthSuperContructorFunctionDecl() {
1606 if (SuperContructorFunctionDecl)
1607 return;
1608 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1609 llvm::SmallVector<QualType, 16> ArgTys;
1610 QualType argT = Context->getObjCIdType();
1611 assert(!argT.isNull() && "Can't find 'id' type");
1612 ArgTys.push_back(argT);
1613 ArgTys.push_back(argT);
1614 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1615 &ArgTys[0], ArgTys.size(),
1616 false);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001617 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001618 msgSendIdent, msgSendType,
1619 FunctionDecl::Extern, false, 0);
1620}
1621
Steve Naroff02a82aa2007-10-30 23:14:51 +00001622// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1623void RewriteTest::SynthMsgSendFunctionDecl() {
1624 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1625 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001626 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001627 assert(!argT.isNull() && "Can't find 'id' type");
1628 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001629 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001630 assert(!argT.isNull() && "Can't find 'SEL' type");
1631 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001632 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001633 &ArgTys[0], ArgTys.size(),
1634 true /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001635 MsgSendFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001636 msgSendIdent, msgSendType,
1637 FunctionDecl::Extern, false, 0);
1638}
1639
Steve Naroff764c1ae2007-11-15 10:28:18 +00001640// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1641void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1642 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1643 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattner58114f02008-03-15 21:32:50 +00001644 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, SourceLocation(),
1645 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001646 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1647 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1648 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001649 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001650 assert(!argT.isNull() && "Can't find 'SEL' type");
1651 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001652 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001653 &ArgTys[0], ArgTys.size(),
1654 true /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001655 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001656 msgSendIdent, msgSendType,
1657 FunctionDecl::Extern, false, 0);
1658}
1659
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001660// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1661void RewriteTest::SynthMsgSendStretFunctionDecl() {
1662 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1663 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001664 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001665 assert(!argT.isNull() && "Can't find 'id' type");
1666 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001667 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001668 assert(!argT.isNull() && "Can't find 'SEL' type");
1669 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001670 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001671 &ArgTys[0], ArgTys.size(),
1672 true /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001673 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001674 msgSendIdent, msgSendType,
1675 FunctionDecl::Extern, false, 0);
1676}
1677
1678// SynthMsgSendSuperStretFunctionDecl -
1679// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1680void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1681 IdentifierInfo *msgSendIdent =
1682 &Context->Idents.get("objc_msgSendSuper_stret");
1683 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattner58114f02008-03-15 21:32:50 +00001684 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, SourceLocation(),
1685 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001686 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1687 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1688 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001689 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001690 assert(!argT.isNull() && "Can't find 'SEL' type");
1691 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001692 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001693 &ArgTys[0], ArgTys.size(),
1694 true /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001695 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context,
1696 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001697 msgSendIdent, msgSendType,
1698 FunctionDecl::Extern, false, 0);
1699}
1700
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001701// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1702void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1703 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1704 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001705 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001706 assert(!argT.isNull() && "Can't find 'id' type");
1707 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001708 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001709 assert(!argT.isNull() && "Can't find 'SEL' type");
1710 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001711 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001712 &ArgTys[0], ArgTys.size(),
1713 true /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001714 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001715 msgSendIdent, msgSendType,
1716 FunctionDecl::Extern, false, 0);
1717}
1718
Steve Naroff02a82aa2007-10-30 23:14:51 +00001719// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1720void RewriteTest::SynthGetClassFunctionDecl() {
1721 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1722 llvm::SmallVector<QualType, 16> ArgTys;
1723 ArgTys.push_back(Context->getPointerType(
1724 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001725 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001726 &ArgTys[0], ArgTys.size(),
1727 false /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001728 GetClassFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001729 getClassIdent, getClassType,
1730 FunctionDecl::Extern, false, 0);
1731}
1732
Steve Naroff3b1caac2007-12-07 03:50:46 +00001733// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1734void RewriteTest::SynthGetMetaClassFunctionDecl() {
1735 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1736 llvm::SmallVector<QualType, 16> ArgTys;
1737 ArgTys.push_back(Context->getPointerType(
1738 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001739 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001740 &ArgTys[0], ArgTys.size(),
1741 false /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001742 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001743 getClassIdent, getClassType,
1744 FunctionDecl::Extern, false, 0);
1745}
1746
Steve Naroff0add5d22007-11-03 11:27:19 +00001747Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001748 QualType strType = getConstantStringStructType();
1749
1750 std::string S = "__NSConstantStringImpl_";
1751 S += utostr(NumObjCStringLiterals++);
1752
1753 std::string StrObjDecl = "static __NSConstantStringImpl " + S;
Steve Naroffe0766ed2008-03-18 01:47:18 +00001754 StrObjDecl += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1755 StrObjDecl += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00001756 // The pretty printer for StringLiteral handles escape characters properly.
1757 std::ostringstream prettyBuf;
1758 Exp->getString()->printPretty(prettyBuf);
1759 StrObjDecl += prettyBuf.str();
1760 StrObjDecl += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00001761 // The minus 2 removes the begin/end double quotes.
Steve Naroffe0766ed2008-03-18 01:47:18 +00001762 StrObjDecl += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001763 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
1764 StrObjDecl.c_str(), StrObjDecl.size());
1765
Chris Lattner58114f02008-03-15 21:32:50 +00001766 FileVarDecl *NewVD = FileVarDecl::Create(*Context, SourceLocation(),
Steve Naroff47e7fa22008-03-15 00:55:56 +00001767 &Context->Idents.get(S.c_str()), strType,
Chris Lattner58114f02008-03-15 21:32:50 +00001768 VarDecl::Static, NULL);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001769 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1770 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1771 Context->getPointerType(DRE->getType()),
1772 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001773 // cast to NSConstantString *
Steve Naroff47e7fa22008-03-15 00:55:56 +00001774 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001775 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001776 delete Exp;
1777 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001778}
1779
Ted Kremenek42730c52008-01-07 19:49:32 +00001780ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001781 // check if we are sending a message to 'super'
Chris Lattnere4650482008-03-15 06:12:44 +00001782 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1783
1784 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1785 if (!CE) return 0;
1786
1787 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1788 if (!DRE) return 0;
1789
1790 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1791 if (!PVD) return 0;
1792
1793 if (strcmp(PVD->getName(), "self") != 0)
1794 return 0;
1795
1796 // is this id<P1..> type?
1797 if (CE->getType()->isObjCQualifiedIdType())
1798 return 0;
1799 const PointerType *PT = CE->getType()->getAsPointerType();
1800 if (!PT) return 0;
1801
1802 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1803 if (!IT) return 0;
1804
1805 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1806 return 0;
1807
1808 return IT->getDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001809}
1810
1811// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1812QualType RewriteTest::getSuperStructType() {
1813 if (!SuperStructDecl) {
Chris Lattner58114f02008-03-15 21:32:50 +00001814 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct,
1815 SourceLocation(),
1816 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001817 QualType FieldTypes[2];
1818
1819 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001820 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001821 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001822 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001823 // Create fields
1824 FieldDecl *FieldDecls[2];
1825
1826 for (unsigned i = 0; i < 2; ++i)
Chris Lattner81db64a2008-03-16 00:16:02 +00001827 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
1828 FieldTypes[i]);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001829
1830 SuperStructDecl->defineBody(FieldDecls, 4);
1831 }
1832 return Context->getTagDeclType(SuperStructDecl);
1833}
1834
Steve Naroff47e7fa22008-03-15 00:55:56 +00001835QualType RewriteTest::getConstantStringStructType() {
1836 if (!ConstantStringDecl) {
Chris Lattner58114f02008-03-15 21:32:50 +00001837 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct,
1838 SourceLocation(),
1839 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001840 QualType FieldTypes[4];
1841
1842 // struct objc_object *receiver;
1843 FieldTypes[0] = Context->getObjCIdType();
1844 // int flags;
1845 FieldTypes[1] = Context->IntTy;
1846 // char *str;
1847 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1848 // long length;
1849 FieldTypes[3] = Context->LongTy;
1850 // Create fields
1851 FieldDecl *FieldDecls[2];
1852
1853 for (unsigned i = 0; i < 4; ++i)
Chris Lattner81db64a2008-03-16 00:16:02 +00001854 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
1855 FieldTypes[i]);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001856
1857 ConstantStringDecl->defineBody(FieldDecls, 4);
1858 }
1859 return Context->getTagDeclType(ConstantStringDecl);
1860}
1861
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001862Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001863 if (!SelGetUidFunctionDecl)
1864 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001865 if (!MsgSendFunctionDecl)
1866 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001867 if (!MsgSendSuperFunctionDecl)
1868 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001869 if (!MsgSendStretFunctionDecl)
1870 SynthMsgSendStretFunctionDecl();
1871 if (!MsgSendSuperStretFunctionDecl)
1872 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001873 if (!MsgSendFpretFunctionDecl)
1874 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001875 if (!GetClassFunctionDecl)
1876 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001877 if (!GetMetaClassFunctionDecl)
1878 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001879
Steve Naroff764c1ae2007-11-15 10:28:18 +00001880 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001881 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1882 // May need to use objc_msgSend_stret() as well.
1883 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001884 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001885 QualType resultType = mDecl->getResultType();
1886 if (resultType.getCanonicalType()->isStructureType()
1887 || resultType.getCanonicalType()->isUnionType())
1888 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001889 else if (resultType.getCanonicalType()->isRealFloatingType())
1890 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001891 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001892
Steve Naroff71226032007-10-24 22:48:43 +00001893 // Synthesize a call to objc_msgSend().
1894 llvm::SmallVector<Expr*, 8> MsgExprs;
1895 IdentifierInfo *clsName = Exp->getClassName();
1896
1897 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1898 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001899 if (!strcmp(clsName->getName(), "super")) {
1900 MsgSendFlavor = MsgSendSuperFunctionDecl;
1901 if (MsgSendStretFlavor)
1902 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1903 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1904
Ted Kremenek42730c52008-01-07 19:49:32 +00001905 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001906 CurMethodDecl->getClassInterface()->getSuperClass();
1907
1908 llvm::SmallVector<Expr*, 4> InitExprs;
1909
1910 // set the receiver to self, the first argument to all methods.
1911 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001912 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001913 SourceLocation()));
1914 llvm::SmallVector<Expr*, 8> ClsExprs;
1915 QualType argType = Context->getPointerType(Context->CharTy);
1916 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1917 SuperDecl->getIdentifier()->getLength(),
1918 false, argType, SourceLocation(),
1919 SourceLocation()));
1920 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1921 &ClsExprs[0],
1922 ClsExprs.size());
1923 // To turn off a warning, type-cast to 'id'
1924 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001925 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001926 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1927 // struct objc_super
1928 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00001929 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00001930
Steve Naroffdee066b2008-03-11 18:14:26 +00001931 if (LangOpts.Microsoft) {
1932 SynthSuperContructorFunctionDecl();
1933 // Simulate a contructor call...
1934 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1935 superType, SourceLocation());
1936 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1937 superType, SourceLocation());
1938 } else {
1939 // (struct objc_super) { <exprs from above> }
1940 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1941 &InitExprs[0], InitExprs.size(),
1942 SourceLocation());
1943 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1944 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001945 // struct objc_super *
1946 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1947 Context->getPointerType(SuperRep->getType()),
1948 SourceLocation());
1949 MsgExprs.push_back(Unop);
1950 } else {
1951 llvm::SmallVector<Expr*, 8> ClsExprs;
1952 QualType argType = Context->getPointerType(Context->CharTy);
1953 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1954 clsName->getLength(),
1955 false, argType, SourceLocation(),
1956 SourceLocation()));
1957 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1958 &ClsExprs[0],
1959 ClsExprs.size());
1960 MsgExprs.push_back(Cls);
1961 }
Steve Naroff885e2122007-11-14 23:54:14 +00001962 } else { // instance message.
1963 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001964
Ted Kremenek42730c52008-01-07 19:49:32 +00001965 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001966 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001967 if (MsgSendStretFlavor)
1968 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001969 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1970
1971 llvm::SmallVector<Expr*, 4> InitExprs;
1972
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001973 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001974 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001975 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001976
1977 llvm::SmallVector<Expr*, 8> ClsExprs;
1978 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001979 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1980 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001981 false, argType, SourceLocation(),
1982 SourceLocation()));
1983 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001984 &ClsExprs[0],
1985 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001986 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001987 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001988 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001989 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001990 // struct objc_super
1991 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00001992 Expr *SuperRep;
1993
1994 if (LangOpts.Microsoft) {
1995 SynthSuperContructorFunctionDecl();
1996 // Simulate a contructor call...
1997 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1998 superType, SourceLocation());
1999 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2000 superType, SourceLocation());
2001 } else {
2002 // (struct objc_super) { <exprs from above> }
2003 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2004 &InitExprs[0], InitExprs.size(),
2005 SourceLocation());
2006 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2007 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002008 // struct objc_super *
2009 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2010 Context->getPointerType(SuperRep->getType()),
2011 SourceLocation());
2012 MsgExprs.push_back(Unop);
2013 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002014 // Remove all type-casts because it may contain objc-style types; e.g.
2015 // Foo<Proto> *.
2016 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2017 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002018 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002019 MsgExprs.push_back(recExpr);
2020 }
Steve Naroff885e2122007-11-14 23:54:14 +00002021 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002022 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002023 llvm::SmallVector<Expr*, 8> SelExprs;
2024 QualType argType = Context->getPointerType(Context->CharTy);
2025 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2026 Exp->getSelector().getName().size(),
2027 false, argType, SourceLocation(),
2028 SourceLocation()));
2029 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2030 &SelExprs[0], SelExprs.size());
2031 MsgExprs.push_back(SelExp);
2032
2033 // Now push any user supplied arguments.
2034 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002035 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002036 // Make all implicit casts explicit...ICE comes in handy:-)
2037 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2038 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00002039 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2040 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002041 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002042 }
2043 // Make id<P...> cast into an 'id' cast.
2044 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002045 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002046 while ((CE = dyn_cast<CastExpr>(userExpr)))
2047 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002048 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002049 userExpr, SourceLocation());
2050 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002051 }
Steve Naroff885e2122007-11-14 23:54:14 +00002052 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002053 // We've transferred the ownership to MsgExprs. Null out the argument in
2054 // the original expression, since we will delete it below.
2055 Exp->setArg(i, 0);
2056 }
Steve Naroff0744c472007-11-04 22:37:50 +00002057 // Generate the funky cast.
2058 CastExpr *cast;
2059 llvm::SmallVector<QualType, 8> ArgTypes;
2060 QualType returnType;
2061
2062 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002063 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2064 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2065 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002066 ArgTypes.push_back(Context->getObjCIdType());
2067 ArgTypes.push_back(Context->getObjCSelType());
2068 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002069 // Push any user argument types.
Chris Lattner685d7922008-03-16 01:07:14 +00002070 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002071 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2072 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002073 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00002074 ArgTypes.push_back(t);
2075 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002076 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2077 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002078 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002079 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002080 }
2081 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002082 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002083
2084 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002085 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2086 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002087
2088 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2089 // If we don't do this cast, we get the following bizarre warning/note:
2090 // xx.m:13: warning: function called through a non-compatible type
2091 // xx.m:13: note: if this code is reached, the program will abort
2092 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2093 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002094
Steve Naroff0744c472007-11-04 22:37:50 +00002095 // Now do the "normal" pointer to function cast.
2096 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002097 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002098 // If we don't have a method decl, force a variadic cast.
2099 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroff0744c472007-11-04 22:37:50 +00002100 castType = Context->getPointerType(castType);
2101 cast = new CastExpr(castType, cast, SourceLocation());
2102
2103 // Don't forget the parens to enforce the proper binding.
2104 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2105
2106 const FunctionType *FT = msgSendType->getAsFunctionType();
2107 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2108 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002109 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002110 if (MsgSendStretFlavor) {
2111 // We have the method which returns a struct/union. Must also generate
2112 // call to objc_msgSend_stret and hang both varieties on a conditional
2113 // expression which dictate which one to envoke depending on size of
2114 // method's return type.
2115
2116 // Create a reference to the objc_msgSend_stret() declaration.
2117 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2118 SourceLocation());
2119 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2120 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2121 SourceLocation());
2122 // Now do the "normal" pointer to function cast.
2123 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002124 &ArgTypes[0], ArgTypes.size(),
2125 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002126 castType = Context->getPointerType(castType);
2127 cast = new CastExpr(castType, cast, SourceLocation());
2128
2129 // Don't forget the parens to enforce the proper binding.
2130 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2131
2132 FT = msgSendType->getAsFunctionType();
2133 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2134 FT->getResultType(), SourceLocation());
2135
2136 // Build sizeof(returnType)
2137 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2138 returnType, Context->getSizeType(),
2139 SourceLocation(), SourceLocation());
2140 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2141 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2142 // For X86 it is more complicated and some kind of target specific routine
2143 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002144 unsigned IntSize =
2145 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002146 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2147 Context->IntTy,
2148 SourceLocation());
2149 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2150 BinaryOperator::LE,
2151 Context->IntTy,
2152 SourceLocation());
2153 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2154 ConditionalOperator *CondExpr =
2155 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002156 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002157 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002158 return ReplacingStmt;
2159}
2160
2161Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2162 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002163 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002164 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002165
Chris Lattner0021f452007-10-24 16:57:36 +00002166 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002167 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002168}
2169
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002170/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2171/// call to objc_getProtocol("proto-name").
2172Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2173 if (!GetProtocolFunctionDecl)
2174 SynthGetProtocolFunctionDecl();
2175 // Create a call to objc_getProtocol("ProtocolName").
2176 llvm::SmallVector<Expr*, 8> ProtoExprs;
2177 QualType argType = Context->getPointerType(Context->CharTy);
2178 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2179 strlen(Exp->getProtocol()->getName()),
2180 false, argType, SourceLocation(),
2181 SourceLocation()));
2182 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2183 &ProtoExprs[0],
2184 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002185 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002186 delete Exp;
2187 return ProtoExp;
2188
2189}
2190
Ted Kremenek42730c52008-01-07 19:49:32 +00002191/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002192/// an objective-c class with ivars.
Ted Kremenek42730c52008-01-07 19:49:32 +00002193void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002194 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002195 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2196 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002197 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002198 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002199 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002200 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002201 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002202 SourceLocation LocStart = CDecl->getLocStart();
2203 SourceLocation LocEnd = CDecl->getLocEnd();
2204
2205 const char *startBuf = SM->getCharacterData(LocStart);
2206 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002207 // If no ivars and no root or if its root, directly or indirectly,
2208 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002209 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2210 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002211 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002212 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002213 return;
2214 }
2215
2216 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002217 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002218 Result += "\nstruct ";
2219 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002220 if (LangOpts.Microsoft)
2221 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002222
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002223 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002224 const char *cursor = strchr(startBuf, '{');
2225 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002226 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00002227
2228 // rewrite the original header *without* disturbing the '{'
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002229 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremenek42730c52008-01-07 19:49:32 +00002230 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002231 Result = "\n struct ";
2232 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002233 Result += "_IMPL ";
2234 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002235 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002236
2237 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002238 SourceLocation OnePastCurly =
2239 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2240 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002241 }
2242 cursor++; // past '{'
2243
2244 // Now comment out any visibility specifiers.
2245 while (cursor < endBuf) {
2246 if (*cursor == '@') {
2247 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002248 // Skip whitespace.
2249 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2250 /*scan*/;
2251
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002252 // FIXME: presence of @public, etc. inside comment results in
2253 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002254 if (!strncmp(cursor, "public", strlen("public")) ||
2255 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002256 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002257 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002258 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002259 // FIXME: If there are cases where '<' is used in ivar declaration part
2260 // of user code, then scan the ivar list and use needToScanForQualifiers
2261 // for type checking.
2262 else if (*cursor == '<') {
2263 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002264 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002265 cursor = strchr(cursor, '>');
2266 cursor++;
2267 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002268 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002269 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002270 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002271 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002272 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002273 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002274 } else { // we don't have any instance variables - insert super struct.
2275 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2276 Result += " {\n struct ";
2277 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002278 Result += "_IMPL ";
2279 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002280 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002281 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002282 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002283 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002284 if (!ObjCSynthesizedStructs.insert(CDecl))
2285 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002286}
2287
Ted Kremenek42730c52008-01-07 19:49:32 +00002288// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002289/// class methods.
Ted Kremenek42730c52008-01-07 19:49:32 +00002290void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002291 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002292 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002293 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002294 const char *ClassName,
2295 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002296 if (MethodBegin == MethodEnd) return;
2297
Fariborz Jahanian04455192007-10-22 21:41:37 +00002298 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002299 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002300 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002301 SEL _cmd;
2302 char *method_types;
2303 void *_imp;
2304 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002305 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002306 Result += "\nstruct _objc_method {\n";
2307 Result += "\tSEL _cmd;\n";
2308 Result += "\tchar *method_types;\n";
2309 Result += "\tvoid *_imp;\n";
2310 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002311
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002312 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002313 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002314
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002315 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002316
2317 /* struct {
2318 struct _objc_method_list *next_method;
2319 int method_count;
2320 struct _objc_method method_list[];
2321 }
2322 */
2323 Result += "\nstatic struct {\n";
2324 Result += "\tstruct _objc_method_list *next_method;\n";
2325 Result += "\tint method_count;\n";
2326 Result += "\tstruct _objc_method method_list[";
2327 Result += utostr(MethodEnd-MethodBegin);
2328 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002329 Result += prefix;
2330 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2331 Result += "_METHODS_";
2332 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002333 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002334 Result += IsInstanceMethod ? "inst" : "cls";
2335 Result += "_meth\")))= ";
2336 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002337
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002338 Result += "\t,{{(SEL)\"";
2339 Result += (*MethodBegin)->getSelector().getName().c_str();
2340 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002341 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002342 Result += "\", \"";
2343 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002344 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002345 Result += MethodInternalNames[*MethodBegin];
2346 Result += "}\n";
2347 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2348 Result += "\t ,{(SEL)\"";
2349 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002350 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002351 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002352 Result += "\", \"";
2353 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002354 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002355 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002356 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002357 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002358 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002359}
2360
Ted Kremenek42730c52008-01-07 19:49:32 +00002361/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2362void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002363 int NumProtocols,
2364 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002365 const char *ClassName,
2366 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002367 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002368 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002369 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002370 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002371 // Output struct protocol_methods holder of method selector and type.
Chris Lattner7afba9c2008-03-16 20:19:15 +00002372 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002373 /* struct protocol_methods {
2374 SEL _cmd;
2375 char *method_types;
2376 }
2377 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002378 Result += "\nstruct protocol_methods {\n";
2379 Result += "\tSEL _cmd;\n";
2380 Result += "\tchar *method_types;\n";
2381 Result += "};\n";
2382
Steve Naroff27429432008-03-12 01:06:30 +00002383 objc_protocol_methods = true;
2384 }
Chris Lattner7afba9c2008-03-16 20:19:15 +00002385 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2386 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002387 /* struct _objc_protocol_method_list {
2388 int protocol_method_count;
2389 struct protocol_methods protocols[];
2390 }
2391 */
Steve Naroff27429432008-03-12 01:06:30 +00002392 Result += "\nstatic struct {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002393 Result += "\tint protocol_method_count;\n";
Steve Naroff27429432008-03-12 01:06:30 +00002394 Result += "\tstruct protocol_methods protocols[";
2395 Result += utostr(NumMethods);
2396 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002397 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002398 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002399 "{\n\t" + utostr(NumMethods) + "\n";
2400
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002401 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002402 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002403 E = PDecl->instmeth_end(); I != E; ++I) {
2404 if (I == PDecl->instmeth_begin())
2405 Result += "\t ,{{(SEL)\"";
2406 else
2407 Result += "\t ,{(SEL)\"";
2408 Result += (*I)->getSelector().getName().c_str();
2409 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002410 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002411 Result += "\", \"";
2412 Result += MethodTypeString;
2413 Result += "\"}\n";
2414 }
2415 Result += "\t }\n};\n";
2416 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002417
2418 // Output class methods declared in this protocol.
Chris Lattner7afba9c2008-03-16 20:19:15 +00002419 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahanian04455192007-10-22 21:41:37 +00002420 if (NumMethods > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002421 /* struct _objc_protocol_method_list {
2422 int protocol_method_count;
2423 struct protocol_methods protocols[];
2424 }
2425 */
2426 Result += "\nstatic struct {\n";
2427 Result += "\tint protocol_method_count;\n";
2428 Result += "\tstruct protocol_methods protocols[";
2429 Result += utostr(NumMethods);
2430 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002431 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002432 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002433 "{\n\t";
2434 Result += utostr(NumMethods);
2435 Result += "\n";
2436
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002437 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002438 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002439 E = PDecl->classmeth_end(); I != E; ++I) {
2440 if (I == PDecl->classmeth_begin())
2441 Result += "\t ,{{(SEL)\"";
2442 else
2443 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002444 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002445 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002446 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002447 Result += "\", \"";
2448 Result += MethodTypeString;
2449 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002450 }
2451 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002452 }
2453 // Output:
2454 /* struct _objc_protocol {
2455 // Objective-C 1.0 extensions
2456 struct _objc_protocol_extension *isa;
2457 char *protocol_name;
2458 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002459 struct _objc_protocol_method_list *instance_methods;
2460 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002461 };
2462 */
2463 static bool objc_protocol = false;
2464 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002465 Result += "\nstruct _objc_protocol {\n";
2466 Result += "\tstruct _objc_protocol_extension *isa;\n";
2467 Result += "\tchar *protocol_name;\n";
2468 Result += "\tstruct _objc_protocol **protocol_list;\n";
2469 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2470 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2471 Result += "};\n";
2472
Fariborz Jahanian04455192007-10-22 21:41:37 +00002473 objc_protocol = true;
2474 }
2475
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002476 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2477 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002478 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002479 "{\n\t0, \"";
2480 Result += PDecl->getName();
2481 Result += "\", 0, ";
Chris Lattner7afba9c2008-03-16 20:19:15 +00002482 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00002483 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002484 Result += PDecl->getName();
2485 Result += ", ";
2486 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002487 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002488 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002489 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002490 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002491 Result += PDecl->getName();
2492 Result += "\n";
2493 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002494 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002495 Result += "0\n";
2496 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002497 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002498 // Output the top lovel protocol meta-data for the class.
Steve Naroff27429432008-03-12 01:06:30 +00002499 /* struct _objc_protocol_list {
2500 struct _objc_protocol_list *next;
2501 int protocol_count;
2502 struct _objc_protocol *class_protocols[];
2503 }
2504 */
2505 Result += "\nstatic struct {\n";
2506 Result += "\tstruct _objc_protocol_list *next;\n";
2507 Result += "\tint protocol_count;\n";
2508 Result += "\tstruct _objc_protocol *class_protocols[";
2509 Result += utostr(NumProtocols);
2510 Result += "];\n} _OBJC_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002511 Result += prefix;
2512 Result += "_PROTOCOLS_";
2513 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002514 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002515 "{\n\t0, ";
2516 Result += utostr(NumProtocols);
2517 Result += "\n";
2518
2519 Result += "\t,{&_OBJC_PROTOCOL_";
2520 Result += Protocols[0]->getName();
2521 Result += " \n";
2522
2523 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002524 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff27429432008-03-12 01:06:30 +00002525 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002526 Result += PDecl->getName();
2527 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002528 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002529 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002530 }
2531}
2532
Ted Kremenek42730c52008-01-07 19:49:32 +00002533/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002534/// implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002535void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002536 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002537 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002538 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002539 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002540 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2541 CDecl = CDecl->getNextClassCategory())
2542 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2543 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002544
Chris Lattnera661a4d2007-12-23 01:40:15 +00002545 std::string FullCategoryName = ClassDecl->getName();
2546 FullCategoryName += '_';
2547 FullCategoryName += IDecl->getName();
2548
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002549 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002550 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002551 true, "CATEGORY_", FullCategoryName.c_str(),
2552 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002553
2554 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002555 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002556 false, "CATEGORY_", FullCategoryName.c_str(),
2557 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002558
2559 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002560 // Null CDecl is case of a category implementation with no category interface
2561 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002562 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002563 CDecl->getNumReferencedProtocols(),
2564 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002565 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002566
2567 /* struct _objc_category {
2568 char *category_name;
2569 char *class_name;
2570 struct _objc_method_list *instance_methods;
2571 struct _objc_method_list *class_methods;
2572 struct _objc_protocol_list *protocols;
2573 // Objective-C 1.0 extensions
2574 uint32_t size; // sizeof (struct _objc_category)
2575 struct _objc_property_list *instance_properties; // category's own
2576 // @property decl.
2577 };
2578 */
2579
2580 static bool objc_category = false;
2581 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002582 Result += "\nstruct _objc_category {\n";
2583 Result += "\tchar *category_name;\n";
2584 Result += "\tchar *class_name;\n";
2585 Result += "\tstruct _objc_method_list *instance_methods;\n";
2586 Result += "\tstruct _objc_method_list *class_methods;\n";
2587 Result += "\tstruct _objc_protocol_list *protocols;\n";
2588 Result += "\tunsigned int size;\n";
2589 Result += "\tstruct _objc_property_list *instance_properties;\n";
2590 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002591 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002592 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002593 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2594 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002595 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002596 Result += IDecl->getName();
2597 Result += "\"\n\t, \"";
2598 Result += ClassDecl->getName();
2599 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002600
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002601 if (IDecl->getNumInstanceMethods() > 0) {
2602 Result += "\t, (struct _objc_method_list *)"
2603 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2604 Result += FullCategoryName;
2605 Result += "\n";
2606 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002607 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002608 Result += "\t, 0\n";
2609 if (IDecl->getNumClassMethods() > 0) {
2610 Result += "\t, (struct _objc_method_list *)"
2611 "&_OBJC_CATEGORY_CLASS_METHODS_";
2612 Result += FullCategoryName;
2613 Result += "\n";
2614 }
2615 else
2616 Result += "\t, 0\n";
2617
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002618 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002619 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2620 Result += FullCategoryName;
2621 Result += "\n";
2622 }
2623 else
2624 Result += "\t, 0\n";
2625 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002626}
2627
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002628/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2629/// ivar offset.
Ted Kremenek42730c52008-01-07 19:49:32 +00002630void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2631 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002632 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002633 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002634 Result += IDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002635 if (LangOpts.Microsoft)
2636 Result += "_IMPL";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002637 Result += ", ";
2638 Result += ivar->getName();
2639 Result += ")";
2640}
2641
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002642//===----------------------------------------------------------------------===//
2643// Meta Data Emission
2644//===----------------------------------------------------------------------===//
2645
Ted Kremenek42730c52008-01-07 19:49:32 +00002646void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002647 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002648 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002649
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002650 // Explictly declared @interface's are already synthesized.
2651 if (CDecl->ImplicitInterfaceDecl()) {
2652 // FIXME: Implementation of a class with no @interface (legacy) doese not
2653 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002654 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002655 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002656
Chris Lattnerc7b06752007-12-12 07:56:42 +00002657 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00002658 unsigned NumIvars = !IDecl->ivar_empty()
2659 ? IDecl->ivar_size()
2660 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002661 if (NumIvars > 0) {
2662 static bool objc_ivar = false;
2663 if (!objc_ivar) {
2664 /* struct _objc_ivar {
2665 char *ivar_name;
2666 char *ivar_type;
2667 int ivar_offset;
2668 };
2669 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002670 Result += "\nstruct _objc_ivar {\n";
2671 Result += "\tchar *ivar_name;\n";
2672 Result += "\tchar *ivar_type;\n";
2673 Result += "\tint ivar_offset;\n";
2674 Result += "};\n";
2675
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002676 objc_ivar = true;
2677 }
2678
Steve Naroffc723eec2008-03-11 00:12:29 +00002679 /* struct {
2680 int ivar_count;
2681 struct _objc_ivar ivar_list[nIvars];
2682 };
2683 */
2684 Result += "\nstatic struct {\n";
2685 Result += "\tint ivar_count;\n";
2686 Result += "\tstruct _objc_ivar ivar_list[";
2687 Result += utostr(NumIvars);
2688 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002689 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002690 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002691 "{\n\t";
2692 Result += utostr(NumIvars);
2693 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002694
Ted Kremenek42730c52008-01-07 19:49:32 +00002695 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00002696 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00002697 IVI = IDecl->ivar_begin();
2698 IVE = IDecl->ivar_end();
2699 } else {
2700 IVI = CDecl->ivar_begin();
2701 IVE = CDecl->ivar_end();
2702 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002703 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002704 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002705 Result += "\", \"";
2706 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002707 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2708 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002709 Result += StrEncoding;
2710 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002711 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002712 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002713 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002714 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002715 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002716 Result += "\", \"";
2717 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002718 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2719 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002720 Result += StrEncoding;
2721 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002722 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002723 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002724 }
2725
2726 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002727 }
2728
2729 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002730 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002731 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002732
2733 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002734 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002735 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002736
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002737 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002738 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002739 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002740 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002741
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002742
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002743 // Declaration of class/meta-class metadata
2744 /* struct _objc_class {
2745 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002746 const char *super_class_name;
2747 char *name;
2748 long version;
2749 long info;
2750 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002751 struct _objc_ivar_list *ivars;
2752 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002753 struct objc_cache *cache;
2754 struct objc_protocol_list *protocols;
2755 const char *ivar_layout;
2756 struct _objc_class_ext *ext;
2757 };
2758 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002759 static bool objc_class = false;
2760 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002761 Result += "\nstruct _objc_class {\n";
2762 Result += "\tstruct _objc_class *isa;\n";
2763 Result += "\tconst char *super_class_name;\n";
2764 Result += "\tchar *name;\n";
2765 Result += "\tlong version;\n";
2766 Result += "\tlong info;\n";
2767 Result += "\tlong instance_size;\n";
2768 Result += "\tstruct _objc_ivar_list *ivars;\n";
2769 Result += "\tstruct _objc_method_list *methods;\n";
2770 Result += "\tstruct objc_cache *cache;\n";
2771 Result += "\tstruct _objc_protocol_list *protocols;\n";
2772 Result += "\tconst char *ivar_layout;\n";
2773 Result += "\tstruct _objc_class_ext *ext;\n";
2774 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002775 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002776 }
2777
2778 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002779 ObjCInterfaceDecl *RootClass = 0;
2780 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002781 while (SuperClass) {
2782 RootClass = SuperClass;
2783 SuperClass = SuperClass->getSuperClass();
2784 }
2785 SuperClass = CDecl->getSuperClass();
2786
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002787 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2788 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002789 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002790 "{\n\t(struct _objc_class *)\"";
2791 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2792 Result += "\"";
2793
2794 if (SuperClass) {
2795 Result += ", \"";
2796 Result += SuperClass->getName();
2797 Result += "\", \"";
2798 Result += CDecl->getName();
2799 Result += "\"";
2800 }
2801 else {
2802 Result += ", 0, \"";
2803 Result += CDecl->getName();
2804 Result += "\"";
2805 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002806 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002807 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002808 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002809 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00002810 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002811 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002812 Result += "\n";
2813 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002814 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002815 Result += ", 0\n";
2816 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002817 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002818 Result += CDecl->getName();
2819 Result += ",0,0\n";
2820 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002821 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002822 Result += "\t,0,0,0,0\n";
2823 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002824
2825 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002826 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2827 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002828 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002829 "{\n\t&_OBJC_METACLASS_";
2830 Result += CDecl->getName();
2831 if (SuperClass) {
2832 Result += ", \"";
2833 Result += SuperClass->getName();
2834 Result += "\", \"";
2835 Result += CDecl->getName();
2836 Result += "\"";
2837 }
2838 else {
2839 Result += ", 0, \"";
2840 Result += CDecl->getName();
2841 Result += "\"";
2842 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002843 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002844 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002845 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002846 Result += ",0";
2847 else {
2848 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002849 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002850 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00002851 if (LangOpts.Microsoft)
2852 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002853 Result += ")";
2854 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002855 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00002856 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002857 Result += CDecl->getName();
2858 Result += "\n\t";
2859 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002860 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002861 Result += ",0";
2862 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00002863 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002864 Result += CDecl->getName();
2865 Result += ", 0\n\t";
2866 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002867 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002868 Result += ",0,0";
2869 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002870 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002871 Result += CDecl->getName();
2872 Result += ", 0,0\n";
2873 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002874 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002875 Result += ",0,0,0\n";
2876 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002877}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002878
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002879/// RewriteImplementations - This routine rewrites all method implementations
2880/// and emits meta-data.
2881
2882void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002883 int ClsDefCount = ClassImplementation.size();
2884 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002885
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002886 if (ClsDefCount == 0 && CatDefCount == 0)
2887 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002888 // Rewrite implemented methods
2889 for (int i = 0; i < ClsDefCount; i++)
2890 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002891
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002892 for (int i = 0; i < CatDefCount; i++)
2893 RewriteImplementationDecl(CategoryImplementation[i]);
2894
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002895 // This is needed for use of offsetof
2896 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002897
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002898 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002899 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002900 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002901
2902 // For each implemented category, write out all its meta data.
2903 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002904 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002905
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002906 // Write objc_symtab metadata
2907 /*
2908 struct _objc_symtab
2909 {
2910 long sel_ref_cnt;
2911 SEL *refs;
2912 short cls_def_cnt;
2913 short cat_def_cnt;
2914 void *defs[cls_def_cnt + cat_def_cnt];
2915 };
2916 */
2917
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002918 Result += "\nstruct _objc_symtab {\n";
2919 Result += "\tlong sel_ref_cnt;\n";
2920 Result += "\tSEL *refs;\n";
2921 Result += "\tshort cls_def_cnt;\n";
2922 Result += "\tshort cat_def_cnt;\n";
2923 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2924 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002925
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002926 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00002927 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002928 Result += "\t0, 0, " + utostr(ClsDefCount)
2929 + ", " + utostr(CatDefCount) + "\n";
2930 for (int i = 0; i < ClsDefCount; i++) {
2931 Result += "\t,&_OBJC_CLASS_";
2932 Result += ClassImplementation[i]->getName();
2933 Result += "\n";
2934 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002935
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002936 for (int i = 0; i < CatDefCount; i++) {
2937 Result += "\t,&_OBJC_CATEGORY_";
2938 Result += CategoryImplementation[i]->getClassInterface()->getName();
2939 Result += "_";
2940 Result += CategoryImplementation[i]->getName();
2941 Result += "\n";
2942 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002943
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002944 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002945
2946 // Write objc_module metadata
2947
2948 /*
2949 struct _objc_module {
2950 long version;
2951 long size;
2952 const char *name;
2953 struct _objc_symtab *symtab;
2954 }
2955 */
2956
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002957 Result += "\nstruct _objc_module {\n";
2958 Result += "\tlong version;\n";
2959 Result += "\tlong size;\n";
2960 Result += "\tconst char *name;\n";
2961 Result += "\tstruct _objc_symtab *symtab;\n";
2962 Result += "};\n\n";
2963 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00002964 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002965 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2966 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002967 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00002968
2969 if (LangOpts.Microsoft) {
2970 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2971 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2972 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2973 Result += "&_OBJC_MODULES;\n";
2974 Result += "#pragma data_seg(pop)\n\n";
2975 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002976}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002977