blob: bd809beae8f05d2ba5fe90bde1b0d741d59f0e6a [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"
Ted Kremenek79b50cb2008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner569faa62007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000025#include "llvm/Support/MemoryBuffer.h"
Steve Naroff1c46cf12008-01-28 21:34:52 +000026#include "llvm/Support/CommandLine.h"
Dan Gohman6da15102008-05-21 20:19:16 +000027#include "llvm/Support/Streams.h"
Chris Lattner673f2bd2008-03-22 00:08:40 +000028#include "llvm/System/Path.h"
Steve Naroff3c7b9a02008-04-14 22:53:48 +000029#include <sstream>
Chris Lattner673f2bd2008-03-22 00:08:40 +000030#include <fstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000031using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000033
Steve Naroff1c46cf12008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattnerb429ae42007-10-11 00:43:27 +000038namespace {
Steve Naroff44e81222008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000046 SourceManager *SM;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner569faa62007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Narofffef037c2008-03-27 22:29:16 +000051
Ted Kremenek42730c52008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff04eaa192008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek42730c52008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian248db262008-01-22 22:44:46 +000060 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffe9780582007-10-23 23:50:29 +000061
Steve Naroff47e7fa22008-03-15 00:55:56 +000062 unsigned NumObjCStringLiterals;
63
Steve Naroffe9780582007-10-23 23:50:29 +000064 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000065 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000066 FunctionDecl *MsgSendStretFunctionDecl;
67 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000068 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000069 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000070 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000071 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000072 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000073 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000074 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000075
Steve Naroff0add5d22007-11-03 11:27:19 +000076 // ObjC string constant support.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000077 VarDecl *ConstantStringClassReference;
Steve Naroff0add5d22007-11-03 11:27:19 +000078 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000079
Fariborz Jahanian22277422008-01-16 00:09:11 +000080 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000081 int BcLabelCount;
82
Steve Naroff764c1ae2007-11-15 10:28:18 +000083 // Needed for super.
Ted Kremenek42730c52008-01-07 19:49:32 +000084 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000085 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000086 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000087
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000088 // Needed for header files being rewritten
89 bool IsHeader;
90
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000091 std::string InFileName;
92 std::string OutFileName;
93
Steve Narofffef037c2008-03-27 22:29:16 +000094 std::string Preamble;
95
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000096 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000097 public:
Ted Kremenek79b50cb2008-05-31 20:11:04 +000098 virtual void Initialize(ASTContext &context);
99
100 virtual void InitializeTU(TranslationUnit &TU) {
101 TU.SetOwnsDecls(false);
102 Initialize(TU.getContext());
103 }
Chris Lattner12499682008-01-31 19:38:44 +0000104
Chris Lattner569faa62007-10-11 18:38:32 +0000105
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000106 // Top Level Driver code.
107 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000108 void HandleDeclInMainFile(Decl *D);
Steve Naroff44e81222008-04-14 22:03:09 +0000109 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000110 Diagnostic &D, const LangOptions &LOpts);
Ted Kremenekcab0b0c2008-08-08 04:15:52 +0000111
112 ~RewriteObjC() {}
113
114 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerb1548372008-01-31 19:37:57 +0000115
116 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattner6216f292008-01-31 19:42:41 +0000117 // If replacement succeeded or warning disabled return with no warning.
118 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerb1548372008-01-31 19:37:57 +0000119 return;
120
Chris Lattnerb1548372008-01-31 19:37:57 +0000121 SourceRange Range = Old->getSourceRange();
122 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
123 0, 0, &Range, 1);
124 }
125
Steve Narofffef037c2008-03-27 22:29:16 +0000126 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
127 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000128 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000129 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000130 SilenceRewriteMacroWarning)
131 return;
132
133 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
134 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000135
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000136 void RemoveText(SourceLocation Loc, unsigned StrLen) {
137 // If removal succeeded or warning disabled return with no warning.
138 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
139 return;
140
141 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
142 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000143
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000144 void ReplaceText(SourceLocation Start, unsigned OrigLength,
145 const char *NewStr, unsigned NewLength) {
146 // If removal succeeded or warning disabled return with no warning.
147 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
148 SilenceRewriteMacroWarning)
149 return;
150
151 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
152 }
153
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000154 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000155 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000156 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000157 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000158 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
159 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000160 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000161 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
162 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
163 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
164 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
165 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattnercffe3662008-03-16 21:23:50 +0000166 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000167 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000168 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000169 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000170 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000171 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000172 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000173 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000174 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000175
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000176 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000177 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000178 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000179 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff296b74f2007-11-05 14:50:49 +0000180 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000181 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000182 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000183 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000184 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000185 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000186 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
187 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
188 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000189 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
190 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000191 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
192 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000193 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000194 Stmt *RewriteBreakStmt(BreakStmt *S);
195 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000196 void SynthCountByEnumWithState(std::string &buf);
197
Steve Naroff02a82aa2007-10-30 23:14:51 +0000198 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000199 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000200 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000201 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000202 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000203 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000204 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000205 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000206 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000207 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000208
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000209 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000210 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000211 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000212
Ted Kremenek42730c52008-01-07 19:49:32 +0000213 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000214 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000215
Ted Kremenek42730c52008-01-07 19:49:32 +0000216 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
217 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000218 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000219 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000220 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000221 const char *ClassName,
222 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000223
Chris Lattner0be08822008-07-21 21:32:27 +0000224 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
225 &Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000226 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000227 const char *ClassName,
228 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000229 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000230 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000231 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
232 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000233 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000234 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000235 };
236}
237
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000238static bool IsHeaderFile(const std::string &Filename) {
239 std::string::size_type DotPos = Filename.rfind('.');
240
241 if (DotPos == std::string::npos) {
242 // no file extension
243 return false;
244 }
245
246 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
247 // C header: .h
248 // C++ header: .hh or .H;
249 return Ext == "h" || Ext == "hh" || Ext == "H";
250}
251
Steve Naroff44e81222008-04-14 22:03:09 +0000252RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000253 Diagnostic &D, const LangOptions &LOpts)
254 : Diags(D), LangOpts(LOpts) {
255 IsHeader = IsHeaderFile(inFile);
256 InFileName = inFile;
257 OutFileName = outFile;
258 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
259 "rewriting sub-expression within a macro (may not be correct)");
260}
261
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000262ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000263 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000264 Diagnostic &Diags,
265 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000266 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000267}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000268
Steve Naroff44e81222008-04-14 22:03:09 +0000269void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000270 Context = &context;
271 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000272 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000273 MsgSendFunctionDecl = 0;
274 MsgSendSuperFunctionDecl = 0;
275 MsgSendStretFunctionDecl = 0;
276 MsgSendSuperStretFunctionDecl = 0;
277 MsgSendFpretFunctionDecl = 0;
278 GetClassFunctionDecl = 0;
279 GetMetaClassFunctionDecl = 0;
280 SelGetUidFunctionDecl = 0;
281 CFStringFunctionDecl = 0;
282 GetProtocolFunctionDecl = 0;
283 ConstantStringClassReference = 0;
284 NSStringRecord = 0;
285 CurMethodDecl = 0;
286 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000287 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000288 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000289 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000290 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000291
292 // Get the ID and start/end of the main file.
293 MainFileID = SM->getMainFileID();
294 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
295 MainFileStart = MainBuf->getBufferStart();
296 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000297
Chris Lattner12499682008-01-31 19:38:44 +0000298 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000299
Chris Lattner12499682008-01-31 19:38:44 +0000300 // declaring objc_selector outside the parameter list removes a silly
301 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000302 if (IsHeader)
303 Preamble = "#pragma once\n";
304 Preamble += "struct objc_selector; struct objc_class;\n";
305 Preamble += "#ifndef OBJC_SUPER\n";
306 Preamble += "struct objc_super { struct objc_object *object; ";
307 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000308 if (LangOpts.Microsoft) {
309 // Add a constructor for creating temporary objects.
Steve Narofffef037c2008-03-27 22:29:16 +0000310 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
311 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000312 }
Steve Narofffef037c2008-03-27 22:29:16 +0000313 Preamble += "};\n";
314 Preamble += "#define OBJC_SUPER\n";
315 Preamble += "#endif\n";
316 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
317 Preamble += "typedef struct objc_object Protocol;\n";
318 Preamble += "#define _REWRITER_typedef_Protocol\n";
319 Preamble += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000320 if (LangOpts.Microsoft)
Steve Naroff618c6a42008-05-06 22:45:19 +0000321 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
322 else
323 Preamble += "#define __OBJC_RW_EXTERN extern\n";
324 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000325 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000326 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000327 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000328 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000329 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000330 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000331 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff31316a12008-05-08 22:02:18 +0000332 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000333 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroffa9636222008-05-08 17:52:16 +0000334 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000335 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000336 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000337 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000338 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
339 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
340 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
341 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
342 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000343 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000344 // @synchronized hooks.
345 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
346 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000347 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000348 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
349 Preamble += "struct __objcFastEnumerationState {\n\t";
350 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000351 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000352 Preamble += "unsigned long *mutationsPtr;\n\t";
353 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff37157242008-06-02 20:23:21 +0000354 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000355 Preamble += "#define __FASTENUMERATIONSTATE\n";
356 Preamble += "#endif\n";
357 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
358 Preamble += "struct __NSConstantStringImpl {\n";
359 Preamble += " int *isa;\n";
360 Preamble += " int flags;\n";
361 Preamble += " char *str;\n";
362 Preamble += " long length;\n";
363 Preamble += "};\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000364 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
365 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
366 Preamble += "#else\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000367 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000368 Preamble += "#endif\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000369 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
370 Preamble += "#endif\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000371 if (LangOpts.Microsoft) {
372 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000373 Preamble += "#define __attribute__(X)\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000374 }
Chris Lattner12499682008-01-31 19:38:44 +0000375}
376
377
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000378//===----------------------------------------------------------------------===//
379// Top Level Driver Code
380//===----------------------------------------------------------------------===//
381
Steve Naroff44e81222008-04-14 22:03:09 +0000382void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000383 // Two cases: either the decl could be in the main file, or it could be in a
384 // #included file. If the former, rewrite it now. If the later, check to see
385 // if we rewrote the #include/#import.
386 SourceLocation Loc = D->getLocation();
387 Loc = SM->getLogicalLoc(Loc);
388
389 // If this is for a builtin, ignore it.
390 if (Loc.isInvalid()) return;
391
Steve Naroffe9780582007-10-23 23:50:29 +0000392 // Look for built-in declarations that we need to refer during the rewrite.
393 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000394 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000395 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000396 // declared in <Foundation/NSString.h>
397 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
398 ConstantStringClassReference = FVD;
399 return;
400 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000401 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000402 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000403 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000404 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000405 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000406 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000407 } else if (ObjCForwardProtocolDecl *FP =
408 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000409 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000410 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000411 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000412 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000413 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000414}
415
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000416/// HandleDeclInMainFile - This is called for each top-level decl defined in the
417/// main file of the input.
Steve Naroff44e81222008-04-14 22:03:09 +0000418void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000419 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
420 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000421 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000422
Ted Kremenek42730c52008-01-07 19:49:32 +0000423 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000424 if (Stmt *Body = MD->getBody()) {
425 //Body->dump();
426 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000427 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000428 CurMethodDecl = 0;
429 }
Steve Naroff18c83382007-11-13 23:01:27 +0000430 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000431 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000432 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000433 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000434 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000435 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000436 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000437 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000438 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000439 if (VD->getInit())
440 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
441 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000442 // Nothing yet.
443}
444
Ted Kremenekcab0b0c2008-08-08 04:15:52 +0000445void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000446 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000447
448 // Rewrite tabs if we care.
449 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000450
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000451 if (Diags.hasErrorOccurred())
452 return;
453
454 // Create the output file.
455
456 std::ostream *OutFile;
457 if (OutFileName == "-") {
458 OutFile = llvm::cout.stream();
459 } else if (!OutFileName.empty()) {
460 OutFile = new std::ofstream(OutFileName.c_str(),
461 std::ios_base::binary|std::ios_base::out);
462 } else if (InFileName == "-") {
463 OutFile = llvm::cout.stream();
464 } else {
465 llvm::sys::Path Path(InFileName);
466 Path.eraseSuffix();
467 Path.appendSuffix("cpp");
468 OutFile = new std::ofstream(Path.toString().c_str(),
469 std::ios_base::binary|std::ios_base::out);
470 }
471
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000472 RewriteInclude();
473
Steve Narofffef037c2008-03-27 22:29:16 +0000474 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
475 Preamble.c_str(), Preamble.size(), false);
476
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000477 // Rewrite Objective-c meta data*
478 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000479 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000480
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000481 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
482 // we are done.
483 if (const RewriteBuffer *RewriteBuf =
484 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000485 //printf("Changed:\n");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000486 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000487 } else {
Chris Lattner673f2bd2008-03-22 00:08:40 +0000488 fprintf(stderr, "No changes\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000489 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000490 // Emit metadata.
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000491 *OutFile << ResultStr;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000492}
493
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000494//===----------------------------------------------------------------------===//
495// Syntactic (non-AST) Rewriting Code
496//===----------------------------------------------------------------------===//
497
Steve Naroff44e81222008-04-14 22:03:09 +0000498void RewriteObjC::RewriteInclude() {
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000499 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
500 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
501 const char *MainBufStart = MainBuf.first;
502 const char *MainBufEnd = MainBuf.second;
503 size_t ImportLen = strlen("import");
504 size_t IncludeLen = strlen("include");
505
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000506 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000507 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
508 if (*BufPtr == '#') {
509 if (++BufPtr == MainBufEnd)
510 return;
511 while (*BufPtr == ' ' || *BufPtr == '\t')
512 if (++BufPtr == MainBufEnd)
513 return;
514 if (!strncmp(BufPtr, "import", ImportLen)) {
515 // replace import with include
516 SourceLocation ImportLoc =
517 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000518 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000519 BufPtr += ImportLen;
520 }
521 }
522 }
Chris Lattner74db1682007-10-16 21:07:07 +0000523}
524
Steve Naroff44e81222008-04-14 22:03:09 +0000525void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000526 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
527 const char *MainBufStart = MainBuf.first;
528 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000529
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000530 // Loop over the whole file, looking for tabs.
531 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
532 if (*BufPtr != '\t')
533 continue;
534
535 // Okay, we found a tab. This tab will turn into at least one character,
536 // but it depends on which 'virtual column' it is in. Compute that now.
537 unsigned VCol = 0;
538 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
539 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
540 ++VCol;
541
542 // Okay, now that we know the virtual column, we know how many spaces to
543 // insert. We assume 8-character tab-stops.
544 unsigned Spaces = 8-(VCol & 7);
545
546 // Get the location of the tab.
547 SourceLocation TabLoc =
548 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
549
550 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000551 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000552 }
Chris Lattner569faa62007-10-11 18:38:32 +0000553}
554
555
Steve Naroff44e81222008-04-14 22:03:09 +0000556void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000557 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000558 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000559
560 // Get the start location and compute the semi location.
561 SourceLocation startLoc = ClassDecl->getLocation();
562 const char *startBuf = SM->getCharacterData(startLoc);
563 const char *semiPtr = strchr(startBuf, ';');
564
565 // Translate to typedef's that forward reference structs with the same name
566 // as the class. As a convenience, we include the original declaration
567 // as a comment.
568 std::string typedefString;
569 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000570 typedefString.append(startBuf, semiPtr-startBuf+1);
571 typedefString += "\n";
572 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000573 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000574 typedefString += "#ifndef _REWRITER_typedef_";
575 typedefString += ForwardDecl->getName();
576 typedefString += "\n";
577 typedefString += "#define _REWRITER_typedef_";
578 typedefString += ForwardDecl->getName();
579 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000580 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000581 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000582 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000583 }
584
585 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000586 ReplaceText(startLoc, semiPtr-startBuf+1,
587 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000588}
589
Steve Naroff44e81222008-04-14 22:03:09 +0000590void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000591 SourceLocation LocStart = Method->getLocStart();
592 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000593
Steve Naroff2ce399a2007-12-14 23:37:57 +0000594 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattner6216f292008-01-31 19:42:41 +0000595 InsertText(LocStart, "/* ", 3);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000596 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000597 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000598 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000599 }
600}
601
Steve Naroff44e81222008-04-14 22:03:09 +0000602void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000603{
Chris Lattnercffe3662008-03-16 21:23:50 +0000604 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000605 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000606 SourceLocation Loc = Property->getLocation();
607
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000608 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000609
610 // FIXME: handle properties that are declared across multiple lines.
611 }
612}
613
Steve Naroff44e81222008-04-14 22:03:09 +0000614void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000615 SourceLocation LocStart = CatDecl->getLocStart();
616
617 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000618 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000619
Ted Kremenek42730c52008-01-07 19:49:32 +0000620 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000621 E = CatDecl->instmeth_end(); I != E; ++I)
622 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000623 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000624 E = CatDecl->classmeth_end(); I != E; ++I)
625 RewriteMethodDeclaration(*I);
626
Steve Naroff667f1682007-10-30 13:30:57 +0000627 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000628 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000629}
630
Steve Naroff44e81222008-04-14 22:03:09 +0000631void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000632 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000633
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000634 SourceLocation LocStart = PDecl->getLocStart();
635
636 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000637 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000638
Ted Kremenek42730c52008-01-07 19:49:32 +0000639 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000640 E = PDecl->instmeth_end(); I != E; ++I)
641 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000642 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000643 E = PDecl->classmeth_end(); I != E; ++I)
644 RewriteMethodDeclaration(*I);
645
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000646 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000647 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000648 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000649
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000650 // Must comment out @optional/@required
651 const char *startBuf = SM->getCharacterData(LocStart);
652 const char *endBuf = SM->getCharacterData(LocEnd);
653 for (const char *p = startBuf; p < endBuf; p++) {
654 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
655 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000656 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000657 ReplaceText(OptionalLoc, strlen("@optional"),
658 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000659
660 }
661 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
662 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000663 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000664 ReplaceText(OptionalLoc, strlen("@required"),
665 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000666
667 }
668 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000669}
670
Steve Naroff44e81222008-04-14 22:03:09 +0000671void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000672 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000673 if (LocStart.isInvalid())
674 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000675 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000676 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000677}
678
Steve Naroff44e81222008-04-14 22:03:09 +0000679void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000680 std::string &ResultStr) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000681 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000682 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000683 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000684 ResultStr += "id";
Steve Naroff91044cf2008-07-16 14:40:40 +0000685 else if (OMD->getResultType()->isFunctionPointerType()) {
686 // needs special handling, since pointer-to-functions have special
687 // syntax (where a decaration models use).
688 QualType retType = OMD->getResultType();
689 if (const PointerType* PT = retType->getAsPointerType()) {
690 QualType PointeeTy = PT->getPointeeType();
691 if ((FPRetType = PointeeTy->getAsFunctionType())) {
692 ResultStr += FPRetType->getResultType().getAsString();
693 ResultStr += "(*";
694 }
695 }
696 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000697 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000698 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000699
700 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000701 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000702
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000703 if (OMD->isInstance())
704 NameStr += "_I_";
705 else
706 NameStr += "_C_";
707
708 NameStr += OMD->getClassInterface()->getName();
709 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000710
711 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000712 if (ObjCCategoryImplDecl *CID =
713 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000714 NameStr += CID->getName();
715 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000716 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000717 // Append selector names, replacing ':' with '_'
718 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000719 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000720 else {
721 std::string selString = OMD->getSelector().getName();
722 int len = selString.size();
723 for (int i = 0; i < len; i++)
724 if (selString[i] == ':')
725 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000726 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000727 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000728 // Remember this name for metadata emission
729 MethodInternalNames[OMD] = NameStr;
730 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000731
732 // Rewrite arguments
733 ResultStr += "(";
734
735 // invisible arguments
736 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000737 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000738 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000739 if (!LangOpts.Microsoft) {
740 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
741 ResultStr += "struct ";
742 }
743 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroffde0da102008-03-10 23:16:54 +0000744 ResultStr += OMD->getClassInterface()->getName();
Steve Naroffde0da102008-03-10 23:16:54 +0000745 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000746 }
747 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000748 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000749
750 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000751 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000752 ResultStr += " _cmd";
753
754 // Method arguments.
Chris Lattner685d7922008-03-16 01:07:14 +0000755 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000756 ParmVarDecl *PDecl = OMD->getParamDecl(i);
757 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000758 if (PDecl->getType()->isObjCQualifiedIdType()) {
759 ResultStr += "id ";
760 ResultStr += PDecl->getName();
761 } else {
762 std::string Name = PDecl->getName();
763 PDecl->getType().getAsStringInternal(Name);
764 ResultStr += Name;
765 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000766 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000767 if (OMD->isVariadic())
768 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000769 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000770
Steve Naroff91044cf2008-07-16 14:40:40 +0000771 if (FPRetType) {
772 ResultStr += ")"; // close the precedence "scope" for "*".
773
774 // Now, emit the argument types (if any).
775 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
776 ResultStr += "(";
777 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
778 if (i) ResultStr += ", ";
779 std::string ParamStr = FT->getArgType(i).getAsString();
780 ResultStr += ParamStr;
781 }
782 if (FT->isVariadic()) {
783 if (FT->getNumArgs()) ResultStr += ", ";
784 ResultStr += "...";
785 }
786 ResultStr += ")";
787 } else {
788 ResultStr += "()";
789 }
790 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000791}
Steve Naroff44e81222008-04-14 22:03:09 +0000792void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000793 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
794 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000795
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000796 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000797 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000798 else
Chris Lattner6216f292008-01-31 19:42:41 +0000799 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000800
Ted Kremenek42730c52008-01-07 19:49:32 +0000801 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000802 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
803 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000804 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000805 ObjCMethodDecl *OMD = *I;
806 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000807 SourceLocation LocStart = OMD->getLocStart();
808 SourceLocation LocEnd = OMD->getBody()->getLocStart();
809
810 const char *startBuf = SM->getCharacterData(LocStart);
811 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000812 ReplaceText(LocStart, endBuf-startBuf,
813 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000814 }
815
Ted Kremenek42730c52008-01-07 19:49:32 +0000816 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000817 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
818 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000819 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000820 ObjCMethodDecl *OMD = *I;
821 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000822 SourceLocation LocStart = OMD->getLocStart();
823 SourceLocation LocEnd = OMD->getBody()->getLocStart();
824
825 const char *startBuf = SM->getCharacterData(LocStart);
826 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000827 ReplaceText(LocStart, endBuf-startBuf,
828 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000829 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000830 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000831 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000832 else
Chris Lattner6216f292008-01-31 19:42:41 +0000833 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000834}
835
Steve Naroff44e81222008-04-14 22:03:09 +0000836void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000837 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000838 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000839 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000840 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000841 ResultStr += ClassDecl->getName();
842 ResultStr += "\n";
843 ResultStr += "#define _REWRITER_typedef_";
844 ResultStr += ClassDecl->getName();
845 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000846 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000847 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000848 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000849 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000850 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000851 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000852 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000853
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000854 RewriteProperties(ClassDecl->getNumPropertyDecl(),
855 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000856 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000857 E = ClassDecl->instmeth_end(); I != E; ++I)
858 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000859 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000860 E = ClassDecl->classmeth_end(); I != E; ++I)
861 RewriteMethodDeclaration(*I);
862
Steve Naroff1ccf4632007-10-30 03:43:13 +0000863 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000864 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000865}
866
Chris Lattner343c82b2008-05-23 20:40:52 +0000867Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
868 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000869 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000870 if (CurMethodDecl) {
871 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000872 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
873 // lookup which class implements the instance variable.
874 ObjCInterfaceDecl *clsDeclared = 0;
875 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
876 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
877
878 // Synthesize an explicit cast to gain access to the ivar.
879 std::string RecName = clsDeclared->getIdentifier()->getName();
880 RecName += "_IMPL";
881 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000882 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +0000883 SourceLocation(), II);
Steve Naroffa9636222008-05-08 17:52:16 +0000884 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
885 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +0000886 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
887 SourceLocation());
Steve Naroffa9636222008-05-08 17:52:16 +0000888 // Don't forget the parens to enforce the proper binding.
Chris Lattner343c82b2008-05-23 20:40:52 +0000889 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
890 IV->getBase()->getLocEnd(),
891 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +0000892 if (IV->isFreeIvar() &&
893 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner343c82b2008-05-23 20:40:52 +0000894 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
895 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +0000896 ReplaceStmt(IV, ME);
897 delete IV;
898 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +0000899 }
Chris Lattner343c82b2008-05-23 20:40:52 +0000900
901 ReplaceStmt(IV->getBase(), PE);
902 // Cannot delete IV->getBase(), since PE points to it.
903 // Replace the old base with the cast. This is important when doing
904 // embedded rewrites. For example, [newInv->_container addObject:0].
905 IV->setBase(PE);
906 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000907 }
Steve Naroffe6155362008-04-18 21:55:08 +0000908 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +0000909 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
910
911 // Explicit ivar refs need to have a cast inserted.
912 // FIXME: consider sharing some of this code with the code above.
913 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000914 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +0000915 // lookup which class implements the instance variable.
916 ObjCInterfaceDecl *clsDeclared = 0;
Steve Naroffa9636222008-05-08 17:52:16 +0000917 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000918 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
919
920 // Synthesize an explicit cast to gain access to the ivar.
921 std::string RecName = clsDeclared->getIdentifier()->getName();
922 RecName += "_IMPL";
923 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000924 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +0000925 SourceLocation(), II);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000926 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
927 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +0000928 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
929 SourceLocation());
Steve Naroffd8d30b92008-05-06 23:20:07 +0000930 // Don't forget the parens to enforce the proper binding.
Chris Lattner3cca6612008-05-28 16:38:23 +0000931 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
932 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000933 ReplaceStmt(IV->getBase(), PE);
934 // Cannot delete IV->getBase(), since PE points to it.
935 // Replace the old base with the cast. This is important when doing
936 // embedded rewrites. For example, [newInv->_container addObject:0].
937 IV->setBase(PE);
938 return IV;
939 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000940 }
Steve Naroffe6155362008-04-18 21:55:08 +0000941 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000942}
943
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000944//===----------------------------------------------------------------------===//
945// Function Body / Expression rewriting
946//===----------------------------------------------------------------------===//
947
Steve Naroff44e81222008-04-14 22:03:09 +0000948Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000949 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
950 isa<DoStmt>(S) || isa<ForStmt>(S))
951 Stmts.push_back(S);
952 else if (isa<ObjCForCollectionStmt>(S)) {
953 Stmts.push_back(S);
954 ObjCBcLabelNo.push_back(++BcLabelCount);
955 }
956
Chris Lattner343c82b2008-05-23 20:40:52 +0000957 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner2c022162008-01-31 05:10:40 +0000958
959 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000960 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
961 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000962 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000963 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000964 if (newStmt)
965 *CI = newStmt;
966 }
Steve Naroffe9780582007-10-23 23:50:29 +0000967
968 // Handle specific things.
969 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
970 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000971
972 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner343c82b2008-05-23 20:40:52 +0000973 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroff296b74f2007-11-05 14:50:49 +0000974
975 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
976 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000977
Steve Naroff0add5d22007-11-03 11:27:19 +0000978 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
979 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000980
Steve Naroff71226032007-10-24 22:48:43 +0000981 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
982 // Before we rewrite it, put the original message expression in a comment.
983 SourceLocation startLoc = MessExpr->getLocStart();
984 SourceLocation endLoc = MessExpr->getLocEnd();
985
986 const char *startBuf = SM->getCharacterData(startLoc);
987 const char *endBuf = SM->getCharacterData(endLoc);
988
989 std::string messString;
990 messString += "// ";
991 messString.append(startBuf, endBuf-startBuf+1);
992 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000993
Chris Lattner6216f292008-01-31 19:42:41 +0000994 // FIXME: Missing definition of
995 // InsertText(clang::SourceLocation, char const*, unsigned int).
996 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff71226032007-10-24 22:48:43 +0000997 // Tried this, but it didn't work either...
Chris Lattner6216f292008-01-31 19:42:41 +0000998 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000999 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001000 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001001
Ted Kremenek42730c52008-01-07 19:49:32 +00001002 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
1003 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001004
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001005 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
1006 return RewriteObjCSynchronizedStmt(StmtTry);
1007
Ted Kremenek42730c52008-01-07 19:49:32 +00001008 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
1009 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001010
1011 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
1012 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001013
1014 if (ObjCForCollectionStmt *StmtForCollection =
1015 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner343c82b2008-05-23 20:40:52 +00001016 return RewriteObjCForCollectionStmt(StmtForCollection,
1017 OrigStmtRange.getEnd());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001018 if (BreakStmt *StmtBreakStmt =
1019 dyn_cast<BreakStmt>(S))
1020 return RewriteBreakStmt(StmtBreakStmt);
1021 if (ContinueStmt *StmtContinueStmt =
1022 dyn_cast<ContinueStmt>(S))
1023 return RewriteContinueStmt(StmtContinueStmt);
Steve Naroffd06c88d2008-07-29 18:15:38 +00001024
1025 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls and cast exprs.
1026 if (DeclStmt *DS = dyn_cast<DeclStmt>(S))
1027 RewriteObjCQualifiedInterfaceTypes(DS->getDecl());
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001028 if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(S))
Steve Naroffd06c88d2008-07-29 18:15:38 +00001029 RewriteObjCQualifiedInterfaceTypes(CE);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001030
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001031 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1032 isa<DoStmt>(S) || isa<ForStmt>(S)) {
1033 assert(!Stmts.empty() && "Statement stack is empty");
1034 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
1035 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
1036 && "Statement stack mismatch");
1037 Stmts.pop_back();
1038 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001039#if 0
1040 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
1041 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
1042 // Get the new text.
1043 std::ostringstream Buf;
1044 Replacement->printPretty(Buf);
1045 const std::string &Str = Buf.str();
1046
1047 printf("CAST = %s\n", &Str[0]);
Chris Lattner6216f292008-01-31 19:42:41 +00001048 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001049 delete S;
1050 return Replacement;
1051 }
1052#endif
Chris Lattner0021f452007-10-24 16:57:36 +00001053 // Return this stmt unmodified.
1054 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001055}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001056
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001057/// SynthCountByEnumWithState - To print:
1058/// ((unsigned int (*)
1059/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1060/// (void *)objc_msgSend)((id)l_collection,
1061/// sel_registerName(
1062/// "countByEnumeratingWithState:objects:count:"),
1063/// &enumState,
1064/// (id *)items, (unsigned int)16)
1065///
Steve Naroff44e81222008-04-14 22:03:09 +00001066void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001067 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1068 "id *, unsigned int))(void *)objc_msgSend)";
1069 buf += "\n\t\t";
1070 buf += "((id)l_collection,\n\t\t";
1071 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1072 buf += "\n\t\t";
1073 buf += "&enumState, "
1074 "(id *)items, (unsigned int)16)";
1075}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001076
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001077/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1078/// statement to exit to its outer synthesized loop.
1079///
Steve Naroff44e81222008-04-14 22:03:09 +00001080Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001081 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1082 return S;
1083 // replace break with goto __break_label
1084 std::string buf;
1085
1086 SourceLocation startLoc = S->getLocStart();
1087 buf = "goto __break_label_";
1088 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001089 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001090
1091 return 0;
1092}
1093
1094/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1095/// statement to continue with its inner synthesized loop.
1096///
Steve Naroff44e81222008-04-14 22:03:09 +00001097Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001098 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1099 return S;
1100 // replace continue with goto __continue_label
1101 std::string buf;
1102
1103 SourceLocation startLoc = S->getLocStart();
1104 buf = "goto __continue_label_";
1105 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001106 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001107
1108 return 0;
1109}
1110
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001111/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001112/// It rewrites:
1113/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001114
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001115/// Into:
1116/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001117/// type elem;
1118/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001119/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001120/// id l_collection = (id)collection;
1121/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1122/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001123/// if (limit) {
1124/// unsigned long startMutations = *enumState.mutationsPtr;
1125/// do {
1126/// unsigned long counter = 0;
1127/// do {
1128/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001129/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001130/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001131/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001132/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001133/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001134/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1135/// objects:items count:16]);
1136/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001137/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001138/// }
1139/// else
1140/// elem = nil;
1141/// }
1142///
Steve Naroff44e81222008-04-14 22:03:09 +00001143Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001144 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001145 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1146 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1147 "ObjCForCollectionStmt Statement stack mismatch");
1148 assert(!ObjCBcLabelNo.empty() &&
1149 "ObjCForCollectionStmt - Label No stack empty");
1150
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001151 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001152 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001153 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001154 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001155 std::string buf;
1156 buf = "\n{\n\t";
1157 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1158 // type elem;
1159 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001160 elementTypeAsString = ElementType.getAsString();
1161 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001162 buf += " ";
1163 elementName = DS->getDecl()->getName();
1164 buf += elementName;
1165 buf += ";\n\t";
1166 }
Chris Lattner690c2872008-04-08 05:52:18 +00001167 else {
1168 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001169 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001170 elementTypeAsString = DR->getDecl()->getType().getAsString();
1171 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001172
1173 // struct __objcFastEnumerationState enumState = { 0 };
1174 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1175 // id items[16];
1176 buf += "id items[16];\n\t";
1177 // id l_collection = (id)
1178 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001179 // Find start location of 'collection' the hard way!
1180 const char *startCollectionBuf = startBuf;
1181 startCollectionBuf += 3; // skip 'for'
1182 startCollectionBuf = strchr(startCollectionBuf, '(');
1183 startCollectionBuf++; // skip '('
1184 // find 'in' and skip it.
1185 while (*startCollectionBuf != ' ' ||
1186 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1187 (*(startCollectionBuf+3) != ' ' &&
1188 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1189 startCollectionBuf++;
1190 startCollectionBuf += 3;
1191
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001192 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001193 ReplaceText(startLoc, startCollectionBuf - startBuf,
1194 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001195 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001196 SourceLocation rightParenLoc = S->getRParenLoc();
1197 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1198 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001199 buf = ";\n\t";
1200
1201 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1202 // objects:items count:16];
1203 // which is synthesized into:
1204 // unsigned int limit =
1205 // ((unsigned int (*)
1206 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1207 // (void *)objc_msgSend)((id)l_collection,
1208 // sel_registerName(
1209 // "countByEnumeratingWithState:objects:count:"),
1210 // (struct __objcFastEnumerationState *)&state,
1211 // (id *)items, (unsigned int)16);
1212 buf += "unsigned long limit =\n\t\t";
1213 SynthCountByEnumWithState(buf);
1214 buf += ";\n\t";
1215 /// if (limit) {
1216 /// unsigned long startMutations = *enumState.mutationsPtr;
1217 /// do {
1218 /// unsigned long counter = 0;
1219 /// do {
1220 /// if (startMutations != *enumState.mutationsPtr)
1221 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001222 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001223 buf += "if (limit) {\n\t";
1224 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1225 buf += "do {\n\t\t";
1226 buf += "unsigned long counter = 0;\n\t\t";
1227 buf += "do {\n\t\t\t";
1228 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1229 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1230 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001231 buf += " = (";
1232 buf += elementTypeAsString;
1233 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001234 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001235 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001236
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001237 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001238 /// } while (counter < limit);
1239 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1240 /// objects:items count:16]);
1241 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001242 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001243 /// }
1244 /// else
1245 /// elem = nil;
1246 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001247 ///
1248 buf = ";\n\t";
1249 buf += "__continue_label_";
1250 buf += utostr(ObjCBcLabelNo.back());
1251 buf += ": ;";
1252 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001253 buf += "} while (counter < limit);\n\t";
1254 buf += "} while (limit = ";
1255 SynthCountByEnumWithState(buf);
1256 buf += ");\n\t";
1257 buf += elementName;
1258 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001259 buf += "__break_label_";
1260 buf += utostr(ObjCBcLabelNo.back());
1261 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001262 buf += "}\n\t";
1263 buf += "else\n\t\t";
1264 buf += elementName;
1265 buf += " = nil;\n";
1266 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001267
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001268 // Insert all these *after* the statement body.
Steve Naroff5f238fe2008-07-21 18:26:02 +00001269 if (isa<CompoundStmt>(S->getBody())) {
1270 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1271 InsertText(endBodyLoc, buf.c_str(), buf.size());
1272 } else {
1273 /* Need to treat single statements specially. For example:
1274 *
1275 * for (A *a in b) if (stuff()) break;
1276 * for (A *a in b) xxxyy;
1277 *
1278 * The following code simply scans ahead to the semi to find the actual end.
1279 */
1280 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1281 const char *semiBuf = strchr(stmtBuf, ';');
1282 assert(semiBuf && "Can't find ';'");
1283 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1284 InsertText(endBodyLoc, buf.c_str(), buf.size());
1285 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001286 Stmts.pop_back();
1287 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001288 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001289}
1290
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001291/// RewriteObjCSynchronizedStmt -
1292/// This routine rewrites @synchronized(expr) stmt;
1293/// into:
1294/// objc_sync_enter(expr);
1295/// @try stmt @finally { objc_sync_exit(expr); }
1296///
Steve Naroff44e81222008-04-14 22:03:09 +00001297Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001298 // Get the start location and compute the semi location.
1299 SourceLocation startLoc = S->getLocStart();
1300 const char *startBuf = SM->getCharacterData(startLoc);
1301
1302 assert((*startBuf == '@') && "bogus @synchronized location");
1303
1304 std::string buf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001305 buf = "objc_sync_enter((id)";
1306 const char *lparenBuf = startBuf;
1307 while (*lparenBuf != '(') lparenBuf++;
1308 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroff027cd0b2008-08-19 13:04:19 +00001309 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1310 // the sync expression is typically a message expression that's already
1311 // been rewritten! (which implies the SourceLocation's are invalid).
1312 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001313 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroff027cd0b2008-08-19 13:04:19 +00001314 while (*endBuf != ')') endBuf--;
1315 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001316 buf = ");\n";
1317 // declare a new scope with two variables, _stack and _rethrow.
1318 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1319 buf += "int buf[18/*32-bit i386*/];\n";
1320 buf += "char *pointers[4];} _stack;\n";
1321 buf += "id volatile _rethrow = 0;\n";
1322 buf += "objc_exception_try_enter(&_stack);\n";
1323 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001324 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001325 startLoc = S->getSynchBody()->getLocEnd();
1326 startBuf = SM->getCharacterData(startLoc);
1327
Steve Naroff027cd0b2008-08-19 13:04:19 +00001328 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001329 SourceLocation lastCurlyLoc = startLoc;
1330 buf = "}\nelse {\n";
1331 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1332 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001333 buf += " objc_sync_exit(";
Steve Naroffc1656a62008-08-21 13:03:03 +00001334 Expr *syncExpr = new ExplicitCastExpr(Context->getObjCIdType(),
1335 S->getSynchExpr(), SourceLocation());
Steve Naroff17919b52008-07-16 19:47:39 +00001336 std::ostringstream syncExprBuf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001337 syncExpr->printPretty(syncExprBuf);
Steve Naroff17919b52008-07-16 19:47:39 +00001338 buf += syncExprBuf.str();
1339 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001340 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1341 buf += "}\n";
1342 buf += "}";
1343
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001344 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001345 return 0;
1346}
1347
Steve Naroff44e81222008-04-14 22:03:09 +00001348Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001349 // Get the start location and compute the semi location.
1350 SourceLocation startLoc = S->getLocStart();
1351 const char *startBuf = SM->getCharacterData(startLoc);
1352
1353 assert((*startBuf == '@') && "bogus @try location");
1354
1355 std::string buf;
1356 // declare a new scope with two variables, _stack and _rethrow.
1357 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1358 buf += "int buf[18/*32-bit i386*/];\n";
1359 buf += "char *pointers[4];} _stack;\n";
1360 buf += "id volatile _rethrow = 0;\n";
1361 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001362 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001363
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001364 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001365
1366 startLoc = S->getTryBody()->getLocEnd();
1367 startBuf = SM->getCharacterData(startLoc);
1368
1369 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001370
Steve Naroffe9f69842007-11-07 04:08:17 +00001371 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001372 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1373 if (catchList) {
1374 startLoc = startLoc.getFileLocWithOffset(1);
1375 buf = " /* @catch begin */ else {\n";
1376 buf += " id _caught = objc_exception_extract(&_stack);\n";
1377 buf += " objc_exception_try_enter (&_stack);\n";
1378 buf += " if (_setjmp(_stack.buf))\n";
1379 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1380 buf += " else { /* @catch continue */";
1381
1382 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff36269d22008-09-09 19:59:12 +00001383 } else { /* no catch list */
1384 buf = "}\nelse {\n";
1385 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1386 buf += "}";
1387 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff9d0ff352008-07-16 15:31:30 +00001388 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001389 bool sawIdTypedCatch = false;
1390 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001391 while (catchList) {
1392 Stmt *catchStmt = catchList->getCatchParamStmt();
1393
1394 if (catchList == S->getCatchStmts())
1395 buf = "if ("; // we are generating code for the first catch clause
1396 else
1397 buf = "else if (";
1398 startLoc = catchList->getLocStart();
1399 startBuf = SM->getCharacterData(startLoc);
1400
1401 assert((*startBuf == '@') && "bogus @catch location");
1402
1403 const char *lParenLoc = strchr(startBuf, '(');
1404
Steve Naroff397c4ce2008-02-01 22:08:12 +00001405 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001406 // Now rewrite the body...
1407 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001408 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1409 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001410 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1411 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001412 assert((*bodyBuf == '{') && "bogus @catch body location");
1413
1414 buf += "1) { id _tmp = _caught;";
1415 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1416 buf.c_str(), buf.size());
1417 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001418 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001419 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001420 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001421 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001422 sawIdTypedCatch = true;
1423 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001424 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001425
Ted Kremenek42730c52008-01-07 19:49:32 +00001426 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001427 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001428 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001429 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001430 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001431 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001432 }
1433 }
1434 // Now rewrite the body...
1435 lastCatchBody = catchList->getCatchBody();
1436 SourceLocation rParenLoc = catchList->getRParenLoc();
1437 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1438 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1439 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1440 assert((*rParenBuf == ')') && "bogus @catch paren location");
1441 assert((*bodyBuf == '{') && "bogus @catch body location");
1442
1443 buf = " = _caught;";
1444 // Here we replace ") {" with "= _caught;" (which initializes and
1445 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001446 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001447 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001448 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001449 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001450 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001451 catchList = catchList->getNextCatchStmt();
1452 }
1453 // Complete the catch list...
1454 if (lastCatchBody) {
1455 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001456 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1457 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001458
Steve Naroff31325c12008-09-11 15:29:03 +00001459 // Insert the last (implicit) else clause *before* the right curly brace.
1460 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1461 buf = "} /* last catch end */\n";
1462 buf += "else {\n";
1463 buf += " _rethrow = _caught;\n";
1464 buf += " objc_exception_try_exit(&_stack);\n";
1465 buf += "} } /* @catch end */\n";
1466 if (!S->getFinallyStmt())
1467 buf += "}\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001468 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001469
1470 // Set lastCurlyLoc
1471 lastCurlyLoc = lastCatchBody->getLocEnd();
1472 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001473 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001474 startLoc = finalStmt->getLocStart();
1475 startBuf = SM->getCharacterData(startLoc);
1476 assert((*startBuf == '@') && "bogus @finally start");
1477
1478 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001479 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001480
1481 Stmt *body = finalStmt->getFinallyBody();
1482 SourceLocation startLoc = body->getLocStart();
1483 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001484 assert(*SM->getCharacterData(startLoc) == '{' &&
1485 "bogus @finally body location");
1486 assert(*SM->getCharacterData(endLoc) == '}' &&
1487 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001488
1489 startLoc = startLoc.getFileLocWithOffset(1);
1490 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001491 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001492 endLoc = endLoc.getFileLocWithOffset(-1);
1493 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001494 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001495
1496 // Set lastCurlyLoc
1497 lastCurlyLoc = body->getLocEnd();
Steve Naroff31325c12008-09-11 15:29:03 +00001498 } else { /* no finally clause - make sure we synthesize an implicit one */
1499 buf = "{ /* implicit finally clause */\n";
1500 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1501 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1502 buf += "}";
1503 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001504 }
1505 // Now emit the final closing curly brace...
1506 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1507 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001508 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001509 return 0;
1510}
1511
Steve Naroff44e81222008-04-14 22:03:09 +00001512Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001513 return 0;
1514}
1515
Steve Naroff44e81222008-04-14 22:03:09 +00001516Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001517 return 0;
1518}
1519
Chris Lattnerb1548372008-01-31 19:37:57 +00001520// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001521// the throw expression is typically a message expression that's already
1522// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001523Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001524 // Get the start location and compute the semi location.
1525 SourceLocation startLoc = S->getLocStart();
1526 const char *startBuf = SM->getCharacterData(startLoc);
1527
1528 assert((*startBuf == '@') && "bogus @throw location");
1529
1530 std::string buf;
1531 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001532 if (S->getThrowExpr())
1533 buf = "objc_exception_throw(";
1534 else // add an implicit argument
1535 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001536
1537 // handle "@ throw" correctly.
1538 const char *wBuf = strchr(startBuf, 'w');
1539 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1540 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1541
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001542 const char *semiBuf = strchr(startBuf, ';');
1543 assert((*semiBuf == ';') && "@throw: can't find ';'");
1544 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1545 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001546 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001547 return 0;
1548}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001549
Steve Naroff44e81222008-04-14 22:03:09 +00001550Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001551 // Create a new string expression.
1552 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001553 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001554 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1555 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001556 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1557 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001558 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001559 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001560
Chris Lattner4478db92007-11-30 22:53:43 +00001561 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001562 delete Exp;
1563 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001564}
1565
Steve Naroff44e81222008-04-14 22:03:09 +00001566Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff296b74f2007-11-05 14:50:49 +00001567 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1568 // Create a call to sel_registerName("selName").
1569 llvm::SmallVector<Expr*, 8> SelExprs;
1570 QualType argType = Context->getPointerType(Context->CharTy);
1571 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1572 Exp->getSelector().getName().size(),
1573 false, argType, SourceLocation(),
1574 SourceLocation()));
1575 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1576 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001577 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001578 delete Exp;
1579 return SelExp;
1580}
1581
Steve Naroff44e81222008-04-14 22:03:09 +00001582CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001583 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001584 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001585 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001586
1587 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001588 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001589
1590 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001591 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001592 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1593
1594 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001595
Steve Naroff71226032007-10-24 22:48:43 +00001596 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1597}
1598
Steve Naroffc8a92d12007-11-01 13:24:47 +00001599static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1600 const char *&startRef, const char *&endRef) {
1601 while (startBuf < endBuf) {
1602 if (*startBuf == '<')
1603 startRef = startBuf; // mark the start.
1604 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001605 if (startRef && *startRef == '<') {
1606 endRef = startBuf; // mark the end.
1607 return true;
1608 }
1609 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001610 }
1611 startBuf++;
1612 }
1613 return false;
1614}
1615
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001616static void scanToNextArgument(const char *&argRef) {
1617 int angle = 0;
1618 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1619 if (*argRef == '<')
1620 angle++;
1621 else if (*argRef == '>')
1622 angle--;
1623 argRef++;
1624 }
1625 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1626}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001627
Steve Naroff44e81222008-04-14 22:03:09 +00001628bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001629
Ted Kremenek42730c52008-01-07 19:49:32 +00001630 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001631 return true;
1632
Steve Naroffc8a92d12007-11-01 13:24:47 +00001633 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001634 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001635 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001636 return true; // we have "Class <Protocol> *".
1637 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001638 return false;
1639}
1640
Steve Naroffd06c88d2008-07-29 18:15:38 +00001641void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1642 QualType Type = E->getType();
1643 if (needToScanForQualifiers(Type)) {
1644 SourceLocation Loc = E->getLocStart();
1645 const char *startBuf = SM->getCharacterData(Loc);
1646 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1647 const char *startRef = 0, *endRef = 0;
1648 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1649 // Get the locations of the startRef, endRef.
1650 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1651 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1652 // Comment out the protocol references.
1653 InsertText(LessLoc, "/*", 2);
1654 InsertText(GreaterLoc, "*/", 2);
1655 }
1656 }
1657}
1658
Steve Naroff44e81222008-04-14 22:03:09 +00001659void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001660 SourceLocation Loc;
1661 QualType Type;
1662 const FunctionTypeProto *proto = 0;
1663 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1664 Loc = VD->getLocation();
1665 Type = VD->getType();
1666 }
1667 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1668 Loc = FD->getLocation();
1669 // Check for ObjC 'id' and class types that have been adorned with protocol
1670 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1671 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1672 assert(funcType && "missing function type");
1673 proto = dyn_cast<FunctionTypeProto>(funcType);
1674 if (!proto)
1675 return;
1676 Type = proto->getResultType();
1677 }
1678 else
1679 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001680
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001681 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001682 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001683
1684 const char *endBuf = SM->getCharacterData(Loc);
1685 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001686 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001687 startBuf--; // scan backward (from the decl location) for return type.
1688 const char *startRef = 0, *endRef = 0;
1689 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1690 // Get the locations of the startRef, endRef.
1691 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1692 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1693 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001694 InsertText(LessLoc, "/*", 2);
1695 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001696 }
1697 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001698 if (!proto)
1699 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001700 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001701 const char *startBuf = SM->getCharacterData(Loc);
1702 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001703 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1704 if (needToScanForQualifiers(proto->getArgType(i))) {
1705 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001706
Steve Naroffc8a92d12007-11-01 13:24:47 +00001707 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001708 // scan forward (from the decl location) for argument types.
1709 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001710 const char *startRef = 0, *endRef = 0;
1711 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1712 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001713 SourceLocation LessLoc =
1714 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1715 SourceLocation GreaterLoc =
1716 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001717 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001718 InsertText(LessLoc, "/*", 2);
1719 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001720 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001721 startBuf = ++endBuf;
1722 }
1723 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001724 // If the function name is derived from a macro expansion, then the
1725 // argument buffer will not follow the name. Need to speak with Chris.
1726 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001727 startBuf++; // scan forward (from the decl location) for argument types.
1728 startBuf++;
1729 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001730 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001731}
1732
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001733// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001734void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001735 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1736 llvm::SmallVector<QualType, 16> ArgTys;
1737 ArgTys.push_back(Context->getPointerType(
1738 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001739 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001740 &ArgTys[0], ArgTys.size(),
1741 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001742 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001743 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001744 SelGetUidIdent, getFuncType,
1745 FunctionDecl::Extern, false, 0);
1746}
1747
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001748// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001749void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001750 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1751 llvm::SmallVector<QualType, 16> ArgTys;
1752 ArgTys.push_back(Context->getPointerType(
1753 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001754 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001755 &ArgTys[0], ArgTys.size(),
1756 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001757 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001758 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001759 SelGetProtoIdent, getFuncType,
1760 FunctionDecl::Extern, false, 0);
1761}
1762
Steve Naroff44e81222008-04-14 22:03:09 +00001763void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001764 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001765 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001766 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001767 return;
1768 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001769 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001770}
1771
Steve Naroffbec4bf52008-03-11 17:37:02 +00001772// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001773void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001774 if (SuperContructorFunctionDecl)
1775 return;
1776 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1777 llvm::SmallVector<QualType, 16> ArgTys;
1778 QualType argT = Context->getObjCIdType();
1779 assert(!argT.isNull() && "Can't find 'id' type");
1780 ArgTys.push_back(argT);
1781 ArgTys.push_back(argT);
1782 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1783 &ArgTys[0], ArgTys.size(),
1784 false);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001785 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001786 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001787 msgSendIdent, msgSendType,
1788 FunctionDecl::Extern, false, 0);
1789}
1790
Steve Naroff02a82aa2007-10-30 23:14:51 +00001791// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001792void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001793 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1794 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001795 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001796 assert(!argT.isNull() && "Can't find 'id' type");
1797 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001798 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001799 assert(!argT.isNull() && "Can't find 'SEL' type");
1800 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001801 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001802 &ArgTys[0], ArgTys.size(),
1803 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001804 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001805 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001806 msgSendIdent, msgSendType,
1807 FunctionDecl::Extern, false, 0);
1808}
1809
Steve Naroff764c1ae2007-11-15 10:28:18 +00001810// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001811void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001812 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1813 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001814 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001815 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001816 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00001817 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1818 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1819 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001820 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001821 assert(!argT.isNull() && "Can't find 'SEL' type");
1822 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001823 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001824 &ArgTys[0], ArgTys.size(),
1825 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001826 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001827 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001828 msgSendIdent, msgSendType,
1829 FunctionDecl::Extern, false, 0);
1830}
1831
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001832// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001833void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001834 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1835 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001836 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001837 assert(!argT.isNull() && "Can't find 'id' type");
1838 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001839 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001840 assert(!argT.isNull() && "Can't find 'SEL' type");
1841 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001842 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001843 &ArgTys[0], ArgTys.size(),
1844 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001845 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001846 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001847 msgSendIdent, msgSendType,
1848 FunctionDecl::Extern, false, 0);
1849}
1850
1851// SynthMsgSendSuperStretFunctionDecl -
1852// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001853void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001854 IdentifierInfo *msgSendIdent =
1855 &Context->Idents.get("objc_msgSendSuper_stret");
1856 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001857 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001858 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001859 &Context->Idents.get("objc_super"));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001860 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1861 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1862 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001863 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001864 assert(!argT.isNull() && "Can't find 'SEL' type");
1865 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001866 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001867 &ArgTys[0], ArgTys.size(),
1868 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001869 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00001870 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001871 msgSendIdent, msgSendType,
1872 FunctionDecl::Extern, false, 0);
1873}
1874
Steve Naroff31316a12008-05-08 22:02:18 +00001875// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001876void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001877 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1878 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001879 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001880 assert(!argT.isNull() && "Can't find 'id' type");
1881 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001882 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001883 assert(!argT.isNull() && "Can't find 'SEL' type");
1884 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00001885 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001886 &ArgTys[0], ArgTys.size(),
1887 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001888 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001889 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001890 msgSendIdent, msgSendType,
1891 FunctionDecl::Extern, false, 0);
1892}
1893
Steve Naroff02a82aa2007-10-30 23:14:51 +00001894// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001895void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001896 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1897 llvm::SmallVector<QualType, 16> ArgTys;
1898 ArgTys.push_back(Context->getPointerType(
1899 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001900 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001901 &ArgTys[0], ArgTys.size(),
1902 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001903 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001904 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001905 getClassIdent, getClassType,
1906 FunctionDecl::Extern, false, 0);
1907}
1908
Steve Naroff3b1caac2007-12-07 03:50:46 +00001909// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001910void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001911 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1912 llvm::SmallVector<QualType, 16> ArgTys;
1913 ArgTys.push_back(Context->getPointerType(
1914 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001915 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001916 &ArgTys[0], ArgTys.size(),
1917 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001918 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001919 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001920 getClassIdent, getClassType,
1921 FunctionDecl::Extern, false, 0);
1922}
1923
Steve Naroff44e81222008-04-14 22:03:09 +00001924Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001925 QualType strType = getConstantStringStructType();
1926
1927 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00001928
1929 std::string tmpName = InFileName;
1930 unsigned i;
1931 for (i=0; i < tmpName.length(); i++) {
1932 char c = tmpName.at(i);
1933 // replace any non alphanumeric characters with '_'.
1934 if (!isalpha(c) && (c < '0' || c > '9'))
1935 tmpName[i] = '_';
1936 }
1937 S += tmpName;
1938 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001939 S += utostr(NumObjCStringLiterals++);
1940
Steve Narofffef037c2008-03-27 22:29:16 +00001941 Preamble += "static __NSConstantStringImpl " + S;
1942 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1943 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00001944 // The pretty printer for StringLiteral handles escape characters properly.
1945 std::ostringstream prettyBuf;
1946 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00001947 Preamble += prettyBuf.str();
1948 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00001949 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00001950 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001951
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001952 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001953 &Context->Idents.get(S.c_str()), strType,
1954 VarDecl::Static, NULL);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001955 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1956 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1957 Context->getPointerType(DRE->getType()),
1958 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001959 // cast to NSConstantString *
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001960 CastExpr *cast = new ExplicitCastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001961 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001962 delete Exp;
1963 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001964}
1965
Steve Naroff44e81222008-04-14 22:03:09 +00001966ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001967 // check if we are sending a message to 'super'
Chris Lattnere4650482008-03-15 06:12:44 +00001968 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1969
Chris Lattner69909292008-08-10 01:53:14 +00001970 if (PredefinedExpr *PDE = dyn_cast<PredefinedExpr>(recExpr))
1971 if (PDE->getIdentType() == PredefinedExpr::ObjCSuper) {
Chris Lattner4423d372008-06-21 18:04:54 +00001972 const PointerType *PT = PDE->getType()->getAsPointerType();
1973 assert(PT);
1974 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1975 return IT->getDecl();
1976 }
1977 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001978}
1979
1980// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00001981QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001982 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001983 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001984 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001985 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00001986 QualType FieldTypes[2];
1987
1988 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001989 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001990 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001991 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001992 // Create fields
1993 FieldDecl *FieldDecls[2];
1994
1995 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001996 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001997 FieldTypes[i]);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001998
Ted Kremenek46a837c2008-09-05 17:16:31 +00001999 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002000 }
2001 return Context->getTagDeclType(SuperStructDecl);
2002}
2003
Steve Naroff44e81222008-04-14 22:03:09 +00002004QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002005 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002006 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002007 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002008 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroff47e7fa22008-03-15 00:55:56 +00002009 QualType FieldTypes[4];
2010
2011 // struct objc_object *receiver;
2012 FieldTypes[0] = Context->getObjCIdType();
2013 // int flags;
2014 FieldTypes[1] = Context->IntTy;
2015 // char *str;
2016 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2017 // long length;
2018 FieldTypes[3] = Context->LongTy;
2019 // Create fields
Steve Naroff053ae3f2008-03-27 22:59:54 +00002020 FieldDecl *FieldDecls[4];
Steve Naroff47e7fa22008-03-15 00:55:56 +00002021
2022 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002023 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00002024 FieldTypes[i]);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002025
Ted Kremenek46a837c2008-09-05 17:16:31 +00002026 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002027 }
2028 return Context->getTagDeclType(ConstantStringDecl);
2029}
2030
Steve Naroff44e81222008-04-14 22:03:09 +00002031Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00002032 if (!SelGetUidFunctionDecl)
2033 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002034 if (!MsgSendFunctionDecl)
2035 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002036 if (!MsgSendSuperFunctionDecl)
2037 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002038 if (!MsgSendStretFunctionDecl)
2039 SynthMsgSendStretFunctionDecl();
2040 if (!MsgSendSuperStretFunctionDecl)
2041 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002042 if (!MsgSendFpretFunctionDecl)
2043 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002044 if (!GetClassFunctionDecl)
2045 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002046 if (!GetMetaClassFunctionDecl)
2047 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002048
Steve Naroff764c1ae2007-11-15 10:28:18 +00002049 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002050 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2051 // May need to use objc_msgSend_stret() as well.
2052 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00002053 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002054 QualType resultType = mDecl->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00002055 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002056 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00002057 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002058 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002059 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002060
Steve Naroff71226032007-10-24 22:48:43 +00002061 // Synthesize a call to objc_msgSend().
2062 llvm::SmallVector<Expr*, 8> MsgExprs;
2063 IdentifierInfo *clsName = Exp->getClassName();
2064
2065 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2066 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00002067 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2068 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002069 if (!strcmp(clsName->getName(), "super")) {
2070 MsgSendFlavor = MsgSendSuperFunctionDecl;
2071 if (MsgSendStretFlavor)
2072 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2073 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2074
Ted Kremenek42730c52008-01-07 19:49:32 +00002075 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00002076 CurMethodDecl->getClassInterface()->getSuperClass();
2077
2078 llvm::SmallVector<Expr*, 4> InitExprs;
2079
2080 // set the receiver to self, the first argument to all methods.
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002081 InitExprs.push_back(new DeclRefExpr(
2082 CurMethodDecl->getSelfDecl(),
2083 Context->getObjCIdType(),
2084 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002085 llvm::SmallVector<Expr*, 8> ClsExprs;
2086 QualType argType = Context->getPointerType(Context->CharTy);
2087 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2088 SuperDecl->getIdentifier()->getLength(),
2089 false, argType, SourceLocation(),
2090 SourceLocation()));
2091 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2092 &ClsExprs[0],
2093 ClsExprs.size());
2094 // To turn off a warning, type-cast to 'id'
2095 InitExprs.push_back(
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002096 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002097 Cls, SourceLocation())); // set 'super class', using objc_getClass().
2098 // struct objc_super
2099 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002100 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002101
Steve Naroffdee066b2008-03-11 18:14:26 +00002102 if (LangOpts.Microsoft) {
2103 SynthSuperContructorFunctionDecl();
2104 // Simulate a contructor call...
2105 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2106 superType, SourceLocation());
2107 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2108 superType, SourceLocation());
2109 } else {
2110 // (struct objc_super) { <exprs from above> }
2111 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2112 &InitExprs[0], InitExprs.size(),
2113 SourceLocation());
2114 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2115 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00002116 // struct objc_super *
2117 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2118 Context->getPointerType(SuperRep->getType()),
2119 SourceLocation());
2120 MsgExprs.push_back(Unop);
2121 } else {
2122 llvm::SmallVector<Expr*, 8> ClsExprs;
2123 QualType argType = Context->getPointerType(Context->CharTy);
2124 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2125 clsName->getLength(),
2126 false, argType, SourceLocation(),
2127 SourceLocation()));
2128 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2129 &ClsExprs[0],
2130 ClsExprs.size());
2131 MsgExprs.push_back(Cls);
2132 }
Steve Naroff885e2122007-11-14 23:54:14 +00002133 } else { // instance message.
2134 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002135
Ted Kremenek42730c52008-01-07 19:49:32 +00002136 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002137 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002138 if (MsgSendStretFlavor)
2139 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002140 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2141
2142 llvm::SmallVector<Expr*, 4> InitExprs;
2143
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002144 InitExprs.push_back(
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002145 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Naroff23528612008-07-16 22:35:27 +00002146 new DeclRefExpr(CurMethodDecl->getSelfDecl(),
2147 Context->getObjCIdType(),
2148 SourceLocation()),
2149 SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002150
2151 llvm::SmallVector<Expr*, 8> ClsExprs;
2152 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002153 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2154 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002155 false, argType, SourceLocation(),
2156 SourceLocation()));
2157 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002158 &ClsExprs[0],
2159 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002160 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002161 InitExprs.push_back(
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002162 new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002163 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00002164 // struct objc_super
2165 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002166 Expr *SuperRep;
2167
2168 if (LangOpts.Microsoft) {
2169 SynthSuperContructorFunctionDecl();
2170 // Simulate a contructor call...
2171 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2172 superType, SourceLocation());
2173 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2174 superType, SourceLocation());
2175 } else {
2176 // (struct objc_super) { <exprs from above> }
2177 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2178 &InitExprs[0], InitExprs.size(),
2179 SourceLocation());
2180 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2181 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002182 // struct objc_super *
2183 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2184 Context->getPointerType(SuperRep->getType()),
2185 SourceLocation());
2186 MsgExprs.push_back(Unop);
2187 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002188 // Remove all type-casts because it may contain objc-style types; e.g.
2189 // Foo<Proto> *.
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002190 while (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(recExpr))
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002191 recExpr = CE->getSubExpr();
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002192 recExpr = new ExplicitCastExpr(Context->getObjCIdType(), recExpr,
2193 SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002194 MsgExprs.push_back(recExpr);
2195 }
Steve Naroff885e2122007-11-14 23:54:14 +00002196 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002197 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002198 llvm::SmallVector<Expr*, 8> SelExprs;
2199 QualType argType = Context->getPointerType(Context->CharTy);
2200 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2201 Exp->getSelector().getName().size(),
2202 false, argType, SourceLocation(),
2203 SourceLocation()));
2204 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2205 &SelExprs[0], SelExprs.size());
2206 MsgExprs.push_back(SelExp);
2207
2208 // Now push any user supplied arguments.
2209 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002210 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002211 // Make all implicit casts explicit...ICE comes in handy:-)
2212 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2213 // Reuse the ICE type, it is exactly what the doctor ordered.
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002214 userExpr = new ExplicitCastExpr(ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002215 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002216 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002217 }
2218 // Make id<P...> cast into an 'id' cast.
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002219 else if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002220 if (CE->getType()->isObjCQualifiedIdType()) {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002221 while ((CE = dyn_cast<ExplicitCastExpr>(userExpr)))
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002222 userExpr = CE->getSubExpr();
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002223 userExpr = new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002224 userExpr, SourceLocation());
2225 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002226 }
Steve Naroff885e2122007-11-14 23:54:14 +00002227 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002228 // We've transferred the ownership to MsgExprs. Null out the argument in
2229 // the original expression, since we will delete it below.
2230 Exp->setArg(i, 0);
2231 }
Steve Naroff0744c472007-11-04 22:37:50 +00002232 // Generate the funky cast.
2233 CastExpr *cast;
2234 llvm::SmallVector<QualType, 8> ArgTypes;
2235 QualType returnType;
2236
2237 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002238 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2239 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2240 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002241 ArgTypes.push_back(Context->getObjCIdType());
2242 ArgTypes.push_back(Context->getObjCSelType());
2243 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002244 // Push any user argument types.
Chris Lattner685d7922008-03-16 01:07:14 +00002245 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002246 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2247 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002248 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00002249 ArgTypes.push_back(t);
2250 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002251 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2252 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002253 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002254 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002255 }
2256 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002257 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002258
2259 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002260 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2261 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002262
2263 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2264 // If we don't do this cast, we get the following bizarre warning/note:
2265 // xx.m:13: warning: function called through a non-compatible type
2266 // xx.m:13: note: if this code is reached, the program will abort
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002267 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Steve Naroff0744c472007-11-04 22:37:50 +00002268 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002269
Steve Naroff0744c472007-11-04 22:37:50 +00002270 // Now do the "normal" pointer to function cast.
2271 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002272 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002273 // If we don't have a method decl, force a variadic cast.
2274 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroff0744c472007-11-04 22:37:50 +00002275 castType = Context->getPointerType(castType);
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002276 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002277
2278 // Don't forget the parens to enforce the proper binding.
2279 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2280
2281 const FunctionType *FT = msgSendType->getAsFunctionType();
2282 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2283 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002284 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002285 if (MsgSendStretFlavor) {
2286 // We have the method which returns a struct/union. Must also generate
2287 // call to objc_msgSend_stret and hang both varieties on a conditional
2288 // expression which dictate which one to envoke depending on size of
2289 // method's return type.
2290
2291 // Create a reference to the objc_msgSend_stret() declaration.
2292 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2293 SourceLocation());
2294 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002295 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002296 SourceLocation());
2297 // Now do the "normal" pointer to function cast.
2298 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002299 &ArgTypes[0], ArgTypes.size(),
2300 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002301 castType = Context->getPointerType(castType);
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002302 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002303
2304 // Don't forget the parens to enforce the proper binding.
2305 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2306
2307 FT = msgSendType->getAsFunctionType();
2308 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2309 FT->getResultType(), SourceLocation());
2310
2311 // Build sizeof(returnType)
2312 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2313 returnType, Context->getSizeType(),
2314 SourceLocation(), SourceLocation());
2315 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2316 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2317 // For X86 it is more complicated and some kind of target specific routine
2318 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002319 unsigned IntSize =
2320 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002321 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2322 Context->IntTy,
2323 SourceLocation());
2324 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2325 BinaryOperator::LE,
2326 Context->IntTy,
2327 SourceLocation());
2328 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2329 ConditionalOperator *CondExpr =
2330 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002331 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002332 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002333 return ReplacingStmt;
2334}
2335
Steve Naroff44e81222008-04-14 22:03:09 +00002336Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002337 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002338 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002339 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002340
Chris Lattner0021f452007-10-24 16:57:36 +00002341 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002342 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002343}
2344
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002345/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2346/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002347Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002348 if (!GetProtocolFunctionDecl)
2349 SynthGetProtocolFunctionDecl();
2350 // Create a call to objc_getProtocol("ProtocolName").
2351 llvm::SmallVector<Expr*, 8> ProtoExprs;
2352 QualType argType = Context->getPointerType(Context->CharTy);
2353 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2354 strlen(Exp->getProtocol()->getName()),
2355 false, argType, SourceLocation(),
2356 SourceLocation()));
2357 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2358 &ProtoExprs[0],
2359 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002360 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002361 delete Exp;
2362 return ProtoExp;
2363
2364}
2365
Steve Naroffef82b742008-05-31 14:15:04 +00002366bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2367 const char *endBuf) {
2368 while (startBuf < endBuf) {
2369 if (*startBuf == '#') {
2370 // Skip whitespace.
2371 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2372 ;
2373 if (!strncmp(startBuf, "if", strlen("if")) ||
2374 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2375 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2376 !strncmp(startBuf, "define", strlen("define")) ||
2377 !strncmp(startBuf, "undef", strlen("undef")) ||
2378 !strncmp(startBuf, "else", strlen("else")) ||
2379 !strncmp(startBuf, "elif", strlen("elif")) ||
2380 !strncmp(startBuf, "endif", strlen("endif")) ||
2381 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2382 !strncmp(startBuf, "include", strlen("include")) ||
2383 !strncmp(startBuf, "import", strlen("import")) ||
2384 !strncmp(startBuf, "include_next", strlen("include_next")))
2385 return true;
2386 }
2387 startBuf++;
2388 }
2389 return false;
2390}
2391
Ted Kremenek42730c52008-01-07 19:49:32 +00002392/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002393/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002394void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002395 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002396 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2397 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002398 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002399 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002400 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002401 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002402 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002403 SourceLocation LocStart = CDecl->getLocStart();
2404 SourceLocation LocEnd = CDecl->getLocEnd();
2405
2406 const char *startBuf = SM->getCharacterData(LocStart);
2407 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002408
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002409 // If no ivars and no root or if its root, directly or indirectly,
2410 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002411 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2412 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002413 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002414 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002415 return;
2416 }
2417
2418 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002419 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002420 Result += "\nstruct ";
2421 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002422 if (LangOpts.Microsoft)
2423 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002424
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002425 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002426 const char *cursor = strchr(startBuf, '{');
2427 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002428 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002429 // If the buffer contains preprocessor directives, we do more fine-grained
2430 // rewrites. This is intended to fix code that looks like (which occurs in
2431 // NSURL.h, for example):
2432 //
2433 // #ifdef XYZ
2434 // @interface Foo : NSObject
2435 // #else
2436 // @interface FooBar : NSObject
2437 // #endif
2438 // {
2439 // int i;
2440 // }
2441 // @end
2442 //
2443 // This clause is segregated to avoid breaking the common case.
2444 if (BufferContainsPPDirectives(startBuf, cursor)) {
2445 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2446 CDecl->getClassLoc();
2447 const char *endHeader = SM->getCharacterData(L);
2448 endHeader += Lexer::MeasureTokenLength(L, *SM);
2449
Chris Lattner8bcb5252008-07-21 18:19:38 +00002450 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002451 // advance to the end of the referenced protocols.
2452 while (endHeader < cursor && *endHeader != '>') endHeader++;
2453 endHeader++;
2454 }
2455 // rewrite the original header
2456 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2457 } else {
2458 // rewrite the original header *without* disturbing the '{'
2459 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2460 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002461 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002462 Result = "\n struct ";
2463 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002464 Result += "_IMPL ";
2465 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002466 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002467
2468 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002469 SourceLocation OnePastCurly =
2470 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2471 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002472 }
2473 cursor++; // past '{'
2474
2475 // Now comment out any visibility specifiers.
2476 while (cursor < endBuf) {
2477 if (*cursor == '@') {
2478 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002479 // Skip whitespace.
2480 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2481 /*scan*/;
2482
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002483 // FIXME: presence of @public, etc. inside comment results in
2484 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002485 if (!strncmp(cursor, "public", strlen("public")) ||
2486 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002487 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002488 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002489 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002490 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002491 // FIXME: If there are cases where '<' is used in ivar declaration part
2492 // of user code, then scan the ivar list and use needToScanForQualifiers
2493 // for type checking.
2494 else if (*cursor == '<') {
2495 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002496 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002497 cursor = strchr(cursor, '>');
2498 cursor++;
2499 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002500 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002501 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002502 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002503 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002504 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002505 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002506 } else { // we don't have any instance variables - insert super struct.
2507 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2508 Result += " {\n struct ";
2509 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002510 Result += "_IMPL ";
2511 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002512 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002513 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002514 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002515 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002516 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002517 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002518}
2519
Ted Kremenek42730c52008-01-07 19:49:32 +00002520// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002521/// class methods.
Steve Naroff44e81222008-04-14 22:03:09 +00002522void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002523 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002524 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002525 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002526 const char *ClassName,
2527 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002528 if (MethodBegin == MethodEnd) return;
2529
Fariborz Jahanian04455192007-10-22 21:41:37 +00002530 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002531 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002532 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002533 SEL _cmd;
2534 char *method_types;
2535 void *_imp;
2536 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002537 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002538 Result += "\nstruct _objc_method {\n";
2539 Result += "\tSEL _cmd;\n";
2540 Result += "\tchar *method_types;\n";
2541 Result += "\tvoid *_imp;\n";
2542 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002543
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002544 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002545 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002546
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002547 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002548
2549 /* struct {
2550 struct _objc_method_list *next_method;
2551 int method_count;
2552 struct _objc_method method_list[];
2553 }
2554 */
2555 Result += "\nstatic struct {\n";
2556 Result += "\tstruct _objc_method_list *next_method;\n";
2557 Result += "\tint method_count;\n";
2558 Result += "\tstruct _objc_method method_list[";
2559 Result += utostr(MethodEnd-MethodBegin);
2560 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002561 Result += prefix;
2562 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2563 Result += "_METHODS_";
2564 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002565 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002566 Result += IsInstanceMethod ? "inst" : "cls";
2567 Result += "_meth\")))= ";
2568 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002569
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002570 Result += "\t,{{(SEL)\"";
2571 Result += (*MethodBegin)->getSelector().getName().c_str();
2572 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002573 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002574 Result += "\", \"";
2575 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002576 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002577 Result += MethodInternalNames[*MethodBegin];
2578 Result += "}\n";
2579 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2580 Result += "\t ,{(SEL)\"";
2581 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002582 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002583 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002584 Result += "\", \"";
2585 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002586 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002587 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002588 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002589 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002590 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002591}
2592
Ted Kremenek42730c52008-01-07 19:49:32 +00002593/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002594void RewriteObjC::
2595RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2596 const char *prefix,
2597 const char *ClassName,
2598 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002599 static bool objc_protocol_methods = false;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002600 if (Protocols.empty()) return;
2601
2602 for (unsigned i = 0; i != Protocols.size(); i++) {
2603 ObjCProtocolDecl *PDecl = Protocols[i];
2604 // Output struct protocol_methods holder of method selector and type.
2605 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2606 /* struct protocol_methods {
2607 SEL _cmd;
2608 char *method_types;
2609 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002610 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002611 Result += "\nstruct protocol_methods {\n";
2612 Result += "\tSEL _cmd;\n";
2613 Result += "\tchar *method_types;\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002614 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002615
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002616 objc_protocol_methods = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002617 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002618 // Do not synthesize the protocol more than once.
2619 if (ObjCSynthesizedProtocols.count(PDecl))
2620 continue;
2621
2622 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2623 unsigned NumMethods = PDecl->getNumInstanceMethods();
2624 /* struct _objc_protocol_method_list {
2625 int protocol_method_count;
2626 struct protocol_methods protocols[];
2627 }
2628 */
2629 Result += "\nstatic struct {\n";
2630 Result += "\tint protocol_method_count;\n";
2631 Result += "\tstruct protocol_methods protocols[";
2632 Result += utostr(NumMethods);
2633 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2634 Result += PDecl->getName();
2635 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2636 "{\n\t" + utostr(NumMethods) + "\n";
2637
2638 // Output instance methods declared in this protocol.
2639 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2640 E = PDecl->instmeth_end(); I != E; ++I) {
2641 if (I == PDecl->instmeth_begin())
2642 Result += "\t ,{{(SEL)\"";
2643 else
2644 Result += "\t ,{(SEL)\"";
2645 Result += (*I)->getSelector().getName().c_str();
2646 std::string MethodTypeString;
2647 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2648 Result += "\", \"";
2649 Result += MethodTypeString;
2650 Result += "\"}\n";
2651 }
2652 Result += "\t }\n};\n";
2653 }
2654
2655 // Output class methods declared in this protocol.
2656 int NumMethods = PDecl->getNumClassMethods();
2657 if (NumMethods > 0) {
2658 /* struct _objc_protocol_method_list {
2659 int protocol_method_count;
2660 struct protocol_methods protocols[];
2661 }
2662 */
2663 Result += "\nstatic struct {\n";
2664 Result += "\tint protocol_method_count;\n";
2665 Result += "\tstruct protocol_methods protocols[";
2666 Result += utostr(NumMethods);
2667 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2668 Result += PDecl->getName();
2669 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2670 "{\n\t";
2671 Result += utostr(NumMethods);
2672 Result += "\n";
2673
2674 // Output instance methods declared in this protocol.
2675 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2676 E = PDecl->classmeth_end(); I != E; ++I) {
2677 if (I == PDecl->classmeth_begin())
2678 Result += "\t ,{{(SEL)\"";
2679 else
2680 Result += "\t ,{(SEL)\"";
2681 Result += (*I)->getSelector().getName().c_str();
2682 std::string MethodTypeString;
2683 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2684 Result += "\", \"";
2685 Result += MethodTypeString;
2686 Result += "\"}\n";
2687 }
2688 Result += "\t }\n};\n";
2689 }
2690
2691 // Output:
2692 /* struct _objc_protocol {
2693 // Objective-C 1.0 extensions
2694 struct _objc_protocol_extension *isa;
2695 char *protocol_name;
2696 struct _objc_protocol **protocol_list;
2697 struct _objc_protocol_method_list *instance_methods;
2698 struct _objc_protocol_method_list *class_methods;
2699 };
Steve Naroff27429432008-03-12 01:06:30 +00002700 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002701 static bool objc_protocol = false;
2702 if (!objc_protocol) {
2703 Result += "\nstruct _objc_protocol {\n";
2704 Result += "\tstruct _objc_protocol_extension *isa;\n";
2705 Result += "\tchar *protocol_name;\n";
2706 Result += "\tstruct _objc_protocol **protocol_list;\n";
2707 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2708 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2709 Result += "};\n";
2710
2711 objc_protocol = true;
2712 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002713
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002714 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2715 Result += PDecl->getName();
2716 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2717 "{\n\t0, \"";
2718 Result += PDecl->getName();
2719 Result += "\", 0, ";
2720 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2721 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2722 Result += PDecl->getName();
2723 Result += ", ";
2724 }
2725 else
2726 Result += "0, ";
2727 if (PDecl->getNumClassMethods() > 0) {
2728 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2729 Result += PDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002730 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002731 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002732 else
2733 Result += "0\n";
2734 Result += "};\n";
2735
2736 // Mark this protocol as having been generated.
2737 if (!ObjCSynthesizedProtocols.insert(PDecl))
2738 assert(false && "protocol already synthesized");
2739 }
2740 // Output the top lovel protocol meta-data for the class.
2741 /* struct _objc_protocol_list {
2742 struct _objc_protocol_list *next;
2743 int protocol_count;
2744 struct _objc_protocol *class_protocols[];
2745 }
2746 */
2747 Result += "\nstatic struct {\n";
2748 Result += "\tstruct _objc_protocol_list *next;\n";
2749 Result += "\tint protocol_count;\n";
2750 Result += "\tstruct _objc_protocol *class_protocols[";
2751 Result += utostr(Protocols.size());
2752 Result += "];\n} _OBJC_";
2753 Result += prefix;
2754 Result += "_PROTOCOLS_";
2755 Result += ClassName;
2756 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2757 "{\n\t0, ";
2758 Result += utostr(Protocols.size());
2759 Result += "\n";
2760
2761 Result += "\t,{&_OBJC_PROTOCOL_";
2762 Result += Protocols[0]->getName();
2763 Result += " \n";
2764
2765 for (unsigned i = 1; i != Protocols.size(); i++) {
2766 Result += "\t ,&_OBJC_PROTOCOL_";
2767 Result += Protocols[i]->getName();
2768 Result += "\n";
2769 }
2770 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002771}
2772
Ted Kremenek42730c52008-01-07 19:49:32 +00002773/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002774/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00002775void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002776 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002777 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002778 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002779 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002780 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2781 CDecl = CDecl->getNextClassCategory())
2782 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2783 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002784
Chris Lattnera661a4d2007-12-23 01:40:15 +00002785 std::string FullCategoryName = ClassDecl->getName();
2786 FullCategoryName += '_';
2787 FullCategoryName += IDecl->getName();
2788
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002789 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002790 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002791 true, "CATEGORY_", FullCategoryName.c_str(),
2792 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002793
2794 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002795 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002796 false, "CATEGORY_", FullCategoryName.c_str(),
2797 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002798
2799 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002800 // Null CDecl is case of a category implementation with no category interface
2801 if (CDecl)
Chris Lattner0be08822008-07-21 21:32:27 +00002802 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002803 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002804
2805 /* struct _objc_category {
2806 char *category_name;
2807 char *class_name;
2808 struct _objc_method_list *instance_methods;
2809 struct _objc_method_list *class_methods;
2810 struct _objc_protocol_list *protocols;
2811 // Objective-C 1.0 extensions
2812 uint32_t size; // sizeof (struct _objc_category)
2813 struct _objc_property_list *instance_properties; // category's own
2814 // @property decl.
2815 };
2816 */
2817
2818 static bool objc_category = false;
2819 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002820 Result += "\nstruct _objc_category {\n";
2821 Result += "\tchar *category_name;\n";
2822 Result += "\tchar *class_name;\n";
2823 Result += "\tstruct _objc_method_list *instance_methods;\n";
2824 Result += "\tstruct _objc_method_list *class_methods;\n";
2825 Result += "\tstruct _objc_protocol_list *protocols;\n";
2826 Result += "\tunsigned int size;\n";
2827 Result += "\tstruct _objc_property_list *instance_properties;\n";
2828 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002829 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002830 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002831 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2832 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002833 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002834 Result += IDecl->getName();
2835 Result += "\"\n\t, \"";
2836 Result += ClassDecl->getName();
2837 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002838
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002839 if (IDecl->getNumInstanceMethods() > 0) {
2840 Result += "\t, (struct _objc_method_list *)"
2841 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2842 Result += FullCategoryName;
2843 Result += "\n";
2844 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002845 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002846 Result += "\t, 0\n";
2847 if (IDecl->getNumClassMethods() > 0) {
2848 Result += "\t, (struct _objc_method_list *)"
2849 "&_OBJC_CATEGORY_CLASS_METHODS_";
2850 Result += FullCategoryName;
2851 Result += "\n";
2852 }
2853 else
2854 Result += "\t, 0\n";
2855
Chris Lattner0be08822008-07-21 21:32:27 +00002856 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002857 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2858 Result += FullCategoryName;
2859 Result += "\n";
2860 }
2861 else
2862 Result += "\t, 0\n";
2863 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002864}
2865
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002866/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2867/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00002868void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00002869 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002870 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00002871 if (ivar->isBitField()) {
2872 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2873 // place all bitfields at offset 0.
2874 Result += "0";
2875 } else {
2876 Result += "__OFFSETOFIVAR__(struct ";
2877 Result += IDecl->getName();
2878 if (LangOpts.Microsoft)
2879 Result += "_IMPL";
2880 Result += ", ";
2881 Result += ivar->getName();
2882 Result += ")";
2883 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002884}
2885
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002886//===----------------------------------------------------------------------===//
2887// Meta Data Emission
2888//===----------------------------------------------------------------------===//
2889
Steve Naroff44e81222008-04-14 22:03:09 +00002890void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002891 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002892 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002893
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002894 // Explictly declared @interface's are already synthesized.
2895 if (CDecl->ImplicitInterfaceDecl()) {
2896 // FIXME: Implementation of a class with no @interface (legacy) doese not
2897 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002898 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002899 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002900
Chris Lattnerc7b06752007-12-12 07:56:42 +00002901 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00002902 unsigned NumIvars = !IDecl->ivar_empty()
2903 ? IDecl->ivar_size()
2904 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002905 if (NumIvars > 0) {
2906 static bool objc_ivar = false;
2907 if (!objc_ivar) {
2908 /* struct _objc_ivar {
2909 char *ivar_name;
2910 char *ivar_type;
2911 int ivar_offset;
2912 };
2913 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002914 Result += "\nstruct _objc_ivar {\n";
2915 Result += "\tchar *ivar_name;\n";
2916 Result += "\tchar *ivar_type;\n";
2917 Result += "\tint ivar_offset;\n";
2918 Result += "};\n";
2919
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002920 objc_ivar = true;
2921 }
2922
Steve Naroffc723eec2008-03-11 00:12:29 +00002923 /* struct {
2924 int ivar_count;
2925 struct _objc_ivar ivar_list[nIvars];
2926 };
2927 */
2928 Result += "\nstatic struct {\n";
2929 Result += "\tint ivar_count;\n";
2930 Result += "\tstruct _objc_ivar ivar_list[";
2931 Result += utostr(NumIvars);
2932 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002933 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002934 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002935 "{\n\t";
2936 Result += utostr(NumIvars);
2937 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002938
Ted Kremenek42730c52008-01-07 19:49:32 +00002939 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00002940 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00002941 IVI = IDecl->ivar_begin();
2942 IVE = IDecl->ivar_end();
2943 } else {
2944 IVI = CDecl->ivar_begin();
2945 IVE = CDecl->ivar_end();
2946 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002947 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002948 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002949 Result += "\", \"";
2950 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002951 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2952 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002953 Result += StrEncoding;
2954 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002955 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002956 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002957 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002958 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002959 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002960 Result += "\", \"";
2961 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002962 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2963 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002964 Result += StrEncoding;
2965 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002966 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002967 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002968 }
2969
2970 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002971 }
2972
2973 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002974 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002975 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002976
2977 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002978 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002979 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002980
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002981 // Protocols referenced in class declaration?
Chris Lattner0be08822008-07-21 21:32:27 +00002982 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002983 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002984
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002985
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002986 // Declaration of class/meta-class metadata
2987 /* struct _objc_class {
2988 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002989 const char *super_class_name;
2990 char *name;
2991 long version;
2992 long info;
2993 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002994 struct _objc_ivar_list *ivars;
2995 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002996 struct objc_cache *cache;
2997 struct objc_protocol_list *protocols;
2998 const char *ivar_layout;
2999 struct _objc_class_ext *ext;
3000 };
3001 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003002 static bool objc_class = false;
3003 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003004 Result += "\nstruct _objc_class {\n";
3005 Result += "\tstruct _objc_class *isa;\n";
3006 Result += "\tconst char *super_class_name;\n";
3007 Result += "\tchar *name;\n";
3008 Result += "\tlong version;\n";
3009 Result += "\tlong info;\n";
3010 Result += "\tlong instance_size;\n";
3011 Result += "\tstruct _objc_ivar_list *ivars;\n";
3012 Result += "\tstruct _objc_method_list *methods;\n";
3013 Result += "\tstruct objc_cache *cache;\n";
3014 Result += "\tstruct _objc_protocol_list *protocols;\n";
3015 Result += "\tconst char *ivar_layout;\n";
3016 Result += "\tstruct _objc_class_ext *ext;\n";
3017 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003018 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003019 }
3020
3021 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003022 ObjCInterfaceDecl *RootClass = 0;
3023 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003024 while (SuperClass) {
3025 RootClass = SuperClass;
3026 SuperClass = SuperClass->getSuperClass();
3027 }
3028 SuperClass = CDecl->getSuperClass();
3029
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003030 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3031 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003032 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003033 "{\n\t(struct _objc_class *)\"";
3034 Result += (RootClass ? RootClass->getName() : CDecl->getName());
3035 Result += "\"";
3036
3037 if (SuperClass) {
3038 Result += ", \"";
3039 Result += SuperClass->getName();
3040 Result += "\", \"";
3041 Result += CDecl->getName();
3042 Result += "\"";
3043 }
3044 else {
3045 Result += ", 0, \"";
3046 Result += CDecl->getName();
3047 Result += "\"";
3048 }
Ted Kremenek42730c52008-01-07 19:49:32 +00003049 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003050 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003051 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00003052 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003053 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00003054 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003055 Result += "\n";
3056 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003057 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003058 Result += ", 0\n";
Chris Lattner8bcb5252008-07-21 18:19:38 +00003059 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff27429432008-03-12 01:06:30 +00003060 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003061 Result += CDecl->getName();
3062 Result += ",0,0\n";
3063 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003064 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003065 Result += "\t,0,0,0,0\n";
3066 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003067
3068 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003069 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3070 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003071 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003072 "{\n\t&_OBJC_METACLASS_";
3073 Result += CDecl->getName();
3074 if (SuperClass) {
3075 Result += ", \"";
3076 Result += SuperClass->getName();
3077 Result += "\", \"";
3078 Result += CDecl->getName();
3079 Result += "\"";
3080 }
3081 else {
3082 Result += ", 0, \"";
3083 Result += CDecl->getName();
3084 Result += "\"";
3085 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003086 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003087 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003088 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003089 Result += ",0";
3090 else {
3091 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003092 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003093 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003094 if (LangOpts.Microsoft)
3095 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003096 Result += ")";
3097 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003098 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003099 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003100 Result += CDecl->getName();
3101 Result += "\n\t";
3102 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003103 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003104 Result += ",0";
3105 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003106 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003107 Result += CDecl->getName();
3108 Result += ", 0\n\t";
3109 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003110 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003111 Result += ",0,0";
Chris Lattner8bcb5252008-07-21 18:19:38 +00003112 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff27429432008-03-12 01:06:30 +00003113 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003114 Result += CDecl->getName();
3115 Result += ", 0,0\n";
3116 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003117 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003118 Result += ",0,0,0\n";
3119 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003120}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003121
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003122/// RewriteImplementations - This routine rewrites all method implementations
3123/// and emits meta-data.
3124
Steve Naroff44e81222008-04-14 22:03:09 +00003125void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003126 int ClsDefCount = ClassImplementation.size();
3127 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003128
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003129 if (ClsDefCount == 0 && CatDefCount == 0)
3130 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003131 // Rewrite implemented methods
3132 for (int i = 0; i < ClsDefCount; i++)
3133 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003134
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003135 for (int i = 0; i < CatDefCount; i++)
3136 RewriteImplementationDecl(CategoryImplementation[i]);
3137
Steve Naroff5bf10222008-05-07 21:23:49 +00003138 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003139 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003140 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003141 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003142 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003143
3144 // For each implemented category, write out all its meta data.
3145 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003146 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003147
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003148 // Write objc_symtab metadata
3149 /*
3150 struct _objc_symtab
3151 {
3152 long sel_ref_cnt;
3153 SEL *refs;
3154 short cls_def_cnt;
3155 short cat_def_cnt;
3156 void *defs[cls_def_cnt + cat_def_cnt];
3157 };
3158 */
3159
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003160 Result += "\nstruct _objc_symtab {\n";
3161 Result += "\tlong sel_ref_cnt;\n";
3162 Result += "\tSEL *refs;\n";
3163 Result += "\tshort cls_def_cnt;\n";
3164 Result += "\tshort cat_def_cnt;\n";
3165 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3166 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003167
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003168 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003169 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003170 Result += "\t0, 0, " + utostr(ClsDefCount)
3171 + ", " + utostr(CatDefCount) + "\n";
3172 for (int i = 0; i < ClsDefCount; i++) {
3173 Result += "\t,&_OBJC_CLASS_";
3174 Result += ClassImplementation[i]->getName();
3175 Result += "\n";
3176 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003177
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003178 for (int i = 0; i < CatDefCount; i++) {
3179 Result += "\t,&_OBJC_CATEGORY_";
3180 Result += CategoryImplementation[i]->getClassInterface()->getName();
3181 Result += "_";
3182 Result += CategoryImplementation[i]->getName();
3183 Result += "\n";
3184 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003185
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003186 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003187
3188 // Write objc_module metadata
3189
3190 /*
3191 struct _objc_module {
3192 long version;
3193 long size;
3194 const char *name;
3195 struct _objc_symtab *symtab;
3196 }
3197 */
3198
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003199 Result += "\nstruct _objc_module {\n";
3200 Result += "\tlong version;\n";
3201 Result += "\tlong size;\n";
3202 Result += "\tconst char *name;\n";
3203 Result += "\tstruct _objc_symtab *symtab;\n";
3204 Result += "};\n\n";
3205 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003206 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003207 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3208 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003209 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003210
3211 if (LangOpts.Microsoft) {
3212 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003213 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003214 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3215 Result += "&_OBJC_MODULES;\n";
3216 Result += "#pragma data_seg(pop)\n\n";
3217 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003218}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003219
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003220
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003221
3222