blob: c523b03d5682305d9045fbc72d5fccca1cc730a1 [file] [log] [blame]
Steve Naroff44e81222008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnerb429ae42007-10-11 00:43:27 +00002//
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"
Dan Gohman6da15102008-05-21 20:19:16 +000026#include "llvm/Support/Streams.h"
Chris Lattner673f2bd2008-03-22 00:08:40 +000027#include "llvm/System/Path.h"
Steve Naroff3c7b9a02008-04-14 22:53:48 +000028#include <sstream>
Chris Lattner673f2bd2008-03-22 00:08:40 +000029#include <fstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000030using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000032
Steve Naroff1c46cf12008-01-28 21:34:52 +000033static llvm::cl::opt<bool>
34SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
35 llvm::cl::desc("Silence ObjC rewriting warnings"));
36
Chris Lattnerb429ae42007-10-11 00:43:27 +000037namespace {
Steve Naroff44e81222008-04-14 22:03:09 +000038 class RewriteObjC : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000039 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000040 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000041 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000042 unsigned RewriteFailedDiag;
43
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000044 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000045 SourceManager *SM;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000046 TranslationUnitDecl *TUDecl;
Chris Lattner569faa62007-10-11 18:38:32 +000047 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000048 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000049 SourceLocation LastIncLoc;
Steve Narofffef037c2008-03-27 22:29:16 +000050
Ted Kremenek42730c52008-01-07 19:49:32 +000051 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
52 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
53 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff04eaa192008-05-06 18:26:51 +000054 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek42730c52008-01-07 19:49:32 +000055 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
56 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000057 llvm::SmallVector<Stmt *, 32> Stmts;
58 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian248db262008-01-22 22:44:46 +000059 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffe9780582007-10-23 23:50:29 +000060
Steve Naroff47e7fa22008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffe9780582007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000074
Steve Naroff0add5d22007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroff0add5d22007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000078
Fariborz Jahanian22277422008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff764c1ae2007-11-15 10:28:18 +000082 // Needed for super.
Ted Kremenek42730c52008-01-07 19:49:32 +000083 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000086
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Narofffef037c2008-03-27 22:29:16 +000093 std::string Preamble;
94
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000095 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000096 public:
Chris Lattner12499682008-01-31 19:38:44 +000097 void Initialize(ASTContext &context);
98
Chris Lattner569faa62007-10-11 18:38:32 +000099
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000100 // Top Level Driver code.
101 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000102 void HandleDeclInMainFile(Decl *D);
Steve Naroff44e81222008-04-14 22:03:09 +0000103 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000104 Diagnostic &D, const LangOptions &LOpts);
Steve Naroff44e81222008-04-14 22:03:09 +0000105 ~RewriteObjC();
Chris Lattnerb1548372008-01-31 19:37:57 +0000106
107 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattner6216f292008-01-31 19:42:41 +0000108 // If replacement succeeded or warning disabled return with no warning.
109 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerb1548372008-01-31 19:37:57 +0000110 return;
111
Chris Lattnerb1548372008-01-31 19:37:57 +0000112 SourceRange Range = Old->getSourceRange();
113 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
114 0, 0, &Range, 1);
115 }
116
Steve Narofffef037c2008-03-27 22:29:16 +0000117 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
118 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000119 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000120 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000121 SilenceRewriteMacroWarning)
122 return;
123
124 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
125 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000126
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000127 void RemoveText(SourceLocation Loc, unsigned StrLen) {
128 // If removal succeeded or warning disabled return with no warning.
129 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
130 return;
131
132 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
133 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000134
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000135 void ReplaceText(SourceLocation Start, unsigned OrigLength,
136 const char *NewStr, unsigned NewLength) {
137 // If removal succeeded or warning disabled return with no warning.
138 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
139 SilenceRewriteMacroWarning)
140 return;
141
142 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
143 }
144
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000145 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000146 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000147 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000148 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000149 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
150 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000151 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000152 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
153 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
154 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
155 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
156 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattnercffe3662008-03-16 21:23:50 +0000157 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000158 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000159 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000160 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000161 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000162 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000163 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000164 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000165
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000166 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000167 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000168 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000169 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff296b74f2007-11-05 14:50:49 +0000170 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000171 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000172 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000173 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000174 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000175 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000176 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
177 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
178 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000179 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
180 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000181 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
182 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000183 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000184 Stmt *RewriteBreakStmt(BreakStmt *S);
185 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000186 void SynthCountByEnumWithState(std::string &buf);
187
Steve Naroff02a82aa2007-10-30 23:14:51 +0000188 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000189 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000190 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000191 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000192 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000193 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000194 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000195 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000196 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000197 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000198
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000199 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000200 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000201 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000202
Ted Kremenek42730c52008-01-07 19:49:32 +0000203 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000204 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000205
Ted Kremenek42730c52008-01-07 19:49:32 +0000206 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
207 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000208 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000209 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000210 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000211 const char *ClassName,
212 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000213
Ted Kremenek42730c52008-01-07 19:49:32 +0000214 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000215 int NumProtocols,
216 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000217 const char *ClassName,
218 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000219 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000220 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000221 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
222 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000223 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000224 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000225 };
226}
227
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000228static bool IsHeaderFile(const std::string &Filename) {
229 std::string::size_type DotPos = Filename.rfind('.');
230
231 if (DotPos == std::string::npos) {
232 // no file extension
233 return false;
234 }
235
236 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
237 // C header: .h
238 // C++ header: .hh or .H;
239 return Ext == "h" || Ext == "hh" || Ext == "H";
240}
241
Steve Naroff44e81222008-04-14 22:03:09 +0000242RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000243 Diagnostic &D, const LangOptions &LOpts)
244 : Diags(D), LangOpts(LOpts) {
245 IsHeader = IsHeaderFile(inFile);
246 InFileName = inFile;
247 OutFileName = outFile;
248 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
249 "rewriting sub-expression within a macro (may not be correct)");
250}
251
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000252ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000253 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000254 Diagnostic &Diags,
255 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000256 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000257}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000258
Steve Naroff44e81222008-04-14 22:03:09 +0000259void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000260 Context = &context;
261 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000262 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000263 MsgSendFunctionDecl = 0;
264 MsgSendSuperFunctionDecl = 0;
265 MsgSendStretFunctionDecl = 0;
266 MsgSendSuperStretFunctionDecl = 0;
267 MsgSendFpretFunctionDecl = 0;
268 GetClassFunctionDecl = 0;
269 GetMetaClassFunctionDecl = 0;
270 SelGetUidFunctionDecl = 0;
271 CFStringFunctionDecl = 0;
272 GetProtocolFunctionDecl = 0;
273 ConstantStringClassReference = 0;
274 NSStringRecord = 0;
275 CurMethodDecl = 0;
276 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000277 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000278 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000279 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000280 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000281
282 // Get the ID and start/end of the main file.
283 MainFileID = SM->getMainFileID();
284 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
285 MainFileStart = MainBuf->getBufferStart();
286 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000287
Chris Lattner12499682008-01-31 19:38:44 +0000288 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000289
Chris Lattner12499682008-01-31 19:38:44 +0000290 // declaring objc_selector outside the parameter list removes a silly
291 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000292 if (IsHeader)
293 Preamble = "#pragma once\n";
294 Preamble += "struct objc_selector; struct objc_class;\n";
295 Preamble += "#ifndef OBJC_SUPER\n";
296 Preamble += "struct objc_super { struct objc_object *object; ";
297 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000298 if (LangOpts.Microsoft) {
299 // Add a constructor for creating temporary objects.
Steve Narofffef037c2008-03-27 22:29:16 +0000300 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
301 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000302 }
Steve Narofffef037c2008-03-27 22:29:16 +0000303 Preamble += "};\n";
304 Preamble += "#define OBJC_SUPER\n";
305 Preamble += "#endif\n";
306 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
307 Preamble += "typedef struct objc_object Protocol;\n";
308 Preamble += "#define _REWRITER_typedef_Protocol\n";
309 Preamble += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000310 if (LangOpts.Microsoft)
Steve Naroff618c6a42008-05-06 22:45:19 +0000311 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
312 else
313 Preamble += "#define __OBJC_RW_EXTERN extern\n";
314 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000315 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000316 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000317 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000318 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000319 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000320 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000321 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff31316a12008-05-08 22:02:18 +0000322 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000323 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroffa9636222008-05-08 17:52:16 +0000324 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000325 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000326 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000327 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000328 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
329 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
330 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
331 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
332 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000333 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000334 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000335 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
336 Preamble += "struct __objcFastEnumerationState {\n\t";
337 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000338 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000339 Preamble += "unsigned long *mutationsPtr;\n\t";
340 Preamble += "unsigned long extra[5];\n};\n";
341 Preamble += "#define __FASTENUMERATIONSTATE\n";
342 Preamble += "#endif\n";
343 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
344 Preamble += "struct __NSConstantStringImpl {\n";
345 Preamble += " int *isa;\n";
346 Preamble += " int flags;\n";
347 Preamble += " char *str;\n";
348 Preamble += " long length;\n";
349 Preamble += "};\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000350 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000351 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
352 Preamble += "#endif\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000353 if (LangOpts.Microsoft) {
354 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000355 Preamble += "#define __attribute__(X)\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000356 }
Chris Lattner12499682008-01-31 19:38:44 +0000357}
358
359
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000360//===----------------------------------------------------------------------===//
361// Top Level Driver Code
362//===----------------------------------------------------------------------===//
363
Steve Naroff44e81222008-04-14 22:03:09 +0000364void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000365 // Two cases: either the decl could be in the main file, or it could be in a
366 // #included file. If the former, rewrite it now. If the later, check to see
367 // if we rewrote the #include/#import.
368 SourceLocation Loc = D->getLocation();
369 Loc = SM->getLogicalLoc(Loc);
370
371 // If this is for a builtin, ignore it.
372 if (Loc.isInvalid()) return;
373
Steve Naroffe9780582007-10-23 23:50:29 +0000374 // Look for built-in declarations that we need to refer during the rewrite.
375 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000376 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000377 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000378 // declared in <Foundation/NSString.h>
379 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
380 ConstantStringClassReference = FVD;
381 return;
382 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000383 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000384 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000385 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000386 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000387 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000388 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000389 } else if (ObjCForwardProtocolDecl *FP =
390 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000391 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000392 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000393 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000394 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000395 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000396}
397
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000398/// HandleDeclInMainFile - This is called for each top-level decl defined in the
399/// main file of the input.
Steve Naroff44e81222008-04-14 22:03:09 +0000400void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000401 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
402 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000403 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000404
Ted Kremenek42730c52008-01-07 19:49:32 +0000405 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000406 if (Stmt *Body = MD->getBody()) {
407 //Body->dump();
408 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000409 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000410 CurMethodDecl = 0;
411 }
Steve Naroff18c83382007-11-13 23:01:27 +0000412 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000413 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000414 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000415 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000416 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000417 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000418 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000419 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000420 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000421 if (VD->getInit())
422 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
423 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000424 // Nothing yet.
425}
426
Steve Naroff44e81222008-04-14 22:03:09 +0000427RewriteObjC::~RewriteObjC() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000428 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000429
430 // Rewrite tabs if we care.
431 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000432
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000433 if (Diags.hasErrorOccurred())
434 return;
435
436 // Create the output file.
437
438 std::ostream *OutFile;
439 if (OutFileName == "-") {
440 OutFile = llvm::cout.stream();
441 } else if (!OutFileName.empty()) {
442 OutFile = new std::ofstream(OutFileName.c_str(),
443 std::ios_base::binary|std::ios_base::out);
444 } else if (InFileName == "-") {
445 OutFile = llvm::cout.stream();
446 } else {
447 llvm::sys::Path Path(InFileName);
448 Path.eraseSuffix();
449 Path.appendSuffix("cpp");
450 OutFile = new std::ofstream(Path.toString().c_str(),
451 std::ios_base::binary|std::ios_base::out);
452 }
453
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000454 RewriteInclude();
455
Steve Narofffef037c2008-03-27 22:29:16 +0000456 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
457 Preamble.c_str(), Preamble.size(), false);
458
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000459 // Rewrite Objective-c meta data*
460 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000461 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000462
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000463 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
464 // we are done.
465 if (const RewriteBuffer *RewriteBuf =
466 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000467 //printf("Changed:\n");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000468 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000469 } else {
Chris Lattner673f2bd2008-03-22 00:08:40 +0000470 fprintf(stderr, "No changes\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000471 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000472 // Emit metadata.
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000473 *OutFile << ResultStr;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000474}
475
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000476//===----------------------------------------------------------------------===//
477// Syntactic (non-AST) Rewriting Code
478//===----------------------------------------------------------------------===//
479
Steve Naroff44e81222008-04-14 22:03:09 +0000480void RewriteObjC::RewriteInclude() {
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000481 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
482 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
483 const char *MainBufStart = MainBuf.first;
484 const char *MainBufEnd = MainBuf.second;
485 size_t ImportLen = strlen("import");
486 size_t IncludeLen = strlen("include");
487
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000488 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000489 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
490 if (*BufPtr == '#') {
491 if (++BufPtr == MainBufEnd)
492 return;
493 while (*BufPtr == ' ' || *BufPtr == '\t')
494 if (++BufPtr == MainBufEnd)
495 return;
496 if (!strncmp(BufPtr, "import", ImportLen)) {
497 // replace import with include
498 SourceLocation ImportLoc =
499 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000500 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000501 BufPtr += ImportLen;
502 }
503 }
504 }
Chris Lattner74db1682007-10-16 21:07:07 +0000505}
506
Steve Naroff44e81222008-04-14 22:03:09 +0000507void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000508 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
509 const char *MainBufStart = MainBuf.first;
510 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000511
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000512 // Loop over the whole file, looking for tabs.
513 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
514 if (*BufPtr != '\t')
515 continue;
516
517 // Okay, we found a tab. This tab will turn into at least one character,
518 // but it depends on which 'virtual column' it is in. Compute that now.
519 unsigned VCol = 0;
520 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
521 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
522 ++VCol;
523
524 // Okay, now that we know the virtual column, we know how many spaces to
525 // insert. We assume 8-character tab-stops.
526 unsigned Spaces = 8-(VCol & 7);
527
528 // Get the location of the tab.
529 SourceLocation TabLoc =
530 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
531
532 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000533 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000534 }
Chris Lattner569faa62007-10-11 18:38:32 +0000535}
536
537
Steve Naroff44e81222008-04-14 22:03:09 +0000538void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000539 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000540 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000541
542 // Get the start location and compute the semi location.
543 SourceLocation startLoc = ClassDecl->getLocation();
544 const char *startBuf = SM->getCharacterData(startLoc);
545 const char *semiPtr = strchr(startBuf, ';');
546
547 // Translate to typedef's that forward reference structs with the same name
548 // as the class. As a convenience, we include the original declaration
549 // as a comment.
550 std::string typedefString;
551 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000552 typedefString.append(startBuf, semiPtr-startBuf+1);
553 typedefString += "\n";
554 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000555 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000556 typedefString += "#ifndef _REWRITER_typedef_";
557 typedefString += ForwardDecl->getName();
558 typedefString += "\n";
559 typedefString += "#define _REWRITER_typedef_";
560 typedefString += ForwardDecl->getName();
561 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000562 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000563 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000564 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000565 }
566
567 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000568 ReplaceText(startLoc, semiPtr-startBuf+1,
569 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000570}
571
Steve Naroff44e81222008-04-14 22:03:09 +0000572void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000573 SourceLocation LocStart = Method->getLocStart();
574 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000575
Steve Naroff2ce399a2007-12-14 23:37:57 +0000576 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattner6216f292008-01-31 19:42:41 +0000577 InsertText(LocStart, "/* ", 3);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000578 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000579 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000580 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000581 }
582}
583
Steve Naroff44e81222008-04-14 22:03:09 +0000584void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000585{
Chris Lattnercffe3662008-03-16 21:23:50 +0000586 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000587 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000588 SourceLocation Loc = Property->getLocation();
589
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000590 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000591
592 // FIXME: handle properties that are declared across multiple lines.
593 }
594}
595
Steve Naroff44e81222008-04-14 22:03:09 +0000596void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000597 SourceLocation LocStart = CatDecl->getLocStart();
598
599 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000600 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000601
Ted Kremenek42730c52008-01-07 19:49:32 +0000602 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000603 E = CatDecl->instmeth_end(); I != E; ++I)
604 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000605 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000606 E = CatDecl->classmeth_end(); I != E; ++I)
607 RewriteMethodDeclaration(*I);
608
Steve Naroff667f1682007-10-30 13:30:57 +0000609 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000610 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000611}
612
Steve Naroff44e81222008-04-14 22:03:09 +0000613void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000614 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000615
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000616 SourceLocation LocStart = PDecl->getLocStart();
617
618 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000619 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000620
Ted Kremenek42730c52008-01-07 19:49:32 +0000621 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000622 E = PDecl->instmeth_end(); I != E; ++I)
623 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000624 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000625 E = PDecl->classmeth_end(); I != E; ++I)
626 RewriteMethodDeclaration(*I);
627
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000628 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000629 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000630 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000631
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000632 // Must comment out @optional/@required
633 const char *startBuf = SM->getCharacterData(LocStart);
634 const char *endBuf = SM->getCharacterData(LocEnd);
635 for (const char *p = startBuf; p < endBuf; p++) {
636 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
637 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000638 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000639 ReplaceText(OptionalLoc, strlen("@optional"),
640 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000641
642 }
643 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
644 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000645 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000646 ReplaceText(OptionalLoc, strlen("@required"),
647 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000648
649 }
650 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000651}
652
Steve Naroff44e81222008-04-14 22:03:09 +0000653void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000654 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000655 if (LocStart.isInvalid())
656 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000657 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000658 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000659}
660
Steve Naroff44e81222008-04-14 22:03:09 +0000661void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000662 std::string &ResultStr) {
663 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000664 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000665 ResultStr += "id";
666 else
667 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000668 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000669
670 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000671 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000672
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000673 if (OMD->isInstance())
674 NameStr += "_I_";
675 else
676 NameStr += "_C_";
677
678 NameStr += OMD->getClassInterface()->getName();
679 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000680
681 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000682 if (ObjCCategoryImplDecl *CID =
683 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000684 NameStr += CID->getName();
685 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000686 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000687 // Append selector names, replacing ':' with '_'
688 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000689 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000690 else {
691 std::string selString = OMD->getSelector().getName();
692 int len = selString.size();
693 for (int i = 0; i < len; i++)
694 if (selString[i] == ':')
695 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000696 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000697 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000698 // Remember this name for metadata emission
699 MethodInternalNames[OMD] = NameStr;
700 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000701
702 // Rewrite arguments
703 ResultStr += "(";
704
705 // invisible arguments
706 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000707 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000708 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000709 if (!LangOpts.Microsoft) {
710 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
711 ResultStr += "struct ";
712 }
713 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroffde0da102008-03-10 23:16:54 +0000714 ResultStr += OMD->getClassInterface()->getName();
Steve Naroffde0da102008-03-10 23:16:54 +0000715 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000716 }
717 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000718 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000719
720 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000721 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000722 ResultStr += " _cmd";
723
724 // Method arguments.
Chris Lattner685d7922008-03-16 01:07:14 +0000725 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000726 ParmVarDecl *PDecl = OMD->getParamDecl(i);
727 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000728 if (PDecl->getType()->isObjCQualifiedIdType()) {
729 ResultStr += "id ";
730 ResultStr += PDecl->getName();
731 } else {
732 std::string Name = PDecl->getName();
733 PDecl->getType().getAsStringInternal(Name);
734 ResultStr += Name;
735 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000736 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000737 if (OMD->isVariadic())
738 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000739 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000740
741}
Steve Naroff44e81222008-04-14 22:03:09 +0000742void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000743 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
744 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000745
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000746 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000747 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000748 else
Chris Lattner6216f292008-01-31 19:42:41 +0000749 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000750
Ted Kremenek42730c52008-01-07 19:49:32 +0000751 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000752 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
753 E = IMD ? IMD->instmeth_end() : CID->instmeth_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 }
765
Ted Kremenek42730c52008-01-07 19:49:32 +0000766 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000767 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
768 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000769 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000770 ObjCMethodDecl *OMD = *I;
771 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000772 SourceLocation LocStart = OMD->getLocStart();
773 SourceLocation LocEnd = OMD->getBody()->getLocStart();
774
775 const char *startBuf = SM->getCharacterData(LocStart);
776 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000777 ReplaceText(LocStart, endBuf-startBuf,
778 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000779 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000780 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000781 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000782 else
Chris Lattner6216f292008-01-31 19:42:41 +0000783 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000784}
785
Steve Naroff44e81222008-04-14 22:03:09 +0000786void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000787 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000788 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000789 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000790 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000791 ResultStr += ClassDecl->getName();
792 ResultStr += "\n";
793 ResultStr += "#define _REWRITER_typedef_";
794 ResultStr += ClassDecl->getName();
795 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000796 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000797 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000798 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000799 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000800 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000801 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000802 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000803
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000804 RewriteProperties(ClassDecl->getNumPropertyDecl(),
805 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000806 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000807 E = ClassDecl->instmeth_end(); I != E; ++I)
808 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000809 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000810 E = ClassDecl->classmeth_end(); I != E; ++I)
811 RewriteMethodDeclaration(*I);
812
Steve Naroff1ccf4632007-10-30 03:43:13 +0000813 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000814 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000815}
816
Chris Lattner343c82b2008-05-23 20:40:52 +0000817Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
818 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000819 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000820 if (CurMethodDecl) {
821 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000822 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
823 // lookup which class implements the instance variable.
824 ObjCInterfaceDecl *clsDeclared = 0;
825 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
826 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
827
828 // Synthesize an explicit cast to gain access to the ivar.
829 std::string RecName = clsDeclared->getIdentifier()->getName();
830 RecName += "_IMPL";
831 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
832 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
833 SourceLocation(), II, 0);
834 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
835 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
836 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
837 // Don't forget the parens to enforce the proper binding.
Chris Lattner343c82b2008-05-23 20:40:52 +0000838 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
839 IV->getBase()->getLocEnd(),
840 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +0000841 if (IV->isFreeIvar() &&
842 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner343c82b2008-05-23 20:40:52 +0000843 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
844 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +0000845 ReplaceStmt(IV, ME);
846 delete IV;
847 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +0000848 }
Chris Lattner343c82b2008-05-23 20:40:52 +0000849
850 ReplaceStmt(IV->getBase(), PE);
851 // Cannot delete IV->getBase(), since PE points to it.
852 // Replace the old base with the cast. This is important when doing
853 // embedded rewrites. For example, [newInv->_container addObject:0].
854 IV->setBase(PE);
855 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000856 }
Steve Naroffe6155362008-04-18 21:55:08 +0000857 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +0000858 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
859
860 // Explicit ivar refs need to have a cast inserted.
861 // FIXME: consider sharing some of this code with the code above.
862 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000863 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +0000864 // lookup which class implements the instance variable.
865 ObjCInterfaceDecl *clsDeclared = 0;
Steve Naroffa9636222008-05-08 17:52:16 +0000866 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000867 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
868
869 // Synthesize an explicit cast to gain access to the ivar.
870 std::string RecName = clsDeclared->getIdentifier()->getName();
871 RecName += "_IMPL";
872 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
873 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
874 SourceLocation(), II, 0);
875 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
876 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
877 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
878 // Don't forget the parens to enforce the proper binding.
Chris Lattner3cca6612008-05-28 16:38:23 +0000879 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
880 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000881 ReplaceStmt(IV->getBase(), PE);
882 // Cannot delete IV->getBase(), since PE points to it.
883 // Replace the old base with the cast. This is important when doing
884 // embedded rewrites. For example, [newInv->_container addObject:0].
885 IV->setBase(PE);
886 return IV;
887 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000888 }
Steve Naroffe6155362008-04-18 21:55:08 +0000889 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000890}
891
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000892//===----------------------------------------------------------------------===//
893// Function Body / Expression rewriting
894//===----------------------------------------------------------------------===//
895
Steve Naroff44e81222008-04-14 22:03:09 +0000896Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000897 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
898 isa<DoStmt>(S) || isa<ForStmt>(S))
899 Stmts.push_back(S);
900 else if (isa<ObjCForCollectionStmt>(S)) {
901 Stmts.push_back(S);
902 ObjCBcLabelNo.push_back(++BcLabelCount);
903 }
904
Chris Lattner343c82b2008-05-23 20:40:52 +0000905 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner2c022162008-01-31 05:10:40 +0000906
907 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000908 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
909 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000910 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000911 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000912 if (newStmt)
913 *CI = newStmt;
914 }
Steve Naroffe9780582007-10-23 23:50:29 +0000915
916 // Handle specific things.
917 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
918 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000919
920 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner343c82b2008-05-23 20:40:52 +0000921 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroff296b74f2007-11-05 14:50:49 +0000922
923 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
924 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000925
Steve Naroff0add5d22007-11-03 11:27:19 +0000926 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
927 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000928
Steve Naroff71226032007-10-24 22:48:43 +0000929 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
930 // Before we rewrite it, put the original message expression in a comment.
931 SourceLocation startLoc = MessExpr->getLocStart();
932 SourceLocation endLoc = MessExpr->getLocEnd();
933
934 const char *startBuf = SM->getCharacterData(startLoc);
935 const char *endBuf = SM->getCharacterData(endLoc);
936
937 std::string messString;
938 messString += "// ";
939 messString.append(startBuf, endBuf-startBuf+1);
940 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000941
Chris Lattner6216f292008-01-31 19:42:41 +0000942 // FIXME: Missing definition of
943 // InsertText(clang::SourceLocation, char const*, unsigned int).
944 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff71226032007-10-24 22:48:43 +0000945 // Tried this, but it didn't work either...
Chris Lattner6216f292008-01-31 19:42:41 +0000946 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000947 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000948 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000949
Ted Kremenek42730c52008-01-07 19:49:32 +0000950 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
951 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000952
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000953 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
954 return RewriteObjCSynchronizedStmt(StmtTry);
955
Ted Kremenek42730c52008-01-07 19:49:32 +0000956 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
957 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000958
959 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
960 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000961
962 if (ObjCForCollectionStmt *StmtForCollection =
963 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner343c82b2008-05-23 20:40:52 +0000964 return RewriteObjCForCollectionStmt(StmtForCollection,
965 OrigStmtRange.getEnd());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000966 if (BreakStmt *StmtBreakStmt =
967 dyn_cast<BreakStmt>(S))
968 return RewriteBreakStmt(StmtBreakStmt);
969 if (ContinueStmt *StmtContinueStmt =
970 dyn_cast<ContinueStmt>(S))
971 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000972
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000973 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
974 isa<DoStmt>(S) || isa<ForStmt>(S)) {
975 assert(!Stmts.empty() && "Statement stack is empty");
976 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
977 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
978 && "Statement stack mismatch");
979 Stmts.pop_back();
980 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000981#if 0
982 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
983 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
984 // Get the new text.
985 std::ostringstream Buf;
986 Replacement->printPretty(Buf);
987 const std::string &Str = Buf.str();
988
989 printf("CAST = %s\n", &Str[0]);
Chris Lattner6216f292008-01-31 19:42:41 +0000990 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff764c1ae2007-11-15 10:28:18 +0000991 delete S;
992 return Replacement;
993 }
994#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000995 // Return this stmt unmodified.
996 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000997}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000998
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000999/// SynthCountByEnumWithState - To print:
1000/// ((unsigned int (*)
1001/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1002/// (void *)objc_msgSend)((id)l_collection,
1003/// sel_registerName(
1004/// "countByEnumeratingWithState:objects:count:"),
1005/// &enumState,
1006/// (id *)items, (unsigned int)16)
1007///
Steve Naroff44e81222008-04-14 22:03:09 +00001008void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001009 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1010 "id *, unsigned int))(void *)objc_msgSend)";
1011 buf += "\n\t\t";
1012 buf += "((id)l_collection,\n\t\t";
1013 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1014 buf += "\n\t\t";
1015 buf += "&enumState, "
1016 "(id *)items, (unsigned int)16)";
1017}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001018
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001019/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1020/// statement to exit to its outer synthesized loop.
1021///
Steve Naroff44e81222008-04-14 22:03:09 +00001022Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001023 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1024 return S;
1025 // replace break with goto __break_label
1026 std::string buf;
1027
1028 SourceLocation startLoc = S->getLocStart();
1029 buf = "goto __break_label_";
1030 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001031 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001032
1033 return 0;
1034}
1035
1036/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1037/// statement to continue with its inner synthesized loop.
1038///
Steve Naroff44e81222008-04-14 22:03:09 +00001039Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001040 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1041 return S;
1042 // replace continue with goto __continue_label
1043 std::string buf;
1044
1045 SourceLocation startLoc = S->getLocStart();
1046 buf = "goto __continue_label_";
1047 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001048 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001049
1050 return 0;
1051}
1052
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001053/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001054/// It rewrites:
1055/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001056
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001057/// Into:
1058/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001059/// type elem;
1060/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001061/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001062/// id l_collection = (id)collection;
1063/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1064/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001065/// if (limit) {
1066/// unsigned long startMutations = *enumState.mutationsPtr;
1067/// do {
1068/// unsigned long counter = 0;
1069/// do {
1070/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001071/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001072/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001073/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001074/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001075/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001076/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1077/// objects:items count:16]);
1078/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001079/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001080/// }
1081/// else
1082/// elem = nil;
1083/// }
1084///
Steve Naroff44e81222008-04-14 22:03:09 +00001085Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001086 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001087 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1088 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1089 "ObjCForCollectionStmt Statement stack mismatch");
1090 assert(!ObjCBcLabelNo.empty() &&
1091 "ObjCForCollectionStmt - Label No stack empty");
1092
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001093 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001094 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001095 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001096 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001097 std::string buf;
1098 buf = "\n{\n\t";
1099 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1100 // type elem;
1101 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001102 elementTypeAsString = ElementType.getAsString();
1103 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001104 buf += " ";
1105 elementName = DS->getDecl()->getName();
1106 buf += elementName;
1107 buf += ";\n\t";
1108 }
Chris Lattner690c2872008-04-08 05:52:18 +00001109 else {
1110 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001111 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001112 elementTypeAsString = DR->getDecl()->getType().getAsString();
1113 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001114
1115 // struct __objcFastEnumerationState enumState = { 0 };
1116 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1117 // id items[16];
1118 buf += "id items[16];\n\t";
1119 // id l_collection = (id)
1120 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001121 // Find start location of 'collection' the hard way!
1122 const char *startCollectionBuf = startBuf;
1123 startCollectionBuf += 3; // skip 'for'
1124 startCollectionBuf = strchr(startCollectionBuf, '(');
1125 startCollectionBuf++; // skip '('
1126 // find 'in' and skip it.
1127 while (*startCollectionBuf != ' ' ||
1128 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1129 (*(startCollectionBuf+3) != ' ' &&
1130 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1131 startCollectionBuf++;
1132 startCollectionBuf += 3;
1133
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001134 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001135 ReplaceText(startLoc, startCollectionBuf - startBuf,
1136 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001137 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001138 SourceLocation rightParenLoc = S->getRParenLoc();
1139 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1140 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001141 buf = ";\n\t";
1142
1143 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1144 // objects:items count:16];
1145 // which is synthesized into:
1146 // unsigned int limit =
1147 // ((unsigned int (*)
1148 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1149 // (void *)objc_msgSend)((id)l_collection,
1150 // sel_registerName(
1151 // "countByEnumeratingWithState:objects:count:"),
1152 // (struct __objcFastEnumerationState *)&state,
1153 // (id *)items, (unsigned int)16);
1154 buf += "unsigned long limit =\n\t\t";
1155 SynthCountByEnumWithState(buf);
1156 buf += ";\n\t";
1157 /// if (limit) {
1158 /// unsigned long startMutations = *enumState.mutationsPtr;
1159 /// do {
1160 /// unsigned long counter = 0;
1161 /// do {
1162 /// if (startMutations != *enumState.mutationsPtr)
1163 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001164 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001165 buf += "if (limit) {\n\t";
1166 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1167 buf += "do {\n\t\t";
1168 buf += "unsigned long counter = 0;\n\t\t";
1169 buf += "do {\n\t\t\t";
1170 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1171 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1172 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001173 buf += " = (";
1174 buf += elementTypeAsString;
1175 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001176 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001177 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001178
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001179 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001180 /// } while (counter < limit);
1181 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1182 /// objects:items count:16]);
1183 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001184 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001185 /// }
1186 /// else
1187 /// elem = nil;
1188 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001189 ///
1190 buf = ";\n\t";
1191 buf += "__continue_label_";
1192 buf += utostr(ObjCBcLabelNo.back());
1193 buf += ": ;";
1194 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001195 buf += "} while (counter < limit);\n\t";
1196 buf += "} while (limit = ";
1197 SynthCountByEnumWithState(buf);
1198 buf += ");\n\t";
1199 buf += elementName;
1200 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001201 buf += "__break_label_";
1202 buf += utostr(ObjCBcLabelNo.back());
1203 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001204 buf += "}\n\t";
1205 buf += "else\n\t\t";
1206 buf += elementName;
1207 buf += " = nil;\n";
1208 buf += "}\n";
1209 // Insert all these *after* the statement body.
Chris Lattner2c022162008-01-31 05:10:40 +00001210 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattner6216f292008-01-31 19:42:41 +00001211 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001212 Stmts.pop_back();
1213 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001214 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001215}
1216
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001217/// RewriteObjCSynchronizedStmt -
1218/// This routine rewrites @synchronized(expr) stmt;
1219/// into:
1220/// objc_sync_enter(expr);
1221/// @try stmt @finally { objc_sync_exit(expr); }
1222///
Steve Naroff44e81222008-04-14 22:03:09 +00001223Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001224 // Get the start location and compute the semi location.
1225 SourceLocation startLoc = S->getLocStart();
1226 const char *startBuf = SM->getCharacterData(startLoc);
1227
1228 assert((*startBuf == '@') && "bogus @synchronized location");
1229
1230 std::string buf;
1231 buf = "objc_sync_enter";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001232 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001233 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1234 const char *endBuf = SM->getCharacterData(endLoc);
1235 endBuf++;
1236 const char *rparenBuf = strchr(endBuf, ')');
1237 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1238 buf = ");\n";
1239 // declare a new scope with two variables, _stack and _rethrow.
1240 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1241 buf += "int buf[18/*32-bit i386*/];\n";
1242 buf += "char *pointers[4];} _stack;\n";
1243 buf += "id volatile _rethrow = 0;\n";
1244 buf += "objc_exception_try_enter(&_stack);\n";
1245 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001246 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001247 startLoc = S->getSynchBody()->getLocEnd();
1248 startBuf = SM->getCharacterData(startLoc);
1249
1250 assert((*startBuf == '}') && "bogus @try block");
1251 SourceLocation lastCurlyLoc = startLoc;
1252 buf = "}\nelse {\n";
1253 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1254 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1255 // FIXME: This must be objc_sync_exit(syncExpr);
1256 buf += " objc_sync_exit();\n";
1257 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1258 buf += "}\n";
1259 buf += "}";
1260
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001261 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001262 return 0;
1263}
1264
Steve Naroff44e81222008-04-14 22:03:09 +00001265Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001266 // Get the start location and compute the semi location.
1267 SourceLocation startLoc = S->getLocStart();
1268 const char *startBuf = SM->getCharacterData(startLoc);
1269
1270 assert((*startBuf == '@') && "bogus @try location");
1271
1272 std::string buf;
1273 // declare a new scope with two variables, _stack and _rethrow.
1274 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1275 buf += "int buf[18/*32-bit i386*/];\n";
1276 buf += "char *pointers[4];} _stack;\n";
1277 buf += "id volatile _rethrow = 0;\n";
1278 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001279 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001280
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001281 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001282
1283 startLoc = S->getTryBody()->getLocEnd();
1284 startBuf = SM->getCharacterData(startLoc);
1285
1286 assert((*startBuf == '}') && "bogus @try block");
1287
1288 SourceLocation lastCurlyLoc = startLoc;
1289
1290 startLoc = startLoc.getFileLocWithOffset(1);
1291 buf = " /* @catch begin */ else {\n";
1292 buf += " id _caught = objc_exception_extract(&_stack);\n";
1293 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001294 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001295 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1296 buf += " else { /* @catch continue */";
1297
Chris Lattner6216f292008-01-31 19:42:41 +00001298 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001299
1300 bool sawIdTypedCatch = false;
1301 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001302 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001303 while (catchList) {
1304 Stmt *catchStmt = catchList->getCatchParamStmt();
1305
1306 if (catchList == S->getCatchStmts())
1307 buf = "if ("; // we are generating code for the first catch clause
1308 else
1309 buf = "else if (";
1310 startLoc = catchList->getLocStart();
1311 startBuf = SM->getCharacterData(startLoc);
1312
1313 assert((*startBuf == '@') && "bogus @catch location");
1314
1315 const char *lParenLoc = strchr(startBuf, '(');
1316
Steve Naroff397c4ce2008-02-01 22:08:12 +00001317 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001318 // Now rewrite the body...
1319 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001320 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1321 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001322 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1323 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001324 assert((*bodyBuf == '{') && "bogus @catch body location");
1325
1326 buf += "1) { id _tmp = _caught;";
1327 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1328 buf.c_str(), buf.size());
1329 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001330 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001331 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001332 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001333 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001334 sawIdTypedCatch = true;
1335 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001336 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001337
Ted Kremenek42730c52008-01-07 19:49:32 +00001338 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001339 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001340 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001341 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001342 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001343 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001344 }
1345 }
1346 // Now rewrite the body...
1347 lastCatchBody = catchList->getCatchBody();
1348 SourceLocation rParenLoc = catchList->getRParenLoc();
1349 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1350 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1351 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1352 assert((*rParenBuf == ')') && "bogus @catch paren location");
1353 assert((*bodyBuf == '{') && "bogus @catch body location");
1354
1355 buf = " = _caught;";
1356 // Here we replace ") {" with "= _caught;" (which initializes and
1357 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001358 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001359 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001360 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001361 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001362 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001363 catchList = catchList->getNextCatchStmt();
1364 }
1365 // Complete the catch list...
1366 if (lastCatchBody) {
1367 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001368 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1369 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001370 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1371 buf = " } } /* @catch end */\n";
1372
Chris Lattner6216f292008-01-31 19:42:41 +00001373 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001374
1375 // Set lastCurlyLoc
1376 lastCurlyLoc = lastCatchBody->getLocEnd();
1377 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001378 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001379 startLoc = finalStmt->getLocStart();
1380 startBuf = SM->getCharacterData(startLoc);
1381 assert((*startBuf == '@') && "bogus @finally start");
1382
1383 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001384 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001385
1386 Stmt *body = finalStmt->getFinallyBody();
1387 SourceLocation startLoc = body->getLocStart();
1388 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001389 assert(*SM->getCharacterData(startLoc) == '{' &&
1390 "bogus @finally body location");
1391 assert(*SM->getCharacterData(endLoc) == '}' &&
1392 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001393
1394 startLoc = startLoc.getFileLocWithOffset(1);
1395 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001396 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001397 endLoc = endLoc.getFileLocWithOffset(-1);
1398 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001399 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001400
1401 // Set lastCurlyLoc
1402 lastCurlyLoc = body->getLocEnd();
1403 }
1404 // Now emit the final closing curly brace...
1405 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1406 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001407 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001408 return 0;
1409}
1410
Steve Naroff44e81222008-04-14 22:03:09 +00001411Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001412 return 0;
1413}
1414
Steve Naroff44e81222008-04-14 22:03:09 +00001415Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001416 return 0;
1417}
1418
Chris Lattnerb1548372008-01-31 19:37:57 +00001419// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001420// the throw expression is typically a message expression that's already
1421// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001422Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001423 // Get the start location and compute the semi location.
1424 SourceLocation startLoc = S->getLocStart();
1425 const char *startBuf = SM->getCharacterData(startLoc);
1426
1427 assert((*startBuf == '@') && "bogus @throw location");
1428
1429 std::string buf;
1430 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001431 if (S->getThrowExpr())
1432 buf = "objc_exception_throw(";
1433 else // add an implicit argument
1434 buf = "objc_exception_throw(_caught";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001435 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001436 const char *semiBuf = strchr(startBuf, ';');
1437 assert((*semiBuf == ';') && "@throw: can't find ';'");
1438 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1439 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001440 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001441 return 0;
1442}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001443
Steve Naroff44e81222008-04-14 22:03:09 +00001444Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001445 // Create a new string expression.
1446 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001447 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001448 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1449 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001450 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1451 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001452 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001453 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001454
Chris Lattner4478db92007-11-30 22:53:43 +00001455 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001456 delete Exp;
1457 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001458}
1459
Steve Naroff44e81222008-04-14 22:03:09 +00001460Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff296b74f2007-11-05 14:50:49 +00001461 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1462 // Create a call to sel_registerName("selName").
1463 llvm::SmallVector<Expr*, 8> SelExprs;
1464 QualType argType = Context->getPointerType(Context->CharTy);
1465 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1466 Exp->getSelector().getName().size(),
1467 false, argType, SourceLocation(),
1468 SourceLocation()));
1469 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1470 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001471 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001472 delete Exp;
1473 return SelExp;
1474}
1475
Steve Naroff44e81222008-04-14 22:03:09 +00001476CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001477 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001478 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001479 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001480
1481 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001482 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001483
1484 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001485 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001486 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1487
1488 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001489
Steve Naroff71226032007-10-24 22:48:43 +00001490 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1491}
1492
Steve Naroffc8a92d12007-11-01 13:24:47 +00001493static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1494 const char *&startRef, const char *&endRef) {
1495 while (startBuf < endBuf) {
1496 if (*startBuf == '<')
1497 startRef = startBuf; // mark the start.
1498 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001499 if (startRef && *startRef == '<') {
1500 endRef = startBuf; // mark the end.
1501 return true;
1502 }
1503 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001504 }
1505 startBuf++;
1506 }
1507 return false;
1508}
1509
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001510static void scanToNextArgument(const char *&argRef) {
1511 int angle = 0;
1512 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1513 if (*argRef == '<')
1514 angle++;
1515 else if (*argRef == '>')
1516 angle--;
1517 argRef++;
1518 }
1519 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1520}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001521
Steve Naroff44e81222008-04-14 22:03:09 +00001522bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001523
Ted Kremenek42730c52008-01-07 19:49:32 +00001524 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001525 return true;
1526
Steve Naroffc8a92d12007-11-01 13:24:47 +00001527 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001528 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001529 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001530 return true; // we have "Class <Protocol> *".
1531 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001532 return false;
1533}
1534
Steve Naroff44e81222008-04-14 22:03:09 +00001535void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001536 SourceLocation Loc;
1537 QualType Type;
1538 const FunctionTypeProto *proto = 0;
1539 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1540 Loc = VD->getLocation();
1541 Type = VD->getType();
1542 }
1543 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1544 Loc = FD->getLocation();
1545 // Check for ObjC 'id' and class types that have been adorned with protocol
1546 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1547 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1548 assert(funcType && "missing function type");
1549 proto = dyn_cast<FunctionTypeProto>(funcType);
1550 if (!proto)
1551 return;
1552 Type = proto->getResultType();
1553 }
1554 else
1555 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001556
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001557 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001558 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001559
1560 const char *endBuf = SM->getCharacterData(Loc);
1561 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001562 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001563 startBuf--; // scan backward (from the decl location) for return type.
1564 const char *startRef = 0, *endRef = 0;
1565 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1566 // Get the locations of the startRef, endRef.
1567 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1568 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1569 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001570 InsertText(LessLoc, "/*", 2);
1571 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001572 }
1573 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001574 if (!proto)
1575 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001576 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001577 const char *startBuf = SM->getCharacterData(Loc);
1578 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001579 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1580 if (needToScanForQualifiers(proto->getArgType(i))) {
1581 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001582
Steve Naroffc8a92d12007-11-01 13:24:47 +00001583 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001584 // scan forward (from the decl location) for argument types.
1585 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001586 const char *startRef = 0, *endRef = 0;
1587 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1588 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001589 SourceLocation LessLoc =
1590 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1591 SourceLocation GreaterLoc =
1592 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001593 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001594 InsertText(LessLoc, "/*", 2);
1595 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001596 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001597 startBuf = ++endBuf;
1598 }
1599 else {
1600 while (*startBuf != ')' && *startBuf != ',')
1601 startBuf++; // scan forward (from the decl location) for argument types.
1602 startBuf++;
1603 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001604 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001605}
1606
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001607// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001608void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001609 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1610 llvm::SmallVector<QualType, 16> ArgTys;
1611 ArgTys.push_back(Context->getPointerType(
1612 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001613 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001614 &ArgTys[0], ArgTys.size(),
1615 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001616 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001617 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001618 SelGetUidIdent, getFuncType,
1619 FunctionDecl::Extern, false, 0);
1620}
1621
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001622// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001623void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001624 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1625 llvm::SmallVector<QualType, 16> ArgTys;
1626 ArgTys.push_back(Context->getPointerType(
1627 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001628 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001629 &ArgTys[0], ArgTys.size(),
1630 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001631 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001632 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001633 SelGetProtoIdent, getFuncType,
1634 FunctionDecl::Extern, false, 0);
1635}
1636
Steve Naroff44e81222008-04-14 22:03:09 +00001637void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001638 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001639 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001640 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001641 return;
1642 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001643 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001644}
1645
Steve Naroffbec4bf52008-03-11 17:37:02 +00001646// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001647void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001648 if (SuperContructorFunctionDecl)
1649 return;
1650 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1651 llvm::SmallVector<QualType, 16> ArgTys;
1652 QualType argT = Context->getObjCIdType();
1653 assert(!argT.isNull() && "Can't find 'id' type");
1654 ArgTys.push_back(argT);
1655 ArgTys.push_back(argT);
1656 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1657 &ArgTys[0], ArgTys.size(),
1658 false);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001659 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001660 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001661 msgSendIdent, msgSendType,
1662 FunctionDecl::Extern, false, 0);
1663}
1664
Steve Naroff02a82aa2007-10-30 23:14:51 +00001665// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001666void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001667 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1668 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001669 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001670 assert(!argT.isNull() && "Can't find 'id' type");
1671 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001672 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001673 assert(!argT.isNull() && "Can't find 'SEL' type");
1674 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001675 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001676 &ArgTys[0], ArgTys.size(),
1677 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001678 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001679 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001680 msgSendIdent, msgSendType,
1681 FunctionDecl::Extern, false, 0);
1682}
1683
Steve Naroff764c1ae2007-11-15 10:28:18 +00001684// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001685void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001686 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1687 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001688 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001689 SourceLocation(),
Chris Lattner58114f02008-03-15 21:32:50 +00001690 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001691 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1692 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1693 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001694 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001695 assert(!argT.isNull() && "Can't find 'SEL' type");
1696 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001697 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001698 &ArgTys[0], ArgTys.size(),
1699 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001700 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001701 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001702 msgSendIdent, msgSendType,
1703 FunctionDecl::Extern, false, 0);
1704}
1705
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001706// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001707void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001708 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1709 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001710 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001711 assert(!argT.isNull() && "Can't find 'id' type");
1712 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001713 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001714 assert(!argT.isNull() && "Can't find 'SEL' type");
1715 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001716 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001717 &ArgTys[0], ArgTys.size(),
1718 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001719 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001720 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001721 msgSendIdent, msgSendType,
1722 FunctionDecl::Extern, false, 0);
1723}
1724
1725// SynthMsgSendSuperStretFunctionDecl -
1726// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001727void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001728 IdentifierInfo *msgSendIdent =
1729 &Context->Idents.get("objc_msgSendSuper_stret");
1730 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001731 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001732 SourceLocation(),
Chris Lattner58114f02008-03-15 21:32:50 +00001733 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001734 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1735 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1736 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001737 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001738 assert(!argT.isNull() && "Can't find 'SEL' type");
1739 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001740 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001741 &ArgTys[0], ArgTys.size(),
1742 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001743 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00001744 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001745 msgSendIdent, msgSendType,
1746 FunctionDecl::Extern, false, 0);
1747}
1748
Steve Naroff31316a12008-05-08 22:02:18 +00001749// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001750void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001751 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1752 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001753 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001754 assert(!argT.isNull() && "Can't find 'id' type");
1755 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001756 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001757 assert(!argT.isNull() && "Can't find 'SEL' type");
1758 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00001759 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001760 &ArgTys[0], ArgTys.size(),
1761 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001762 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001763 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001764 msgSendIdent, msgSendType,
1765 FunctionDecl::Extern, false, 0);
1766}
1767
Steve Naroff02a82aa2007-10-30 23:14:51 +00001768// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001769void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001770 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1771 llvm::SmallVector<QualType, 16> ArgTys;
1772 ArgTys.push_back(Context->getPointerType(
1773 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001774 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001775 &ArgTys[0], ArgTys.size(),
1776 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001777 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001778 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001779 getClassIdent, getClassType,
1780 FunctionDecl::Extern, false, 0);
1781}
1782
Steve Naroff3b1caac2007-12-07 03:50:46 +00001783// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001784void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001785 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1786 llvm::SmallVector<QualType, 16> ArgTys;
1787 ArgTys.push_back(Context->getPointerType(
1788 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001789 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001790 &ArgTys[0], ArgTys.size(),
1791 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001792 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001793 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001794 getClassIdent, getClassType,
1795 FunctionDecl::Extern, false, 0);
1796}
1797
Steve Naroff44e81222008-04-14 22:03:09 +00001798Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001799 QualType strType = getConstantStringStructType();
1800
1801 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00001802
1803 std::string tmpName = InFileName;
1804 unsigned i;
1805 for (i=0; i < tmpName.length(); i++) {
1806 char c = tmpName.at(i);
1807 // replace any non alphanumeric characters with '_'.
1808 if (!isalpha(c) && (c < '0' || c > '9'))
1809 tmpName[i] = '_';
1810 }
1811 S += tmpName;
1812 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001813 S += utostr(NumObjCStringLiterals++);
1814
Steve Narofffef037c2008-03-27 22:29:16 +00001815 Preamble += "static __NSConstantStringImpl " + S;
1816 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1817 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00001818 // The pretty printer for StringLiteral handles escape characters properly.
1819 std::ostringstream prettyBuf;
1820 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00001821 Preamble += prettyBuf.str();
1822 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00001823 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00001824 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001825
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001826 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001827 &Context->Idents.get(S.c_str()), strType,
1828 VarDecl::Static, NULL);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001829 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1830 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1831 Context->getPointerType(DRE->getType()),
1832 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001833 // cast to NSConstantString *
Steve Naroff47e7fa22008-03-15 00:55:56 +00001834 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001835 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001836 delete Exp;
1837 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001838}
1839
Steve Naroff44e81222008-04-14 22:03:09 +00001840ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001841 // check if we are sending a message to 'super'
Chris Lattnere4650482008-03-15 06:12:44 +00001842 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1843
1844 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1845 if (!CE) return 0;
1846
1847 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1848 if (!DRE) return 0;
1849
1850 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1851 if (!PVD) return 0;
1852
1853 if (strcmp(PVD->getName(), "self") != 0)
1854 return 0;
1855
1856 // is this id<P1..> type?
1857 if (CE->getType()->isObjCQualifiedIdType())
1858 return 0;
1859 const PointerType *PT = CE->getType()->getAsPointerType();
1860 if (!PT) return 0;
1861
1862 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1863 if (!IT) return 0;
1864
1865 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1866 return 0;
1867
1868 return IT->getDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001869}
1870
1871// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00001872QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001873 if (!SuperStructDecl) {
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001874 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001875 SourceLocation(),
1876 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001877 QualType FieldTypes[2];
1878
1879 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001880 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001881 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001882 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001883 // Create fields
1884 FieldDecl *FieldDecls[2];
1885
1886 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001887 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001888 FieldTypes[i]);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001889
1890 SuperStructDecl->defineBody(FieldDecls, 4);
1891 }
1892 return Context->getTagDeclType(SuperStructDecl);
1893}
1894
Steve Naroff44e81222008-04-14 22:03:09 +00001895QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001896 if (!ConstantStringDecl) {
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001897 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001898 SourceLocation(),
1899 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001900 QualType FieldTypes[4];
1901
1902 // struct objc_object *receiver;
1903 FieldTypes[0] = Context->getObjCIdType();
1904 // int flags;
1905 FieldTypes[1] = Context->IntTy;
1906 // char *str;
1907 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1908 // long length;
1909 FieldTypes[3] = Context->LongTy;
1910 // Create fields
Steve Naroff053ae3f2008-03-27 22:59:54 +00001911 FieldDecl *FieldDecls[4];
Steve Naroff47e7fa22008-03-15 00:55:56 +00001912
1913 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001914 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001915 FieldTypes[i]);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001916
1917 ConstantStringDecl->defineBody(FieldDecls, 4);
1918 }
1919 return Context->getTagDeclType(ConstantStringDecl);
1920}
1921
Steve Naroff44e81222008-04-14 22:03:09 +00001922Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001923 if (!SelGetUidFunctionDecl)
1924 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001925 if (!MsgSendFunctionDecl)
1926 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001927 if (!MsgSendSuperFunctionDecl)
1928 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001929 if (!MsgSendStretFunctionDecl)
1930 SynthMsgSendStretFunctionDecl();
1931 if (!MsgSendSuperStretFunctionDecl)
1932 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001933 if (!MsgSendFpretFunctionDecl)
1934 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001935 if (!GetClassFunctionDecl)
1936 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001937 if (!GetMetaClassFunctionDecl)
1938 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001939
Steve Naroff764c1ae2007-11-15 10:28:18 +00001940 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001941 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1942 // May need to use objc_msgSend_stret() as well.
1943 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001944 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001945 QualType resultType = mDecl->getResultType();
1946 if (resultType.getCanonicalType()->isStructureType()
1947 || resultType.getCanonicalType()->isUnionType())
1948 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001949 else if (resultType.getCanonicalType()->isRealFloatingType())
1950 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001951 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001952
Steve Naroff71226032007-10-24 22:48:43 +00001953 // Synthesize a call to objc_msgSend().
1954 llvm::SmallVector<Expr*, 8> MsgExprs;
1955 IdentifierInfo *clsName = Exp->getClassName();
1956
1957 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1958 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001959 if (!strcmp(clsName->getName(), "super")) {
1960 MsgSendFlavor = MsgSendSuperFunctionDecl;
1961 if (MsgSendStretFlavor)
1962 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1963 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1964
Ted Kremenek42730c52008-01-07 19:49:32 +00001965 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001966 CurMethodDecl->getClassInterface()->getSuperClass();
1967
1968 llvm::SmallVector<Expr*, 4> InitExprs;
1969
1970 // set the receiver to self, the first argument to all methods.
1971 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001972 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001973 SourceLocation()));
1974 llvm::SmallVector<Expr*, 8> ClsExprs;
1975 QualType argType = Context->getPointerType(Context->CharTy);
1976 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1977 SuperDecl->getIdentifier()->getLength(),
1978 false, argType, SourceLocation(),
1979 SourceLocation()));
1980 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1981 &ClsExprs[0],
1982 ClsExprs.size());
1983 // To turn off a warning, type-cast to 'id'
1984 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001985 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001986 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1987 // struct objc_super
1988 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00001989 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00001990
Steve Naroffdee066b2008-03-11 18:14:26 +00001991 if (LangOpts.Microsoft) {
1992 SynthSuperContructorFunctionDecl();
1993 // Simulate a contructor call...
1994 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1995 superType, SourceLocation());
1996 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1997 superType, SourceLocation());
1998 } else {
1999 // (struct objc_super) { <exprs from above> }
2000 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2001 &InitExprs[0], InitExprs.size(),
2002 SourceLocation());
2003 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2004 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00002005 // struct objc_super *
2006 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2007 Context->getPointerType(SuperRep->getType()),
2008 SourceLocation());
2009 MsgExprs.push_back(Unop);
2010 } else {
2011 llvm::SmallVector<Expr*, 8> ClsExprs;
2012 QualType argType = Context->getPointerType(Context->CharTy);
2013 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2014 clsName->getLength(),
2015 false, argType, SourceLocation(),
2016 SourceLocation()));
2017 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2018 &ClsExprs[0],
2019 ClsExprs.size());
2020 MsgExprs.push_back(Cls);
2021 }
Steve Naroff885e2122007-11-14 23:54:14 +00002022 } else { // instance message.
2023 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002024
Ted Kremenek42730c52008-01-07 19:49:32 +00002025 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002026 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002027 if (MsgSendStretFlavor)
2028 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002029 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2030
2031 llvm::SmallVector<Expr*, 4> InitExprs;
2032
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002033 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00002034 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002035 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002036
2037 llvm::SmallVector<Expr*, 8> ClsExprs;
2038 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002039 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2040 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002041 false, argType, SourceLocation(),
2042 SourceLocation()));
2043 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002044 &ClsExprs[0],
2045 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002046 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002047 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00002048 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002049 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00002050 // struct objc_super
2051 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002052 Expr *SuperRep;
2053
2054 if (LangOpts.Microsoft) {
2055 SynthSuperContructorFunctionDecl();
2056 // Simulate a contructor call...
2057 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2058 superType, SourceLocation());
2059 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2060 superType, SourceLocation());
2061 } else {
2062 // (struct objc_super) { <exprs from above> }
2063 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2064 &InitExprs[0], InitExprs.size(),
2065 SourceLocation());
2066 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2067 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002068 // struct objc_super *
2069 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2070 Context->getPointerType(SuperRep->getType()),
2071 SourceLocation());
2072 MsgExprs.push_back(Unop);
2073 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002074 // Remove all type-casts because it may contain objc-style types; e.g.
2075 // Foo<Proto> *.
2076 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2077 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002078 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002079 MsgExprs.push_back(recExpr);
2080 }
Steve Naroff885e2122007-11-14 23:54:14 +00002081 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002082 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002083 llvm::SmallVector<Expr*, 8> SelExprs;
2084 QualType argType = Context->getPointerType(Context->CharTy);
2085 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2086 Exp->getSelector().getName().size(),
2087 false, argType, SourceLocation(),
2088 SourceLocation()));
2089 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2090 &SelExprs[0], SelExprs.size());
2091 MsgExprs.push_back(SelExp);
2092
2093 // Now push any user supplied arguments.
2094 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002095 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002096 // Make all implicit casts explicit...ICE comes in handy:-)
2097 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2098 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00002099 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2100 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002101 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002102 }
2103 // Make id<P...> cast into an 'id' cast.
2104 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002105 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002106 while ((CE = dyn_cast<CastExpr>(userExpr)))
2107 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002108 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002109 userExpr, SourceLocation());
2110 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002111 }
Steve Naroff885e2122007-11-14 23:54:14 +00002112 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002113 // We've transferred the ownership to MsgExprs. Null out the argument in
2114 // the original expression, since we will delete it below.
2115 Exp->setArg(i, 0);
2116 }
Steve Naroff0744c472007-11-04 22:37:50 +00002117 // Generate the funky cast.
2118 CastExpr *cast;
2119 llvm::SmallVector<QualType, 8> ArgTypes;
2120 QualType returnType;
2121
2122 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002123 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2124 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2125 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002126 ArgTypes.push_back(Context->getObjCIdType());
2127 ArgTypes.push_back(Context->getObjCSelType());
2128 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002129 // Push any user argument types.
Chris Lattner685d7922008-03-16 01:07:14 +00002130 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002131 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2132 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002133 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00002134 ArgTypes.push_back(t);
2135 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002136 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2137 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002138 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002139 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002140 }
2141 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002142 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002143
2144 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002145 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2146 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002147
2148 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2149 // If we don't do this cast, we get the following bizarre warning/note:
2150 // xx.m:13: warning: function called through a non-compatible type
2151 // xx.m:13: note: if this code is reached, the program will abort
2152 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2153 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002154
Steve Naroff0744c472007-11-04 22:37:50 +00002155 // Now do the "normal" pointer to function cast.
2156 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002157 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002158 // If we don't have a method decl, force a variadic cast.
2159 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroff0744c472007-11-04 22:37:50 +00002160 castType = Context->getPointerType(castType);
2161 cast = new CastExpr(castType, cast, SourceLocation());
2162
2163 // Don't forget the parens to enforce the proper binding.
2164 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2165
2166 const FunctionType *FT = msgSendType->getAsFunctionType();
2167 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2168 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002169 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002170 if (MsgSendStretFlavor) {
2171 // We have the method which returns a struct/union. Must also generate
2172 // call to objc_msgSend_stret and hang both varieties on a conditional
2173 // expression which dictate which one to envoke depending on size of
2174 // method's return type.
2175
2176 // Create a reference to the objc_msgSend_stret() declaration.
2177 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2178 SourceLocation());
2179 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2180 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2181 SourceLocation());
2182 // Now do the "normal" pointer to function cast.
2183 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002184 &ArgTypes[0], ArgTypes.size(),
2185 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002186 castType = Context->getPointerType(castType);
2187 cast = new CastExpr(castType, cast, SourceLocation());
2188
2189 // Don't forget the parens to enforce the proper binding.
2190 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2191
2192 FT = msgSendType->getAsFunctionType();
2193 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2194 FT->getResultType(), SourceLocation());
2195
2196 // Build sizeof(returnType)
2197 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2198 returnType, Context->getSizeType(),
2199 SourceLocation(), SourceLocation());
2200 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2201 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2202 // For X86 it is more complicated and some kind of target specific routine
2203 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002204 unsigned IntSize =
2205 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002206 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2207 Context->IntTy,
2208 SourceLocation());
2209 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2210 BinaryOperator::LE,
2211 Context->IntTy,
2212 SourceLocation());
2213 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2214 ConditionalOperator *CondExpr =
2215 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002216 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002217 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002218 return ReplacingStmt;
2219}
2220
Steve Naroff44e81222008-04-14 22:03:09 +00002221Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002222 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002223 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002224 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002225
Chris Lattner0021f452007-10-24 16:57:36 +00002226 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002227 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002228}
2229
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002230/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2231/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002232Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002233 if (!GetProtocolFunctionDecl)
2234 SynthGetProtocolFunctionDecl();
2235 // Create a call to objc_getProtocol("ProtocolName").
2236 llvm::SmallVector<Expr*, 8> ProtoExprs;
2237 QualType argType = Context->getPointerType(Context->CharTy);
2238 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2239 strlen(Exp->getProtocol()->getName()),
2240 false, argType, SourceLocation(),
2241 SourceLocation()));
2242 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2243 &ProtoExprs[0],
2244 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002245 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002246 delete Exp;
2247 return ProtoExp;
2248
2249}
2250
Steve Naroffef82b742008-05-31 14:15:04 +00002251bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2252 const char *endBuf) {
2253 while (startBuf < endBuf) {
2254 if (*startBuf == '#') {
2255 // Skip whitespace.
2256 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2257 ;
2258 if (!strncmp(startBuf, "if", strlen("if")) ||
2259 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2260 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2261 !strncmp(startBuf, "define", strlen("define")) ||
2262 !strncmp(startBuf, "undef", strlen("undef")) ||
2263 !strncmp(startBuf, "else", strlen("else")) ||
2264 !strncmp(startBuf, "elif", strlen("elif")) ||
2265 !strncmp(startBuf, "endif", strlen("endif")) ||
2266 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2267 !strncmp(startBuf, "include", strlen("include")) ||
2268 !strncmp(startBuf, "import", strlen("import")) ||
2269 !strncmp(startBuf, "include_next", strlen("include_next")))
2270 return true;
2271 }
2272 startBuf++;
2273 }
2274 return false;
2275}
2276
Ted Kremenek42730c52008-01-07 19:49:32 +00002277/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002278/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002279void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002280 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002281 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2282 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002283 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002284 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002285 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002286 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002287 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002288 SourceLocation LocStart = CDecl->getLocStart();
2289 SourceLocation LocEnd = CDecl->getLocEnd();
2290
2291 const char *startBuf = SM->getCharacterData(LocStart);
2292 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002293
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002294 // If no ivars and no root or if its root, directly or indirectly,
2295 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002296 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2297 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002298 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002299 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002300 return;
2301 }
2302
2303 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002304 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002305 Result += "\nstruct ";
2306 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002307 if (LangOpts.Microsoft)
2308 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002309
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002310 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002311 const char *cursor = strchr(startBuf, '{');
2312 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002313 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002314 // If the buffer contains preprocessor directives, we do more fine-grained
2315 // rewrites. This is intended to fix code that looks like (which occurs in
2316 // NSURL.h, for example):
2317 //
2318 // #ifdef XYZ
2319 // @interface Foo : NSObject
2320 // #else
2321 // @interface FooBar : NSObject
2322 // #endif
2323 // {
2324 // int i;
2325 // }
2326 // @end
2327 //
2328 // This clause is segregated to avoid breaking the common case.
2329 if (BufferContainsPPDirectives(startBuf, cursor)) {
2330 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2331 CDecl->getClassLoc();
2332 const char *endHeader = SM->getCharacterData(L);
2333 endHeader += Lexer::MeasureTokenLength(L, *SM);
2334
2335 if (CDecl->getNumIntfRefProtocols()) {
2336 // advance to the end of the referenced protocols.
2337 while (endHeader < cursor && *endHeader != '>') endHeader++;
2338 endHeader++;
2339 }
2340 // rewrite the original header
2341 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2342 } else {
2343 // rewrite the original header *without* disturbing the '{'
2344 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2345 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002346 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002347 Result = "\n struct ";
2348 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002349 Result += "_IMPL ";
2350 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002351 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002352
2353 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002354 SourceLocation OnePastCurly =
2355 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2356 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002357 }
2358 cursor++; // past '{'
2359
2360 // Now comment out any visibility specifiers.
2361 while (cursor < endBuf) {
2362 if (*cursor == '@') {
2363 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002364 // Skip whitespace.
2365 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2366 /*scan*/;
2367
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002368 // FIXME: presence of @public, etc. inside comment results in
2369 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002370 if (!strncmp(cursor, "public", strlen("public")) ||
2371 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002372 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002373 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002374 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002375 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002376 // FIXME: If there are cases where '<' is used in ivar declaration part
2377 // of user code, then scan the ivar list and use needToScanForQualifiers
2378 // for type checking.
2379 else if (*cursor == '<') {
2380 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002381 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002382 cursor = strchr(cursor, '>');
2383 cursor++;
2384 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002385 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002386 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002387 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002388 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002389 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002390 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002391 } else { // we don't have any instance variables - insert super struct.
2392 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2393 Result += " {\n struct ";
2394 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002395 Result += "_IMPL ";
2396 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002397 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002398 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002399 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002400 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002401 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002402 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002403}
2404
Ted Kremenek42730c52008-01-07 19:49:32 +00002405// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002406/// class methods.
Steve Naroff44e81222008-04-14 22:03:09 +00002407void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002408 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002409 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002410 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002411 const char *ClassName,
2412 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002413 if (MethodBegin == MethodEnd) return;
2414
Fariborz Jahanian04455192007-10-22 21:41:37 +00002415 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002416 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002417 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002418 SEL _cmd;
2419 char *method_types;
2420 void *_imp;
2421 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002422 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002423 Result += "\nstruct _objc_method {\n";
2424 Result += "\tSEL _cmd;\n";
2425 Result += "\tchar *method_types;\n";
2426 Result += "\tvoid *_imp;\n";
2427 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002428
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002429 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002430 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002431
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002432 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002433
2434 /* struct {
2435 struct _objc_method_list *next_method;
2436 int method_count;
2437 struct _objc_method method_list[];
2438 }
2439 */
2440 Result += "\nstatic struct {\n";
2441 Result += "\tstruct _objc_method_list *next_method;\n";
2442 Result += "\tint method_count;\n";
2443 Result += "\tstruct _objc_method method_list[";
2444 Result += utostr(MethodEnd-MethodBegin);
2445 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002446 Result += prefix;
2447 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2448 Result += "_METHODS_";
2449 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002450 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002451 Result += IsInstanceMethod ? "inst" : "cls";
2452 Result += "_meth\")))= ";
2453 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002454
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002455 Result += "\t,{{(SEL)\"";
2456 Result += (*MethodBegin)->getSelector().getName().c_str();
2457 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002458 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002459 Result += "\", \"";
2460 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002461 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002462 Result += MethodInternalNames[*MethodBegin];
2463 Result += "}\n";
2464 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2465 Result += "\t ,{(SEL)\"";
2466 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002467 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002468 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002469 Result += "\", \"";
2470 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002471 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002472 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002473 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002474 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002475 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002476}
2477
Ted Kremenek42730c52008-01-07 19:49:32 +00002478/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Steve Naroff44e81222008-04-14 22:03:09 +00002479void RewriteObjC::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002480 int NumProtocols,
2481 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002482 const char *ClassName,
2483 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002484 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002485 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002486 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002487 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002488 // Output struct protocol_methods holder of method selector and type.
Chris Lattner7afba9c2008-03-16 20:19:15 +00002489 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002490 /* struct protocol_methods {
2491 SEL _cmd;
2492 char *method_types;
2493 }
2494 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002495 Result += "\nstruct protocol_methods {\n";
2496 Result += "\tSEL _cmd;\n";
2497 Result += "\tchar *method_types;\n";
2498 Result += "};\n";
2499
Steve Naroff27429432008-03-12 01:06:30 +00002500 objc_protocol_methods = true;
2501 }
Steve Naroff04eaa192008-05-06 18:26:51 +00002502 // Do not synthesize the protocol more than once.
2503 if (ObjCSynthesizedProtocols.count(PDecl))
2504 continue;
2505
Chris Lattner7afba9c2008-03-16 20:19:15 +00002506 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2507 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002508 /* struct _objc_protocol_method_list {
2509 int protocol_method_count;
2510 struct protocol_methods protocols[];
2511 }
2512 */
Steve Naroff27429432008-03-12 01:06:30 +00002513 Result += "\nstatic struct {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002514 Result += "\tint protocol_method_count;\n";
Steve Naroff27429432008-03-12 01:06:30 +00002515 Result += "\tstruct protocol_methods protocols[";
2516 Result += utostr(NumMethods);
2517 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002518 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002519 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002520 "{\n\t" + utostr(NumMethods) + "\n";
2521
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002522 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002523 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002524 E = PDecl->instmeth_end(); I != E; ++I) {
2525 if (I == PDecl->instmeth_begin())
2526 Result += "\t ,{{(SEL)\"";
2527 else
2528 Result += "\t ,{(SEL)\"";
2529 Result += (*I)->getSelector().getName().c_str();
2530 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002531 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002532 Result += "\", \"";
2533 Result += MethodTypeString;
2534 Result += "\"}\n";
2535 }
2536 Result += "\t }\n};\n";
2537 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002538
2539 // Output class methods declared in this protocol.
Chris Lattner7afba9c2008-03-16 20:19:15 +00002540 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahanian04455192007-10-22 21:41:37 +00002541 if (NumMethods > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002542 /* struct _objc_protocol_method_list {
2543 int protocol_method_count;
2544 struct protocol_methods protocols[];
2545 }
2546 */
2547 Result += "\nstatic struct {\n";
2548 Result += "\tint protocol_method_count;\n";
2549 Result += "\tstruct protocol_methods protocols[";
2550 Result += utostr(NumMethods);
2551 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002552 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002553 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002554 "{\n\t";
2555 Result += utostr(NumMethods);
2556 Result += "\n";
2557
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002558 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002559 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002560 E = PDecl->classmeth_end(); I != E; ++I) {
2561 if (I == PDecl->classmeth_begin())
2562 Result += "\t ,{{(SEL)\"";
2563 else
2564 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002565 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002566 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002567 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002568 Result += "\", \"";
2569 Result += MethodTypeString;
2570 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002571 }
2572 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002573 }
Steve Naroff04eaa192008-05-06 18:26:51 +00002574
Fariborz Jahanian04455192007-10-22 21:41:37 +00002575 // Output:
2576 /* struct _objc_protocol {
2577 // Objective-C 1.0 extensions
2578 struct _objc_protocol_extension *isa;
2579 char *protocol_name;
2580 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002581 struct _objc_protocol_method_list *instance_methods;
2582 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002583 };
2584 */
2585 static bool objc_protocol = false;
2586 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002587 Result += "\nstruct _objc_protocol {\n";
2588 Result += "\tstruct _objc_protocol_extension *isa;\n";
2589 Result += "\tchar *protocol_name;\n";
2590 Result += "\tstruct _objc_protocol **protocol_list;\n";
2591 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2592 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2593 Result += "};\n";
2594
Fariborz Jahanian04455192007-10-22 21:41:37 +00002595 objc_protocol = true;
2596 }
2597
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002598 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2599 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002600 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002601 "{\n\t0, \"";
2602 Result += PDecl->getName();
2603 Result += "\", 0, ";
Chris Lattner7afba9c2008-03-16 20:19:15 +00002604 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00002605 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002606 Result += PDecl->getName();
2607 Result += ", ";
2608 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002609 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002610 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002611 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002612 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002613 Result += PDecl->getName();
2614 Result += "\n";
2615 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002616 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002617 Result += "0\n";
2618 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002619
2620 // Mark this protocol as having been generated.
2621 if (!ObjCSynthesizedProtocols.insert(PDecl))
2622 assert(false && "protocol already synthesized");
Fariborz Jahanian04455192007-10-22 21:41:37 +00002623 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002624 // Output the top lovel protocol meta-data for the class.
Steve Naroff27429432008-03-12 01:06:30 +00002625 /* struct _objc_protocol_list {
2626 struct _objc_protocol_list *next;
2627 int protocol_count;
2628 struct _objc_protocol *class_protocols[];
2629 }
2630 */
2631 Result += "\nstatic struct {\n";
2632 Result += "\tstruct _objc_protocol_list *next;\n";
2633 Result += "\tint protocol_count;\n";
2634 Result += "\tstruct _objc_protocol *class_protocols[";
2635 Result += utostr(NumProtocols);
2636 Result += "];\n} _OBJC_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002637 Result += prefix;
2638 Result += "_PROTOCOLS_";
2639 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002640 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002641 "{\n\t0, ";
2642 Result += utostr(NumProtocols);
2643 Result += "\n";
2644
2645 Result += "\t,{&_OBJC_PROTOCOL_";
2646 Result += Protocols[0]->getName();
2647 Result += " \n";
2648
2649 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002650 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroffb6ed80a2008-04-18 22:15:15 +00002651 Result += "\t ,&_OBJC_PROTOCOL_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002652 Result += PDecl->getName();
2653 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002654 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002655 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002656 }
2657}
2658
Ted Kremenek42730c52008-01-07 19:49:32 +00002659/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002660/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00002661void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002662 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002663 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002664 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002665 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002666 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2667 CDecl = CDecl->getNextClassCategory())
2668 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2669 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002670
Chris Lattnera661a4d2007-12-23 01:40:15 +00002671 std::string FullCategoryName = ClassDecl->getName();
2672 FullCategoryName += '_';
2673 FullCategoryName += IDecl->getName();
2674
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002675 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002676 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002677 true, "CATEGORY_", FullCategoryName.c_str(),
2678 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002679
2680 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002681 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002682 false, "CATEGORY_", FullCategoryName.c_str(),
2683 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002684
2685 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002686 // Null CDecl is case of a category implementation with no category interface
2687 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002688 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002689 CDecl->getNumReferencedProtocols(),
2690 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002691 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002692
2693 /* struct _objc_category {
2694 char *category_name;
2695 char *class_name;
2696 struct _objc_method_list *instance_methods;
2697 struct _objc_method_list *class_methods;
2698 struct _objc_protocol_list *protocols;
2699 // Objective-C 1.0 extensions
2700 uint32_t size; // sizeof (struct _objc_category)
2701 struct _objc_property_list *instance_properties; // category's own
2702 // @property decl.
2703 };
2704 */
2705
2706 static bool objc_category = false;
2707 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002708 Result += "\nstruct _objc_category {\n";
2709 Result += "\tchar *category_name;\n";
2710 Result += "\tchar *class_name;\n";
2711 Result += "\tstruct _objc_method_list *instance_methods;\n";
2712 Result += "\tstruct _objc_method_list *class_methods;\n";
2713 Result += "\tstruct _objc_protocol_list *protocols;\n";
2714 Result += "\tunsigned int size;\n";
2715 Result += "\tstruct _objc_property_list *instance_properties;\n";
2716 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002717 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002718 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002719 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2720 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002721 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002722 Result += IDecl->getName();
2723 Result += "\"\n\t, \"";
2724 Result += ClassDecl->getName();
2725 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002726
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002727 if (IDecl->getNumInstanceMethods() > 0) {
2728 Result += "\t, (struct _objc_method_list *)"
2729 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2730 Result += FullCategoryName;
2731 Result += "\n";
2732 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002733 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002734 Result += "\t, 0\n";
2735 if (IDecl->getNumClassMethods() > 0) {
2736 Result += "\t, (struct _objc_method_list *)"
2737 "&_OBJC_CATEGORY_CLASS_METHODS_";
2738 Result += FullCategoryName;
2739 Result += "\n";
2740 }
2741 else
2742 Result += "\t, 0\n";
2743
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002744 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002745 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2746 Result += FullCategoryName;
2747 Result += "\n";
2748 }
2749 else
2750 Result += "\t, 0\n";
2751 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002752}
2753
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002754/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2755/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00002756void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00002757 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002758 std::string &Result) {
Steve Naroff5bf10222008-05-07 21:23:49 +00002759 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002760 Result += IDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002761 if (LangOpts.Microsoft)
2762 Result += "_IMPL";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002763 Result += ", ";
2764 Result += ivar->getName();
2765 Result += ")";
2766}
2767
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002768//===----------------------------------------------------------------------===//
2769// Meta Data Emission
2770//===----------------------------------------------------------------------===//
2771
Steve Naroff44e81222008-04-14 22:03:09 +00002772void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002773 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002774 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002775
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002776 // Explictly declared @interface's are already synthesized.
2777 if (CDecl->ImplicitInterfaceDecl()) {
2778 // FIXME: Implementation of a class with no @interface (legacy) doese not
2779 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002780 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002781 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002782
Chris Lattnerc7b06752007-12-12 07:56:42 +00002783 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00002784 unsigned NumIvars = !IDecl->ivar_empty()
2785 ? IDecl->ivar_size()
2786 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002787 if (NumIvars > 0) {
2788 static bool objc_ivar = false;
2789 if (!objc_ivar) {
2790 /* struct _objc_ivar {
2791 char *ivar_name;
2792 char *ivar_type;
2793 int ivar_offset;
2794 };
2795 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002796 Result += "\nstruct _objc_ivar {\n";
2797 Result += "\tchar *ivar_name;\n";
2798 Result += "\tchar *ivar_type;\n";
2799 Result += "\tint ivar_offset;\n";
2800 Result += "};\n";
2801
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002802 objc_ivar = true;
2803 }
2804
Steve Naroffc723eec2008-03-11 00:12:29 +00002805 /* struct {
2806 int ivar_count;
2807 struct _objc_ivar ivar_list[nIvars];
2808 };
2809 */
2810 Result += "\nstatic struct {\n";
2811 Result += "\tint ivar_count;\n";
2812 Result += "\tstruct _objc_ivar ivar_list[";
2813 Result += utostr(NumIvars);
2814 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002815 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002816 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002817 "{\n\t";
2818 Result += utostr(NumIvars);
2819 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002820
Ted Kremenek42730c52008-01-07 19:49:32 +00002821 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00002822 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00002823 IVI = IDecl->ivar_begin();
2824 IVE = IDecl->ivar_end();
2825 } else {
2826 IVI = CDecl->ivar_begin();
2827 IVE = CDecl->ivar_end();
2828 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002829 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002830 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002831 Result += "\", \"";
2832 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002833 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2834 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002835 Result += StrEncoding;
2836 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002837 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002838 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002839 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002840 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002841 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002842 Result += "\", \"";
2843 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002844 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2845 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002846 Result += StrEncoding;
2847 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002848 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002849 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002850 }
2851
2852 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002853 }
2854
2855 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002856 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002857 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002858
2859 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002860 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002861 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002862
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002863 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002864 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002865 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002866 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002867
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002868
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002869 // Declaration of class/meta-class metadata
2870 /* struct _objc_class {
2871 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002872 const char *super_class_name;
2873 char *name;
2874 long version;
2875 long info;
2876 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002877 struct _objc_ivar_list *ivars;
2878 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002879 struct objc_cache *cache;
2880 struct objc_protocol_list *protocols;
2881 const char *ivar_layout;
2882 struct _objc_class_ext *ext;
2883 };
2884 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002885 static bool objc_class = false;
2886 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002887 Result += "\nstruct _objc_class {\n";
2888 Result += "\tstruct _objc_class *isa;\n";
2889 Result += "\tconst char *super_class_name;\n";
2890 Result += "\tchar *name;\n";
2891 Result += "\tlong version;\n";
2892 Result += "\tlong info;\n";
2893 Result += "\tlong instance_size;\n";
2894 Result += "\tstruct _objc_ivar_list *ivars;\n";
2895 Result += "\tstruct _objc_method_list *methods;\n";
2896 Result += "\tstruct objc_cache *cache;\n";
2897 Result += "\tstruct _objc_protocol_list *protocols;\n";
2898 Result += "\tconst char *ivar_layout;\n";
2899 Result += "\tstruct _objc_class_ext *ext;\n";
2900 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002901 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002902 }
2903
2904 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002905 ObjCInterfaceDecl *RootClass = 0;
2906 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002907 while (SuperClass) {
2908 RootClass = SuperClass;
2909 SuperClass = SuperClass->getSuperClass();
2910 }
2911 SuperClass = CDecl->getSuperClass();
2912
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002913 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2914 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002915 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002916 "{\n\t(struct _objc_class *)\"";
2917 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2918 Result += "\"";
2919
2920 if (SuperClass) {
2921 Result += ", \"";
2922 Result += SuperClass->getName();
2923 Result += "\", \"";
2924 Result += CDecl->getName();
2925 Result += "\"";
2926 }
2927 else {
2928 Result += ", 0, \"";
2929 Result += CDecl->getName();
2930 Result += "\"";
2931 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002932 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002933 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002934 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002935 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00002936 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002937 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002938 Result += "\n";
2939 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002940 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002941 Result += ", 0\n";
2942 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002943 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002944 Result += CDecl->getName();
2945 Result += ",0,0\n";
2946 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002947 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002948 Result += "\t,0,0,0,0\n";
2949 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002950
2951 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002952 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2953 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002954 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002955 "{\n\t&_OBJC_METACLASS_";
2956 Result += CDecl->getName();
2957 if (SuperClass) {
2958 Result += ", \"";
2959 Result += SuperClass->getName();
2960 Result += "\", \"";
2961 Result += CDecl->getName();
2962 Result += "\"";
2963 }
2964 else {
2965 Result += ", 0, \"";
2966 Result += CDecl->getName();
2967 Result += "\"";
2968 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002969 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002970 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002971 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002972 Result += ",0";
2973 else {
2974 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002975 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002976 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00002977 if (LangOpts.Microsoft)
2978 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002979 Result += ")";
2980 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002981 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00002982 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002983 Result += CDecl->getName();
2984 Result += "\n\t";
2985 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002986 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002987 Result += ",0";
2988 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00002989 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002990 Result += CDecl->getName();
2991 Result += ", 0\n\t";
2992 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002993 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002994 Result += ",0,0";
2995 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002996 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002997 Result += CDecl->getName();
2998 Result += ", 0,0\n";
2999 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003000 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003001 Result += ",0,0,0\n";
3002 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003003}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003004
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003005/// RewriteImplementations - This routine rewrites all method implementations
3006/// and emits meta-data.
3007
Steve Naroff44e81222008-04-14 22:03:09 +00003008void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003009 int ClsDefCount = ClassImplementation.size();
3010 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003011
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003012 if (ClsDefCount == 0 && CatDefCount == 0)
3013 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003014 // Rewrite implemented methods
3015 for (int i = 0; i < ClsDefCount; i++)
3016 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003017
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003018 for (int i = 0; i < CatDefCount; i++)
3019 RewriteImplementationDecl(CategoryImplementation[i]);
3020
Steve Naroff5bf10222008-05-07 21:23:49 +00003021 // This is needed for determining instance variable offsets.
3022 Result += "#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003023 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003024 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003025 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003026
3027 // For each implemented category, write out all its meta data.
3028 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003029 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003030
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003031 // Write objc_symtab metadata
3032 /*
3033 struct _objc_symtab
3034 {
3035 long sel_ref_cnt;
3036 SEL *refs;
3037 short cls_def_cnt;
3038 short cat_def_cnt;
3039 void *defs[cls_def_cnt + cat_def_cnt];
3040 };
3041 */
3042
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003043 Result += "\nstruct _objc_symtab {\n";
3044 Result += "\tlong sel_ref_cnt;\n";
3045 Result += "\tSEL *refs;\n";
3046 Result += "\tshort cls_def_cnt;\n";
3047 Result += "\tshort cat_def_cnt;\n";
3048 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3049 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003050
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003051 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003052 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003053 Result += "\t0, 0, " + utostr(ClsDefCount)
3054 + ", " + utostr(CatDefCount) + "\n";
3055 for (int i = 0; i < ClsDefCount; i++) {
3056 Result += "\t,&_OBJC_CLASS_";
3057 Result += ClassImplementation[i]->getName();
3058 Result += "\n";
3059 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003060
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003061 for (int i = 0; i < CatDefCount; i++) {
3062 Result += "\t,&_OBJC_CATEGORY_";
3063 Result += CategoryImplementation[i]->getClassInterface()->getName();
3064 Result += "_";
3065 Result += CategoryImplementation[i]->getName();
3066 Result += "\n";
3067 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003068
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003069 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003070
3071 // Write objc_module metadata
3072
3073 /*
3074 struct _objc_module {
3075 long version;
3076 long size;
3077 const char *name;
3078 struct _objc_symtab *symtab;
3079 }
3080 */
3081
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003082 Result += "\nstruct _objc_module {\n";
3083 Result += "\tlong version;\n";
3084 Result += "\tlong size;\n";
3085 Result += "\tconst char *name;\n";
3086 Result += "\tstruct _objc_symtab *symtab;\n";
3087 Result += "};\n\n";
3088 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003089 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003090 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3091 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003092 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003093
3094 if (LangOpts.Microsoft) {
3095 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003096 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003097 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3098 Result += "&_OBJC_MODULES;\n";
3099 Result += "#pragma data_seg(pop)\n\n";
3100 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003101}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003102
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003103