blob: 408860e7e7b754f1e4748a05dfc16e277d35b398 [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);
Steve Naroff44e81222008-04-14 22:03:09 +0000111 ~RewriteObjC();
Chris Lattnerb1548372008-01-31 19:37:57 +0000112
113 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattner6216f292008-01-31 19:42:41 +0000114 // If replacement succeeded or warning disabled return with no warning.
115 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerb1548372008-01-31 19:37:57 +0000116 return;
117
Chris Lattnerb1548372008-01-31 19:37:57 +0000118 SourceRange Range = Old->getSourceRange();
119 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
120 0, 0, &Range, 1);
121 }
122
Steve Narofffef037c2008-03-27 22:29:16 +0000123 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
124 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000125 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000126 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000127 SilenceRewriteMacroWarning)
128 return;
129
130 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
131 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000132
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000133 void RemoveText(SourceLocation Loc, unsigned StrLen) {
134 // If removal succeeded or warning disabled return with no warning.
135 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
136 return;
137
138 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
139 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000140
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000141 void ReplaceText(SourceLocation Start, unsigned OrigLength,
142 const char *NewStr, unsigned NewLength) {
143 // If removal succeeded or warning disabled return with no warning.
144 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
145 SilenceRewriteMacroWarning)
146 return;
147
148 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
149 }
150
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000151 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000152 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000153 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000154 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000155 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
156 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000157 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000158 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
159 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
160 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
161 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
162 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattnercffe3662008-03-16 21:23:50 +0000163 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000164 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000165 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000166 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000167 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000168 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000169 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000170 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000171 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000172
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000173 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000174 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000175 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000176 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff296b74f2007-11-05 14:50:49 +0000177 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000178 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000179 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000180 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000181 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000182 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000183 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
184 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
185 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000186 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
187 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000188 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
189 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000190 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000191 Stmt *RewriteBreakStmt(BreakStmt *S);
192 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000193 void SynthCountByEnumWithState(std::string &buf);
194
Steve Naroff02a82aa2007-10-30 23:14:51 +0000195 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000196 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000197 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000198 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000199 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000200 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000201 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000202 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000203 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000204 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000205
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000206 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000207 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000208 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000209
Ted Kremenek42730c52008-01-07 19:49:32 +0000210 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
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 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
214 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000215 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000216 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000217 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000218 const char *ClassName,
219 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000220
Chris Lattner0be08822008-07-21 21:32:27 +0000221 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
222 &Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000223 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000224 const char *ClassName,
225 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000226 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000227 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000228 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
229 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000230 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000231 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000232 };
233}
234
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000235static bool IsHeaderFile(const std::string &Filename) {
236 std::string::size_type DotPos = Filename.rfind('.');
237
238 if (DotPos == std::string::npos) {
239 // no file extension
240 return false;
241 }
242
243 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
244 // C header: .h
245 // C++ header: .hh or .H;
246 return Ext == "h" || Ext == "hh" || Ext == "H";
247}
248
Steve Naroff44e81222008-04-14 22:03:09 +0000249RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000250 Diagnostic &D, const LangOptions &LOpts)
251 : Diags(D), LangOpts(LOpts) {
252 IsHeader = IsHeaderFile(inFile);
253 InFileName = inFile;
254 OutFileName = outFile;
255 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
256 "rewriting sub-expression within a macro (may not be correct)");
257}
258
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000259ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000260 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000261 Diagnostic &Diags,
262 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000263 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000264}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000265
Steve Naroff44e81222008-04-14 22:03:09 +0000266void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000267 Context = &context;
268 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000269 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000270 MsgSendFunctionDecl = 0;
271 MsgSendSuperFunctionDecl = 0;
272 MsgSendStretFunctionDecl = 0;
273 MsgSendSuperStretFunctionDecl = 0;
274 MsgSendFpretFunctionDecl = 0;
275 GetClassFunctionDecl = 0;
276 GetMetaClassFunctionDecl = 0;
277 SelGetUidFunctionDecl = 0;
278 CFStringFunctionDecl = 0;
279 GetProtocolFunctionDecl = 0;
280 ConstantStringClassReference = 0;
281 NSStringRecord = 0;
282 CurMethodDecl = 0;
283 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000284 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000285 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000286 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000287 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000288
289 // Get the ID and start/end of the main file.
290 MainFileID = SM->getMainFileID();
291 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
292 MainFileStart = MainBuf->getBufferStart();
293 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000294
Chris Lattner12499682008-01-31 19:38:44 +0000295 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000296
Chris Lattner12499682008-01-31 19:38:44 +0000297 // declaring objc_selector outside the parameter list removes a silly
298 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000299 if (IsHeader)
300 Preamble = "#pragma once\n";
301 Preamble += "struct objc_selector; struct objc_class;\n";
302 Preamble += "#ifndef OBJC_SUPER\n";
303 Preamble += "struct objc_super { struct objc_object *object; ";
304 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000305 if (LangOpts.Microsoft) {
306 // Add a constructor for creating temporary objects.
Steve Narofffef037c2008-03-27 22:29:16 +0000307 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
308 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000309 }
Steve Narofffef037c2008-03-27 22:29:16 +0000310 Preamble += "};\n";
311 Preamble += "#define OBJC_SUPER\n";
312 Preamble += "#endif\n";
313 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
314 Preamble += "typedef struct objc_object Protocol;\n";
315 Preamble += "#define _REWRITER_typedef_Protocol\n";
316 Preamble += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000317 if (LangOpts.Microsoft)
Steve Naroff618c6a42008-05-06 22:45:19 +0000318 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
319 else
320 Preamble += "#define __OBJC_RW_EXTERN extern\n";
321 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000322 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000323 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000324 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000325 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000326 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000327 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000328 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff31316a12008-05-08 22:02:18 +0000329 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000330 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroffa9636222008-05-08 17:52:16 +0000331 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000332 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000333 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000334 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000335 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
336 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
337 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
338 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
339 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000340 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000341 // @synchronized hooks.
342 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
343 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000344 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000345 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
346 Preamble += "struct __objcFastEnumerationState {\n\t";
347 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000348 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000349 Preamble += "unsigned long *mutationsPtr;\n\t";
350 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff37157242008-06-02 20:23:21 +0000351 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000352 Preamble += "#define __FASTENUMERATIONSTATE\n";
353 Preamble += "#endif\n";
354 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
355 Preamble += "struct __NSConstantStringImpl {\n";
356 Preamble += " int *isa;\n";
357 Preamble += " int flags;\n";
358 Preamble += " char *str;\n";
359 Preamble += " long length;\n";
360 Preamble += "};\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000361 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
362 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
363 Preamble += "#else\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000364 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000365 Preamble += "#endif\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000366 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
367 Preamble += "#endif\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000368 if (LangOpts.Microsoft) {
369 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000370 Preamble += "#define __attribute__(X)\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000371 }
Chris Lattner12499682008-01-31 19:38:44 +0000372}
373
374
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000375//===----------------------------------------------------------------------===//
376// Top Level Driver Code
377//===----------------------------------------------------------------------===//
378
Steve Naroff44e81222008-04-14 22:03:09 +0000379void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000380 // Two cases: either the decl could be in the main file, or it could be in a
381 // #included file. If the former, rewrite it now. If the later, check to see
382 // if we rewrote the #include/#import.
383 SourceLocation Loc = D->getLocation();
384 Loc = SM->getLogicalLoc(Loc);
385
386 // If this is for a builtin, ignore it.
387 if (Loc.isInvalid()) return;
388
Steve Naroffe9780582007-10-23 23:50:29 +0000389 // Look for built-in declarations that we need to refer during the rewrite.
390 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000391 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000392 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000393 // declared in <Foundation/NSString.h>
394 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
395 ConstantStringClassReference = FVD;
396 return;
397 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000398 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000399 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000400 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000401 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000402 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000403 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000404 } else if (ObjCForwardProtocolDecl *FP =
405 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000406 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000407 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000408 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000409 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000410 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000411}
412
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000413/// HandleDeclInMainFile - This is called for each top-level decl defined in the
414/// main file of the input.
Steve Naroff44e81222008-04-14 22:03:09 +0000415void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000416 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
417 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000418 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000419
Ted Kremenek42730c52008-01-07 19:49:32 +0000420 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000421 if (Stmt *Body = MD->getBody()) {
422 //Body->dump();
423 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000424 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000425 CurMethodDecl = 0;
426 }
Steve Naroff18c83382007-11-13 23:01:27 +0000427 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000428 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000429 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000430 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000431 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000432 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000433 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000434 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000435 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000436 if (VD->getInit())
437 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
438 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000439 // Nothing yet.
440}
441
Steve Naroff44e81222008-04-14 22:03:09 +0000442RewriteObjC::~RewriteObjC() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000443 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000444
445 // Rewrite tabs if we care.
446 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000447
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000448 if (Diags.hasErrorOccurred())
449 return;
450
451 // Create the output file.
452
453 std::ostream *OutFile;
454 if (OutFileName == "-") {
455 OutFile = llvm::cout.stream();
456 } else if (!OutFileName.empty()) {
457 OutFile = new std::ofstream(OutFileName.c_str(),
458 std::ios_base::binary|std::ios_base::out);
459 } else if (InFileName == "-") {
460 OutFile = llvm::cout.stream();
461 } else {
462 llvm::sys::Path Path(InFileName);
463 Path.eraseSuffix();
464 Path.appendSuffix("cpp");
465 OutFile = new std::ofstream(Path.toString().c_str(),
466 std::ios_base::binary|std::ios_base::out);
467 }
468
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000469 RewriteInclude();
470
Steve Narofffef037c2008-03-27 22:29:16 +0000471 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
472 Preamble.c_str(), Preamble.size(), false);
473
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000474 // Rewrite Objective-c meta data*
475 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000476 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000477
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000478 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
479 // we are done.
480 if (const RewriteBuffer *RewriteBuf =
481 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000482 //printf("Changed:\n");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000483 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000484 } else {
Chris Lattner673f2bd2008-03-22 00:08:40 +0000485 fprintf(stderr, "No changes\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000486 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000487 // Emit metadata.
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000488 *OutFile << ResultStr;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000489}
490
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000491//===----------------------------------------------------------------------===//
492// Syntactic (non-AST) Rewriting Code
493//===----------------------------------------------------------------------===//
494
Steve Naroff44e81222008-04-14 22:03:09 +0000495void RewriteObjC::RewriteInclude() {
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000496 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
497 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
498 const char *MainBufStart = MainBuf.first;
499 const char *MainBufEnd = MainBuf.second;
500 size_t ImportLen = strlen("import");
501 size_t IncludeLen = strlen("include");
502
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000503 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000504 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
505 if (*BufPtr == '#') {
506 if (++BufPtr == MainBufEnd)
507 return;
508 while (*BufPtr == ' ' || *BufPtr == '\t')
509 if (++BufPtr == MainBufEnd)
510 return;
511 if (!strncmp(BufPtr, "import", ImportLen)) {
512 // replace import with include
513 SourceLocation ImportLoc =
514 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000515 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000516 BufPtr += ImportLen;
517 }
518 }
519 }
Chris Lattner74db1682007-10-16 21:07:07 +0000520}
521
Steve Naroff44e81222008-04-14 22:03:09 +0000522void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000523 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
524 const char *MainBufStart = MainBuf.first;
525 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000526
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000527 // Loop over the whole file, looking for tabs.
528 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
529 if (*BufPtr != '\t')
530 continue;
531
532 // Okay, we found a tab. This tab will turn into at least one character,
533 // but it depends on which 'virtual column' it is in. Compute that now.
534 unsigned VCol = 0;
535 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
536 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
537 ++VCol;
538
539 // Okay, now that we know the virtual column, we know how many spaces to
540 // insert. We assume 8-character tab-stops.
541 unsigned Spaces = 8-(VCol & 7);
542
543 // Get the location of the tab.
544 SourceLocation TabLoc =
545 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
546
547 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000548 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000549 }
Chris Lattner569faa62007-10-11 18:38:32 +0000550}
551
552
Steve Naroff44e81222008-04-14 22:03:09 +0000553void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000554 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000555 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000556
557 // Get the start location and compute the semi location.
558 SourceLocation startLoc = ClassDecl->getLocation();
559 const char *startBuf = SM->getCharacterData(startLoc);
560 const char *semiPtr = strchr(startBuf, ';');
561
562 // Translate to typedef's that forward reference structs with the same name
563 // as the class. As a convenience, we include the original declaration
564 // as a comment.
565 std::string typedefString;
566 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000567 typedefString.append(startBuf, semiPtr-startBuf+1);
568 typedefString += "\n";
569 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000570 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000571 typedefString += "#ifndef _REWRITER_typedef_";
572 typedefString += ForwardDecl->getName();
573 typedefString += "\n";
574 typedefString += "#define _REWRITER_typedef_";
575 typedefString += ForwardDecl->getName();
576 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000577 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000578 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000579 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000580 }
581
582 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000583 ReplaceText(startLoc, semiPtr-startBuf+1,
584 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000585}
586
Steve Naroff44e81222008-04-14 22:03:09 +0000587void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000588 SourceLocation LocStart = Method->getLocStart();
589 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000590
Steve Naroff2ce399a2007-12-14 23:37:57 +0000591 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattner6216f292008-01-31 19:42:41 +0000592 InsertText(LocStart, "/* ", 3);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000593 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000594 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000595 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000596 }
597}
598
Steve Naroff44e81222008-04-14 22:03:09 +0000599void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000600{
Chris Lattnercffe3662008-03-16 21:23:50 +0000601 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000602 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000603 SourceLocation Loc = Property->getLocation();
604
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000605 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000606
607 // FIXME: handle properties that are declared across multiple lines.
608 }
609}
610
Steve Naroff44e81222008-04-14 22:03:09 +0000611void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000612 SourceLocation LocStart = CatDecl->getLocStart();
613
614 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000615 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000616
Ted Kremenek42730c52008-01-07 19:49:32 +0000617 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000618 E = CatDecl->instmeth_end(); I != E; ++I)
619 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000620 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000621 E = CatDecl->classmeth_end(); I != E; ++I)
622 RewriteMethodDeclaration(*I);
623
Steve Naroff667f1682007-10-30 13:30:57 +0000624 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000625 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000626}
627
Steve Naroff44e81222008-04-14 22:03:09 +0000628void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000629 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000630
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000631 SourceLocation LocStart = PDecl->getLocStart();
632
633 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000634 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000635
Ted Kremenek42730c52008-01-07 19:49:32 +0000636 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000637 E = PDecl->instmeth_end(); I != E; ++I)
638 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000639 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000640 E = PDecl->classmeth_end(); I != E; ++I)
641 RewriteMethodDeclaration(*I);
642
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000643 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000644 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000645 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000646
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000647 // Must comment out @optional/@required
648 const char *startBuf = SM->getCharacterData(LocStart);
649 const char *endBuf = SM->getCharacterData(LocEnd);
650 for (const char *p = startBuf; p < endBuf; p++) {
651 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
652 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000653 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000654 ReplaceText(OptionalLoc, strlen("@optional"),
655 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000656
657 }
658 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
659 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000660 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000661 ReplaceText(OptionalLoc, strlen("@required"),
662 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000663
664 }
665 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000666}
667
Steve Naroff44e81222008-04-14 22:03:09 +0000668void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000669 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000670 if (LocStart.isInvalid())
671 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000672 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000673 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000674}
675
Steve Naroff44e81222008-04-14 22:03:09 +0000676void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000677 std::string &ResultStr) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000678 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000679 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000680 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000681 ResultStr += "id";
Steve Naroff91044cf2008-07-16 14:40:40 +0000682 else if (OMD->getResultType()->isFunctionPointerType()) {
683 // needs special handling, since pointer-to-functions have special
684 // syntax (where a decaration models use).
685 QualType retType = OMD->getResultType();
686 if (const PointerType* PT = retType->getAsPointerType()) {
687 QualType PointeeTy = PT->getPointeeType();
688 if ((FPRetType = PointeeTy->getAsFunctionType())) {
689 ResultStr += FPRetType->getResultType().getAsString();
690 ResultStr += "(*";
691 }
692 }
693 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000694 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000695 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000696
697 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000698 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000699
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000700 if (OMD->isInstance())
701 NameStr += "_I_";
702 else
703 NameStr += "_C_";
704
705 NameStr += OMD->getClassInterface()->getName();
706 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000707
708 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000709 if (ObjCCategoryImplDecl *CID =
710 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000711 NameStr += CID->getName();
712 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000713 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000714 // Append selector names, replacing ':' with '_'
715 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000716 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000717 else {
718 std::string selString = OMD->getSelector().getName();
719 int len = selString.size();
720 for (int i = 0; i < len; i++)
721 if (selString[i] == ':')
722 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000723 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000724 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000725 // Remember this name for metadata emission
726 MethodInternalNames[OMD] = NameStr;
727 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000728
729 // Rewrite arguments
730 ResultStr += "(";
731
732 // invisible arguments
733 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000734 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000735 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000736 if (!LangOpts.Microsoft) {
737 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
738 ResultStr += "struct ";
739 }
740 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroffde0da102008-03-10 23:16:54 +0000741 ResultStr += OMD->getClassInterface()->getName();
Steve Naroffde0da102008-03-10 23:16:54 +0000742 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000743 }
744 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000745 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000746
747 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000748 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000749 ResultStr += " _cmd";
750
751 // Method arguments.
Chris Lattner685d7922008-03-16 01:07:14 +0000752 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000753 ParmVarDecl *PDecl = OMD->getParamDecl(i);
754 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000755 if (PDecl->getType()->isObjCQualifiedIdType()) {
756 ResultStr += "id ";
757 ResultStr += PDecl->getName();
758 } else {
759 std::string Name = PDecl->getName();
760 PDecl->getType().getAsStringInternal(Name);
761 ResultStr += Name;
762 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000763 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000764 if (OMD->isVariadic())
765 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000766 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000767
Steve Naroff91044cf2008-07-16 14:40:40 +0000768 if (FPRetType) {
769 ResultStr += ")"; // close the precedence "scope" for "*".
770
771 // Now, emit the argument types (if any).
772 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
773 ResultStr += "(";
774 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
775 if (i) ResultStr += ", ";
776 std::string ParamStr = FT->getArgType(i).getAsString();
777 ResultStr += ParamStr;
778 }
779 if (FT->isVariadic()) {
780 if (FT->getNumArgs()) ResultStr += ", ";
781 ResultStr += "...";
782 }
783 ResultStr += ")";
784 } else {
785 ResultStr += "()";
786 }
787 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000788}
Steve Naroff44e81222008-04-14 22:03:09 +0000789void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000790 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
791 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000792
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000793 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000794 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000795 else
Chris Lattner6216f292008-01-31 19:42:41 +0000796 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000797
Ted Kremenek42730c52008-01-07 19:49:32 +0000798 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000799 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
800 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000801 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000802 ObjCMethodDecl *OMD = *I;
803 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000804 SourceLocation LocStart = OMD->getLocStart();
805 SourceLocation LocEnd = OMD->getBody()->getLocStart();
806
807 const char *startBuf = SM->getCharacterData(LocStart);
808 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000809 ReplaceText(LocStart, endBuf-startBuf,
810 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000811 }
812
Ted Kremenek42730c52008-01-07 19:49:32 +0000813 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000814 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
815 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000816 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000817 ObjCMethodDecl *OMD = *I;
818 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000819 SourceLocation LocStart = OMD->getLocStart();
820 SourceLocation LocEnd = OMD->getBody()->getLocStart();
821
822 const char *startBuf = SM->getCharacterData(LocStart);
823 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000824 ReplaceText(LocStart, endBuf-startBuf,
825 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000826 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000827 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000828 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000829 else
Chris Lattner6216f292008-01-31 19:42:41 +0000830 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000831}
832
Steve Naroff44e81222008-04-14 22:03:09 +0000833void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000834 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000835 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000836 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000837 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000838 ResultStr += ClassDecl->getName();
839 ResultStr += "\n";
840 ResultStr += "#define _REWRITER_typedef_";
841 ResultStr += ClassDecl->getName();
842 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000843 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000844 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000845 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000846 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000847 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000848 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000849 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000850
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000851 RewriteProperties(ClassDecl->getNumPropertyDecl(),
852 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000853 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000854 E = ClassDecl->instmeth_end(); I != E; ++I)
855 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000856 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000857 E = ClassDecl->classmeth_end(); I != E; ++I)
858 RewriteMethodDeclaration(*I);
859
Steve Naroff1ccf4632007-10-30 03:43:13 +0000860 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000861 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000862}
863
Chris Lattner343c82b2008-05-23 20:40:52 +0000864Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
865 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000866 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000867 if (CurMethodDecl) {
868 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000869 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
870 // lookup which class implements the instance variable.
871 ObjCInterfaceDecl *clsDeclared = 0;
872 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
873 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
874
875 // Synthesize an explicit cast to gain access to the ivar.
876 std::string RecName = clsDeclared->getIdentifier()->getName();
877 RecName += "_IMPL";
878 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000879 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Steve Naroffa9636222008-05-08 17:52:16 +0000880 SourceLocation(), II, 0);
881 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
882 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
883 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
884 // Don't forget the parens to enforce the proper binding.
Chris Lattner343c82b2008-05-23 20:40:52 +0000885 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
886 IV->getBase()->getLocEnd(),
887 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +0000888 if (IV->isFreeIvar() &&
889 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner343c82b2008-05-23 20:40:52 +0000890 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
891 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +0000892 ReplaceStmt(IV, ME);
893 delete IV;
894 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +0000895 }
Chris Lattner343c82b2008-05-23 20:40:52 +0000896
897 ReplaceStmt(IV->getBase(), PE);
898 // Cannot delete IV->getBase(), since PE points to it.
899 // Replace the old base with the cast. This is important when doing
900 // embedded rewrites. For example, [newInv->_container addObject:0].
901 IV->setBase(PE);
902 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000903 }
Steve Naroffe6155362008-04-18 21:55:08 +0000904 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +0000905 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
906
907 // Explicit ivar refs need to have a cast inserted.
908 // FIXME: consider sharing some of this code with the code above.
909 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000910 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +0000911 // lookup which class implements the instance variable.
912 ObjCInterfaceDecl *clsDeclared = 0;
Steve Naroffa9636222008-05-08 17:52:16 +0000913 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000914 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
915
916 // Synthesize an explicit cast to gain access to the ivar.
917 std::string RecName = clsDeclared->getIdentifier()->getName();
918 RecName += "_IMPL";
919 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000920 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Steve Naroffd8d30b92008-05-06 23:20:07 +0000921 SourceLocation(), II, 0);
922 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
923 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
924 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
925 // Don't forget the parens to enforce the proper binding.
Chris Lattner3cca6612008-05-28 16:38:23 +0000926 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
927 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000928 ReplaceStmt(IV->getBase(), PE);
929 // Cannot delete IV->getBase(), since PE points to it.
930 // Replace the old base with the cast. This is important when doing
931 // embedded rewrites. For example, [newInv->_container addObject:0].
932 IV->setBase(PE);
933 return IV;
934 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000935 }
Steve Naroffe6155362008-04-18 21:55:08 +0000936 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000937}
938
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000939//===----------------------------------------------------------------------===//
940// Function Body / Expression rewriting
941//===----------------------------------------------------------------------===//
942
Steve Naroff44e81222008-04-14 22:03:09 +0000943Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000944 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
945 isa<DoStmt>(S) || isa<ForStmt>(S))
946 Stmts.push_back(S);
947 else if (isa<ObjCForCollectionStmt>(S)) {
948 Stmts.push_back(S);
949 ObjCBcLabelNo.push_back(++BcLabelCount);
950 }
951
Chris Lattner343c82b2008-05-23 20:40:52 +0000952 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner2c022162008-01-31 05:10:40 +0000953
954 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000955 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
956 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000957 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000958 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000959 if (newStmt)
960 *CI = newStmt;
961 }
Steve Naroffe9780582007-10-23 23:50:29 +0000962
963 // Handle specific things.
964 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
965 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000966
967 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner343c82b2008-05-23 20:40:52 +0000968 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroff296b74f2007-11-05 14:50:49 +0000969
970 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
971 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000972
Steve Naroff0add5d22007-11-03 11:27:19 +0000973 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
974 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000975
Steve Naroff71226032007-10-24 22:48:43 +0000976 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
977 // Before we rewrite it, put the original message expression in a comment.
978 SourceLocation startLoc = MessExpr->getLocStart();
979 SourceLocation endLoc = MessExpr->getLocEnd();
980
981 const char *startBuf = SM->getCharacterData(startLoc);
982 const char *endBuf = SM->getCharacterData(endLoc);
983
984 std::string messString;
985 messString += "// ";
986 messString.append(startBuf, endBuf-startBuf+1);
987 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000988
Chris Lattner6216f292008-01-31 19:42:41 +0000989 // FIXME: Missing definition of
990 // InsertText(clang::SourceLocation, char const*, unsigned int).
991 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff71226032007-10-24 22:48:43 +0000992 // Tried this, but it didn't work either...
Chris Lattner6216f292008-01-31 19:42:41 +0000993 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000994 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000995 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000996
Ted Kremenek42730c52008-01-07 19:49:32 +0000997 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
998 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000999
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001000 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
1001 return RewriteObjCSynchronizedStmt(StmtTry);
1002
Ted Kremenek42730c52008-01-07 19:49:32 +00001003 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
1004 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001005
1006 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
1007 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001008
1009 if (ObjCForCollectionStmt *StmtForCollection =
1010 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner343c82b2008-05-23 20:40:52 +00001011 return RewriteObjCForCollectionStmt(StmtForCollection,
1012 OrigStmtRange.getEnd());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001013 if (BreakStmt *StmtBreakStmt =
1014 dyn_cast<BreakStmt>(S))
1015 return RewriteBreakStmt(StmtBreakStmt);
1016 if (ContinueStmt *StmtContinueStmt =
1017 dyn_cast<ContinueStmt>(S))
1018 return RewriteContinueStmt(StmtContinueStmt);
Steve Naroffd06c88d2008-07-29 18:15:38 +00001019
1020 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls and cast exprs.
1021 if (DeclStmt *DS = dyn_cast<DeclStmt>(S))
1022 RewriteObjCQualifiedInterfaceTypes(DS->getDecl());
1023 if (CastExpr *CE = dyn_cast<CastExpr>(S))
1024 RewriteObjCQualifiedInterfaceTypes(CE);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001025
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001026 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1027 isa<DoStmt>(S) || isa<ForStmt>(S)) {
1028 assert(!Stmts.empty() && "Statement stack is empty");
1029 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
1030 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
1031 && "Statement stack mismatch");
1032 Stmts.pop_back();
1033 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001034#if 0
1035 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
1036 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
1037 // Get the new text.
1038 std::ostringstream Buf;
1039 Replacement->printPretty(Buf);
1040 const std::string &Str = Buf.str();
1041
1042 printf("CAST = %s\n", &Str[0]);
Chris Lattner6216f292008-01-31 19:42:41 +00001043 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001044 delete S;
1045 return Replacement;
1046 }
1047#endif
Chris Lattner0021f452007-10-24 16:57:36 +00001048 // Return this stmt unmodified.
1049 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001050}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001051
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001052/// SynthCountByEnumWithState - To print:
1053/// ((unsigned int (*)
1054/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1055/// (void *)objc_msgSend)((id)l_collection,
1056/// sel_registerName(
1057/// "countByEnumeratingWithState:objects:count:"),
1058/// &enumState,
1059/// (id *)items, (unsigned int)16)
1060///
Steve Naroff44e81222008-04-14 22:03:09 +00001061void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001062 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1063 "id *, unsigned int))(void *)objc_msgSend)";
1064 buf += "\n\t\t";
1065 buf += "((id)l_collection,\n\t\t";
1066 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1067 buf += "\n\t\t";
1068 buf += "&enumState, "
1069 "(id *)items, (unsigned int)16)";
1070}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001071
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001072/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1073/// statement to exit to its outer synthesized loop.
1074///
Steve Naroff44e81222008-04-14 22:03:09 +00001075Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001076 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1077 return S;
1078 // replace break with goto __break_label
1079 std::string buf;
1080
1081 SourceLocation startLoc = S->getLocStart();
1082 buf = "goto __break_label_";
1083 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001084 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001085
1086 return 0;
1087}
1088
1089/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1090/// statement to continue with its inner synthesized loop.
1091///
Steve Naroff44e81222008-04-14 22:03:09 +00001092Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001093 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1094 return S;
1095 // replace continue with goto __continue_label
1096 std::string buf;
1097
1098 SourceLocation startLoc = S->getLocStart();
1099 buf = "goto __continue_label_";
1100 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001101 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001102
1103 return 0;
1104}
1105
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001106/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001107/// It rewrites:
1108/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001109
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001110/// Into:
1111/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001112/// type elem;
1113/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001114/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001115/// id l_collection = (id)collection;
1116/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1117/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001118/// if (limit) {
1119/// unsigned long startMutations = *enumState.mutationsPtr;
1120/// do {
1121/// unsigned long counter = 0;
1122/// do {
1123/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001124/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001125/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001126/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001127/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001128/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001129/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1130/// objects:items count:16]);
1131/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001132/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001133/// }
1134/// else
1135/// elem = nil;
1136/// }
1137///
Steve Naroff44e81222008-04-14 22:03:09 +00001138Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001139 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001140 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1141 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1142 "ObjCForCollectionStmt Statement stack mismatch");
1143 assert(!ObjCBcLabelNo.empty() &&
1144 "ObjCForCollectionStmt - Label No stack empty");
1145
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001146 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001147 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001148 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001149 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001150 std::string buf;
1151 buf = "\n{\n\t";
1152 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1153 // type elem;
1154 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001155 elementTypeAsString = ElementType.getAsString();
1156 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001157 buf += " ";
1158 elementName = DS->getDecl()->getName();
1159 buf += elementName;
1160 buf += ";\n\t";
1161 }
Chris Lattner690c2872008-04-08 05:52:18 +00001162 else {
1163 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001164 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001165 elementTypeAsString = DR->getDecl()->getType().getAsString();
1166 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001167
1168 // struct __objcFastEnumerationState enumState = { 0 };
1169 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1170 // id items[16];
1171 buf += "id items[16];\n\t";
1172 // id l_collection = (id)
1173 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001174 // Find start location of 'collection' the hard way!
1175 const char *startCollectionBuf = startBuf;
1176 startCollectionBuf += 3; // skip 'for'
1177 startCollectionBuf = strchr(startCollectionBuf, '(');
1178 startCollectionBuf++; // skip '('
1179 // find 'in' and skip it.
1180 while (*startCollectionBuf != ' ' ||
1181 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1182 (*(startCollectionBuf+3) != ' ' &&
1183 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1184 startCollectionBuf++;
1185 startCollectionBuf += 3;
1186
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001187 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001188 ReplaceText(startLoc, startCollectionBuf - startBuf,
1189 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001190 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001191 SourceLocation rightParenLoc = S->getRParenLoc();
1192 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1193 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001194 buf = ";\n\t";
1195
1196 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1197 // objects:items count:16];
1198 // which is synthesized into:
1199 // unsigned int limit =
1200 // ((unsigned int (*)
1201 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1202 // (void *)objc_msgSend)((id)l_collection,
1203 // sel_registerName(
1204 // "countByEnumeratingWithState:objects:count:"),
1205 // (struct __objcFastEnumerationState *)&state,
1206 // (id *)items, (unsigned int)16);
1207 buf += "unsigned long limit =\n\t\t";
1208 SynthCountByEnumWithState(buf);
1209 buf += ";\n\t";
1210 /// if (limit) {
1211 /// unsigned long startMutations = *enumState.mutationsPtr;
1212 /// do {
1213 /// unsigned long counter = 0;
1214 /// do {
1215 /// if (startMutations != *enumState.mutationsPtr)
1216 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001217 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001218 buf += "if (limit) {\n\t";
1219 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1220 buf += "do {\n\t\t";
1221 buf += "unsigned long counter = 0;\n\t\t";
1222 buf += "do {\n\t\t\t";
1223 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1224 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1225 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001226 buf += " = (";
1227 buf += elementTypeAsString;
1228 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001229 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001230 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001231
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001232 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001233 /// } while (counter < limit);
1234 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1235 /// objects:items count:16]);
1236 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001237 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001238 /// }
1239 /// else
1240 /// elem = nil;
1241 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001242 ///
1243 buf = ";\n\t";
1244 buf += "__continue_label_";
1245 buf += utostr(ObjCBcLabelNo.back());
1246 buf += ": ;";
1247 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001248 buf += "} while (counter < limit);\n\t";
1249 buf += "} while (limit = ";
1250 SynthCountByEnumWithState(buf);
1251 buf += ");\n\t";
1252 buf += elementName;
1253 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001254 buf += "__break_label_";
1255 buf += utostr(ObjCBcLabelNo.back());
1256 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001257 buf += "}\n\t";
1258 buf += "else\n\t\t";
1259 buf += elementName;
1260 buf += " = nil;\n";
1261 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001262
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001263 // Insert all these *after* the statement body.
Steve Naroff5f238fe2008-07-21 18:26:02 +00001264 if (isa<CompoundStmt>(S->getBody())) {
1265 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1266 InsertText(endBodyLoc, buf.c_str(), buf.size());
1267 } else {
1268 /* Need to treat single statements specially. For example:
1269 *
1270 * for (A *a in b) if (stuff()) break;
1271 * for (A *a in b) xxxyy;
1272 *
1273 * The following code simply scans ahead to the semi to find the actual end.
1274 */
1275 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1276 const char *semiBuf = strchr(stmtBuf, ';');
1277 assert(semiBuf && "Can't find ';'");
1278 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1279 InsertText(endBodyLoc, buf.c_str(), buf.size());
1280 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001281 Stmts.pop_back();
1282 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001283 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001284}
1285
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001286/// RewriteObjCSynchronizedStmt -
1287/// This routine rewrites @synchronized(expr) stmt;
1288/// into:
1289/// objc_sync_enter(expr);
1290/// @try stmt @finally { objc_sync_exit(expr); }
1291///
Steve Naroff44e81222008-04-14 22:03:09 +00001292Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001293 // Get the start location and compute the semi location.
1294 SourceLocation startLoc = S->getLocStart();
1295 const char *startBuf = SM->getCharacterData(startLoc);
1296
1297 assert((*startBuf == '@') && "bogus @synchronized location");
1298
1299 std::string buf;
1300 buf = "objc_sync_enter";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001301 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001302 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1303 const char *endBuf = SM->getCharacterData(endLoc);
1304 endBuf++;
1305 const char *rparenBuf = strchr(endBuf, ')');
1306 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1307 buf = ");\n";
1308 // declare a new scope with two variables, _stack and _rethrow.
1309 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1310 buf += "int buf[18/*32-bit i386*/];\n";
1311 buf += "char *pointers[4];} _stack;\n";
1312 buf += "id volatile _rethrow = 0;\n";
1313 buf += "objc_exception_try_enter(&_stack);\n";
1314 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001315 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001316 startLoc = S->getSynchBody()->getLocEnd();
1317 startBuf = SM->getCharacterData(startLoc);
1318
1319 assert((*startBuf == '}') && "bogus @try block");
1320 SourceLocation lastCurlyLoc = startLoc;
1321 buf = "}\nelse {\n";
1322 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1323 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001324 buf += " objc_sync_exit(";
1325 std::ostringstream syncExprBuf;
1326 S->getSynchExpr()->printPretty(syncExprBuf);
1327 buf += syncExprBuf.str();
1328 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001329 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1330 buf += "}\n";
1331 buf += "}";
1332
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001333 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001334 return 0;
1335}
1336
Steve Naroff44e81222008-04-14 22:03:09 +00001337Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001338 // Get the start location and compute the semi location.
1339 SourceLocation startLoc = S->getLocStart();
1340 const char *startBuf = SM->getCharacterData(startLoc);
1341
1342 assert((*startBuf == '@') && "bogus @try location");
1343
1344 std::string buf;
1345 // declare a new scope with two variables, _stack and _rethrow.
1346 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1347 buf += "int buf[18/*32-bit i386*/];\n";
1348 buf += "char *pointers[4];} _stack;\n";
1349 buf += "id volatile _rethrow = 0;\n";
1350 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001351 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001352
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001353 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001354
1355 startLoc = S->getTryBody()->getLocEnd();
1356 startBuf = SM->getCharacterData(startLoc);
1357
1358 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001359
Steve Naroffe9f69842007-11-07 04:08:17 +00001360 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001361 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1362 if (catchList) {
1363 startLoc = startLoc.getFileLocWithOffset(1);
1364 buf = " /* @catch begin */ else {\n";
1365 buf += " id _caught = objc_exception_extract(&_stack);\n";
1366 buf += " objc_exception_try_enter (&_stack);\n";
1367 buf += " if (_setjmp(_stack.buf))\n";
1368 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1369 buf += " else { /* @catch continue */";
1370
1371 InsertText(startLoc, buf.c_str(), buf.size());
1372 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001373 bool sawIdTypedCatch = false;
1374 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001375 while (catchList) {
1376 Stmt *catchStmt = catchList->getCatchParamStmt();
1377
1378 if (catchList == S->getCatchStmts())
1379 buf = "if ("; // we are generating code for the first catch clause
1380 else
1381 buf = "else if (";
1382 startLoc = catchList->getLocStart();
1383 startBuf = SM->getCharacterData(startLoc);
1384
1385 assert((*startBuf == '@') && "bogus @catch location");
1386
1387 const char *lParenLoc = strchr(startBuf, '(');
1388
Steve Naroff397c4ce2008-02-01 22:08:12 +00001389 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001390 // Now rewrite the body...
1391 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001392 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1393 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001394 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1395 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001396 assert((*bodyBuf == '{') && "bogus @catch body location");
1397
1398 buf += "1) { id _tmp = _caught;";
1399 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1400 buf.c_str(), buf.size());
1401 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001402 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001403 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001404 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001405 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001406 sawIdTypedCatch = true;
1407 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001408 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001409
Ted Kremenek42730c52008-01-07 19:49:32 +00001410 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001411 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001412 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001413 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001414 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001415 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001416 }
1417 }
1418 // Now rewrite the body...
1419 lastCatchBody = catchList->getCatchBody();
1420 SourceLocation rParenLoc = catchList->getRParenLoc();
1421 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1422 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1423 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1424 assert((*rParenBuf == ')') && "bogus @catch paren location");
1425 assert((*bodyBuf == '{') && "bogus @catch body location");
1426
1427 buf = " = _caught;";
1428 // Here we replace ") {" with "= _caught;" (which initializes and
1429 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001430 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001431 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001432 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001433 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001434 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001435 catchList = catchList->getNextCatchStmt();
1436 }
1437 // Complete the catch list...
1438 if (lastCatchBody) {
1439 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001440 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1441 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001442 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1443 buf = " } } /* @catch end */\n";
1444
Chris Lattner6216f292008-01-31 19:42:41 +00001445 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001446
1447 // Set lastCurlyLoc
1448 lastCurlyLoc = lastCatchBody->getLocEnd();
1449 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001450 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001451 startLoc = finalStmt->getLocStart();
1452 startBuf = SM->getCharacterData(startLoc);
1453 assert((*startBuf == '@') && "bogus @finally start");
1454
1455 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001456 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001457
1458 Stmt *body = finalStmt->getFinallyBody();
1459 SourceLocation startLoc = body->getLocStart();
1460 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001461 assert(*SM->getCharacterData(startLoc) == '{' &&
1462 "bogus @finally body location");
1463 assert(*SM->getCharacterData(endLoc) == '}' &&
1464 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001465
1466 startLoc = startLoc.getFileLocWithOffset(1);
1467 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001468 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001469 endLoc = endLoc.getFileLocWithOffset(-1);
1470 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001471 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001472
1473 // Set lastCurlyLoc
1474 lastCurlyLoc = body->getLocEnd();
1475 }
1476 // Now emit the final closing curly brace...
1477 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1478 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001479 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001480 return 0;
1481}
1482
Steve Naroff44e81222008-04-14 22:03:09 +00001483Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001484 return 0;
1485}
1486
Steve Naroff44e81222008-04-14 22:03:09 +00001487Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001488 return 0;
1489}
1490
Chris Lattnerb1548372008-01-31 19:37:57 +00001491// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001492// the throw expression is typically a message expression that's already
1493// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001494Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001495 // Get the start location and compute the semi location.
1496 SourceLocation startLoc = S->getLocStart();
1497 const char *startBuf = SM->getCharacterData(startLoc);
1498
1499 assert((*startBuf == '@') && "bogus @throw location");
1500
1501 std::string buf;
1502 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001503 if (S->getThrowExpr())
1504 buf = "objc_exception_throw(";
1505 else // add an implicit argument
1506 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001507
1508 // handle "@ throw" correctly.
1509 const char *wBuf = strchr(startBuf, 'w');
1510 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1511 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1512
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001513 const char *semiBuf = strchr(startBuf, ';');
1514 assert((*semiBuf == ';') && "@throw: can't find ';'");
1515 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1516 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001517 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001518 return 0;
1519}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001520
Steve Naroff44e81222008-04-14 22:03:09 +00001521Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001522 // Create a new string expression.
1523 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001524 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001525 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1526 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001527 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1528 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001529 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001530 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001531
Chris Lattner4478db92007-11-30 22:53:43 +00001532 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001533 delete Exp;
1534 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001535}
1536
Steve Naroff44e81222008-04-14 22:03:09 +00001537Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff296b74f2007-11-05 14:50:49 +00001538 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1539 // Create a call to sel_registerName("selName").
1540 llvm::SmallVector<Expr*, 8> SelExprs;
1541 QualType argType = Context->getPointerType(Context->CharTy);
1542 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1543 Exp->getSelector().getName().size(),
1544 false, argType, SourceLocation(),
1545 SourceLocation()));
1546 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1547 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001548 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001549 delete Exp;
1550 return SelExp;
1551}
1552
Steve Naroff44e81222008-04-14 22:03:09 +00001553CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001554 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001555 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001556 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001557
1558 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001559 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001560
1561 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001562 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001563 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1564
1565 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001566
Steve Naroff71226032007-10-24 22:48:43 +00001567 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1568}
1569
Steve Naroffc8a92d12007-11-01 13:24:47 +00001570static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1571 const char *&startRef, const char *&endRef) {
1572 while (startBuf < endBuf) {
1573 if (*startBuf == '<')
1574 startRef = startBuf; // mark the start.
1575 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001576 if (startRef && *startRef == '<') {
1577 endRef = startBuf; // mark the end.
1578 return true;
1579 }
1580 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001581 }
1582 startBuf++;
1583 }
1584 return false;
1585}
1586
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001587static void scanToNextArgument(const char *&argRef) {
1588 int angle = 0;
1589 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1590 if (*argRef == '<')
1591 angle++;
1592 else if (*argRef == '>')
1593 angle--;
1594 argRef++;
1595 }
1596 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1597}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001598
Steve Naroff44e81222008-04-14 22:03:09 +00001599bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001600
Ted Kremenek42730c52008-01-07 19:49:32 +00001601 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001602 return true;
1603
Steve Naroffc8a92d12007-11-01 13:24:47 +00001604 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001605 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001606 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001607 return true; // we have "Class <Protocol> *".
1608 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001609 return false;
1610}
1611
Steve Naroffd06c88d2008-07-29 18:15:38 +00001612void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1613 QualType Type = E->getType();
1614 if (needToScanForQualifiers(Type)) {
1615 SourceLocation Loc = E->getLocStart();
1616 const char *startBuf = SM->getCharacterData(Loc);
1617 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1618 const char *startRef = 0, *endRef = 0;
1619 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1620 // Get the locations of the startRef, endRef.
1621 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1622 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1623 // Comment out the protocol references.
1624 InsertText(LessLoc, "/*", 2);
1625 InsertText(GreaterLoc, "*/", 2);
1626 }
1627 }
1628}
1629
Steve Naroff44e81222008-04-14 22:03:09 +00001630void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001631 SourceLocation Loc;
1632 QualType Type;
1633 const FunctionTypeProto *proto = 0;
1634 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1635 Loc = VD->getLocation();
1636 Type = VD->getType();
1637 }
1638 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1639 Loc = FD->getLocation();
1640 // Check for ObjC 'id' and class types that have been adorned with protocol
1641 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1642 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1643 assert(funcType && "missing function type");
1644 proto = dyn_cast<FunctionTypeProto>(funcType);
1645 if (!proto)
1646 return;
1647 Type = proto->getResultType();
1648 }
1649 else
1650 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001651
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001652 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001653 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001654
1655 const char *endBuf = SM->getCharacterData(Loc);
1656 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001657 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001658 startBuf--; // scan backward (from the decl location) for return type.
1659 const char *startRef = 0, *endRef = 0;
1660 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1661 // Get the locations of the startRef, endRef.
1662 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1663 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1664 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001665 InsertText(LessLoc, "/*", 2);
1666 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001667 }
1668 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001669 if (!proto)
1670 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001671 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001672 const char *startBuf = SM->getCharacterData(Loc);
1673 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001674 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1675 if (needToScanForQualifiers(proto->getArgType(i))) {
1676 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001677
Steve Naroffc8a92d12007-11-01 13:24:47 +00001678 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001679 // scan forward (from the decl location) for argument types.
1680 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001681 const char *startRef = 0, *endRef = 0;
1682 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1683 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001684 SourceLocation LessLoc =
1685 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1686 SourceLocation GreaterLoc =
1687 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001688 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001689 InsertText(LessLoc, "/*", 2);
1690 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001691 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001692 startBuf = ++endBuf;
1693 }
1694 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001695 // If the function name is derived from a macro expansion, then the
1696 // argument buffer will not follow the name. Need to speak with Chris.
1697 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001698 startBuf++; // scan forward (from the decl location) for argument types.
1699 startBuf++;
1700 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001701 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001702}
1703
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001704// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001705void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001706 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1707 llvm::SmallVector<QualType, 16> ArgTys;
1708 ArgTys.push_back(Context->getPointerType(
1709 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001710 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001711 &ArgTys[0], ArgTys.size(),
1712 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001713 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001714 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001715 SelGetUidIdent, getFuncType,
1716 FunctionDecl::Extern, false, 0);
1717}
1718
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001719// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001720void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001721 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1722 llvm::SmallVector<QualType, 16> ArgTys;
1723 ArgTys.push_back(Context->getPointerType(
1724 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001725 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001726 &ArgTys[0], ArgTys.size(),
1727 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001728 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001729 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001730 SelGetProtoIdent, getFuncType,
1731 FunctionDecl::Extern, false, 0);
1732}
1733
Steve Naroff44e81222008-04-14 22:03:09 +00001734void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001735 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001736 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001737 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001738 return;
1739 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001740 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001741}
1742
Steve Naroffbec4bf52008-03-11 17:37:02 +00001743// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001744void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001745 if (SuperContructorFunctionDecl)
1746 return;
1747 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1748 llvm::SmallVector<QualType, 16> ArgTys;
1749 QualType argT = Context->getObjCIdType();
1750 assert(!argT.isNull() && "Can't find 'id' type");
1751 ArgTys.push_back(argT);
1752 ArgTys.push_back(argT);
1753 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1754 &ArgTys[0], ArgTys.size(),
1755 false);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001756 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001757 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001758 msgSendIdent, msgSendType,
1759 FunctionDecl::Extern, false, 0);
1760}
1761
Steve Naroff02a82aa2007-10-30 23:14:51 +00001762// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001763void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001764 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1765 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001766 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001767 assert(!argT.isNull() && "Can't find 'id' type");
1768 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001769 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001770 assert(!argT.isNull() && "Can't find 'SEL' type");
1771 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001772 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001773 &ArgTys[0], ArgTys.size(),
1774 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001775 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001776 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001777 msgSendIdent, msgSendType,
1778 FunctionDecl::Extern, false, 0);
1779}
1780
Steve Naroff764c1ae2007-11-15 10:28:18 +00001781// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001782void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001783 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1784 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001785 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001786 SourceLocation(),
Chris Lattner58114f02008-03-15 21:32:50 +00001787 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001788 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1789 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1790 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001791 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001792 assert(!argT.isNull() && "Can't find 'SEL' type");
1793 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001794 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001795 &ArgTys[0], ArgTys.size(),
1796 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001797 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001798 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001799 msgSendIdent, msgSendType,
1800 FunctionDecl::Extern, false, 0);
1801}
1802
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001803// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001804void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001805 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1806 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001807 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001808 assert(!argT.isNull() && "Can't find 'id' type");
1809 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001810 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001811 assert(!argT.isNull() && "Can't find 'SEL' type");
1812 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001813 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001814 &ArgTys[0], ArgTys.size(),
1815 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001816 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001817 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001818 msgSendIdent, msgSendType,
1819 FunctionDecl::Extern, false, 0);
1820}
1821
1822// SynthMsgSendSuperStretFunctionDecl -
1823// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001824void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001825 IdentifierInfo *msgSendIdent =
1826 &Context->Idents.get("objc_msgSendSuper_stret");
1827 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001828 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001829 SourceLocation(),
Chris Lattner58114f02008-03-15 21:32:50 +00001830 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001831 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1832 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1833 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001834 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001835 assert(!argT.isNull() && "Can't find 'SEL' type");
1836 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001837 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001838 &ArgTys[0], ArgTys.size(),
1839 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001840 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00001841 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001842 msgSendIdent, msgSendType,
1843 FunctionDecl::Extern, false, 0);
1844}
1845
Steve Naroff31316a12008-05-08 22:02:18 +00001846// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001847void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001848 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1849 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001850 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001851 assert(!argT.isNull() && "Can't find 'id' type");
1852 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001853 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001854 assert(!argT.isNull() && "Can't find 'SEL' type");
1855 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00001856 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001857 &ArgTys[0], ArgTys.size(),
1858 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001859 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001860 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001861 msgSendIdent, msgSendType,
1862 FunctionDecl::Extern, false, 0);
1863}
1864
Steve Naroff02a82aa2007-10-30 23:14:51 +00001865// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001866void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001867 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1868 llvm::SmallVector<QualType, 16> ArgTys;
1869 ArgTys.push_back(Context->getPointerType(
1870 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001871 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001872 &ArgTys[0], ArgTys.size(),
1873 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001874 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001875 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001876 getClassIdent, getClassType,
1877 FunctionDecl::Extern, false, 0);
1878}
1879
Steve Naroff3b1caac2007-12-07 03:50:46 +00001880// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001881void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001882 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1883 llvm::SmallVector<QualType, 16> ArgTys;
1884 ArgTys.push_back(Context->getPointerType(
1885 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001886 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001887 &ArgTys[0], ArgTys.size(),
1888 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001889 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001890 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001891 getClassIdent, getClassType,
1892 FunctionDecl::Extern, false, 0);
1893}
1894
Steve Naroff44e81222008-04-14 22:03:09 +00001895Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001896 QualType strType = getConstantStringStructType();
1897
1898 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00001899
1900 std::string tmpName = InFileName;
1901 unsigned i;
1902 for (i=0; i < tmpName.length(); i++) {
1903 char c = tmpName.at(i);
1904 // replace any non alphanumeric characters with '_'.
1905 if (!isalpha(c) && (c < '0' || c > '9'))
1906 tmpName[i] = '_';
1907 }
1908 S += tmpName;
1909 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001910 S += utostr(NumObjCStringLiterals++);
1911
Steve Narofffef037c2008-03-27 22:29:16 +00001912 Preamble += "static __NSConstantStringImpl " + S;
1913 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1914 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00001915 // The pretty printer for StringLiteral handles escape characters properly.
1916 std::ostringstream prettyBuf;
1917 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00001918 Preamble += prettyBuf.str();
1919 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00001920 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00001921 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001922
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001923 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001924 &Context->Idents.get(S.c_str()), strType,
1925 VarDecl::Static, NULL);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001926 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1927 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1928 Context->getPointerType(DRE->getType()),
1929 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001930 // cast to NSConstantString *
Steve Naroff47e7fa22008-03-15 00:55:56 +00001931 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001932 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001933 delete Exp;
1934 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001935}
1936
Steve Naroff44e81222008-04-14 22:03:09 +00001937ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001938 // check if we are sending a message to 'super'
Chris Lattnere4650482008-03-15 06:12:44 +00001939 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1940
Chris Lattner4423d372008-06-21 18:04:54 +00001941 if (PreDefinedExpr *PDE = dyn_cast<PreDefinedExpr>(recExpr))
1942 if (PDE->getIdentType() == PreDefinedExpr::ObjCSuper) {
1943 const PointerType *PT = PDE->getType()->getAsPointerType();
1944 assert(PT);
1945 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1946 return IT->getDecl();
1947 }
1948 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001949}
1950
1951// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00001952QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001953 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001954 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001955 SourceLocation(),
1956 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001957 QualType FieldTypes[2];
1958
1959 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001960 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001961 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001962 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001963 // Create fields
1964 FieldDecl *FieldDecls[2];
1965
1966 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001967 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001968 FieldTypes[i]);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001969
1970 SuperStructDecl->defineBody(FieldDecls, 4);
1971 }
1972 return Context->getTagDeclType(SuperStructDecl);
1973}
1974
Steve Naroff44e81222008-04-14 22:03:09 +00001975QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001976 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001977 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001978 SourceLocation(),
1979 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001980 QualType FieldTypes[4];
1981
1982 // struct objc_object *receiver;
1983 FieldTypes[0] = Context->getObjCIdType();
1984 // int flags;
1985 FieldTypes[1] = Context->IntTy;
1986 // char *str;
1987 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1988 // long length;
1989 FieldTypes[3] = Context->LongTy;
1990 // Create fields
Steve Naroff053ae3f2008-03-27 22:59:54 +00001991 FieldDecl *FieldDecls[4];
Steve Naroff47e7fa22008-03-15 00:55:56 +00001992
1993 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001994 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001995 FieldTypes[i]);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001996
1997 ConstantStringDecl->defineBody(FieldDecls, 4);
1998 }
1999 return Context->getTagDeclType(ConstantStringDecl);
2000}
2001
Steve Naroff44e81222008-04-14 22:03:09 +00002002Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00002003 if (!SelGetUidFunctionDecl)
2004 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002005 if (!MsgSendFunctionDecl)
2006 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002007 if (!MsgSendSuperFunctionDecl)
2008 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002009 if (!MsgSendStretFunctionDecl)
2010 SynthMsgSendStretFunctionDecl();
2011 if (!MsgSendSuperStretFunctionDecl)
2012 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002013 if (!MsgSendFpretFunctionDecl)
2014 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002015 if (!GetClassFunctionDecl)
2016 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002017 if (!GetMetaClassFunctionDecl)
2018 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002019
Steve Naroff764c1ae2007-11-15 10:28:18 +00002020 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002021 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2022 // May need to use objc_msgSend_stret() as well.
2023 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00002024 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002025 QualType resultType = mDecl->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00002026 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002027 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00002028 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002029 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002030 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002031
Steve Naroff71226032007-10-24 22:48:43 +00002032 // Synthesize a call to objc_msgSend().
2033 llvm::SmallVector<Expr*, 8> MsgExprs;
2034 IdentifierInfo *clsName = Exp->getClassName();
2035
2036 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2037 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00002038 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2039 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002040 if (!strcmp(clsName->getName(), "super")) {
2041 MsgSendFlavor = MsgSendSuperFunctionDecl;
2042 if (MsgSendStretFlavor)
2043 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2044 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2045
Ted Kremenek42730c52008-01-07 19:49:32 +00002046 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00002047 CurMethodDecl->getClassInterface()->getSuperClass();
2048
2049 llvm::SmallVector<Expr*, 4> InitExprs;
2050
2051 // set the receiver to self, the first argument to all methods.
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002052 InitExprs.push_back(new DeclRefExpr(
2053 CurMethodDecl->getSelfDecl(),
2054 Context->getObjCIdType(),
2055 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002056 llvm::SmallVector<Expr*, 8> ClsExprs;
2057 QualType argType = Context->getPointerType(Context->CharTy);
2058 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2059 SuperDecl->getIdentifier()->getLength(),
2060 false, argType, SourceLocation(),
2061 SourceLocation()));
2062 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2063 &ClsExprs[0],
2064 ClsExprs.size());
2065 // To turn off a warning, type-cast to 'id'
2066 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00002067 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002068 Cls, SourceLocation())); // set 'super class', using objc_getClass().
2069 // struct objc_super
2070 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002071 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002072
Steve Naroffdee066b2008-03-11 18:14:26 +00002073 if (LangOpts.Microsoft) {
2074 SynthSuperContructorFunctionDecl();
2075 // Simulate a contructor call...
2076 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2077 superType, SourceLocation());
2078 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2079 superType, SourceLocation());
2080 } else {
2081 // (struct objc_super) { <exprs from above> }
2082 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2083 &InitExprs[0], InitExprs.size(),
2084 SourceLocation());
2085 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2086 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00002087 // struct objc_super *
2088 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2089 Context->getPointerType(SuperRep->getType()),
2090 SourceLocation());
2091 MsgExprs.push_back(Unop);
2092 } else {
2093 llvm::SmallVector<Expr*, 8> ClsExprs;
2094 QualType argType = Context->getPointerType(Context->CharTy);
2095 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2096 clsName->getLength(),
2097 false, argType, SourceLocation(),
2098 SourceLocation()));
2099 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2100 &ClsExprs[0],
2101 ClsExprs.size());
2102 MsgExprs.push_back(Cls);
2103 }
Steve Naroff885e2122007-11-14 23:54:14 +00002104 } else { // instance message.
2105 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002106
Ted Kremenek42730c52008-01-07 19:49:32 +00002107 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002108 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002109 if (MsgSendStretFlavor)
2110 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002111 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2112
2113 llvm::SmallVector<Expr*, 4> InitExprs;
2114
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002115 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00002116 new CastExpr(Context->getObjCIdType(),
Steve Naroff23528612008-07-16 22:35:27 +00002117 new DeclRefExpr(CurMethodDecl->getSelfDecl(),
2118 Context->getObjCIdType(),
2119 SourceLocation()),
2120 SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002121
2122 llvm::SmallVector<Expr*, 8> ClsExprs;
2123 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002124 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2125 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002126 false, argType, SourceLocation(),
2127 SourceLocation()));
2128 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002129 &ClsExprs[0],
2130 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002131 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002132 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00002133 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002134 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00002135 // struct objc_super
2136 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002137 Expr *SuperRep;
2138
2139 if (LangOpts.Microsoft) {
2140 SynthSuperContructorFunctionDecl();
2141 // Simulate a contructor call...
2142 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2143 superType, SourceLocation());
2144 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2145 superType, SourceLocation());
2146 } else {
2147 // (struct objc_super) { <exprs from above> }
2148 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2149 &InitExprs[0], InitExprs.size(),
2150 SourceLocation());
2151 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2152 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002153 // struct objc_super *
2154 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2155 Context->getPointerType(SuperRep->getType()),
2156 SourceLocation());
2157 MsgExprs.push_back(Unop);
2158 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002159 // Remove all type-casts because it may contain objc-style types; e.g.
2160 // Foo<Proto> *.
2161 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2162 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002163 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002164 MsgExprs.push_back(recExpr);
2165 }
Steve Naroff885e2122007-11-14 23:54:14 +00002166 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002167 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002168 llvm::SmallVector<Expr*, 8> SelExprs;
2169 QualType argType = Context->getPointerType(Context->CharTy);
2170 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2171 Exp->getSelector().getName().size(),
2172 false, argType, SourceLocation(),
2173 SourceLocation()));
2174 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2175 &SelExprs[0], SelExprs.size());
2176 MsgExprs.push_back(SelExp);
2177
2178 // Now push any user supplied arguments.
2179 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002180 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002181 // Make all implicit casts explicit...ICE comes in handy:-)
2182 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2183 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00002184 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2185 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002186 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002187 }
2188 // Make id<P...> cast into an 'id' cast.
2189 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002190 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002191 while ((CE = dyn_cast<CastExpr>(userExpr)))
2192 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002193 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002194 userExpr, SourceLocation());
2195 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002196 }
Steve Naroff885e2122007-11-14 23:54:14 +00002197 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002198 // We've transferred the ownership to MsgExprs. Null out the argument in
2199 // the original expression, since we will delete it below.
2200 Exp->setArg(i, 0);
2201 }
Steve Naroff0744c472007-11-04 22:37:50 +00002202 // Generate the funky cast.
2203 CastExpr *cast;
2204 llvm::SmallVector<QualType, 8> ArgTypes;
2205 QualType returnType;
2206
2207 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002208 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2209 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2210 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002211 ArgTypes.push_back(Context->getObjCIdType());
2212 ArgTypes.push_back(Context->getObjCSelType());
2213 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002214 // Push any user argument types.
Chris Lattner685d7922008-03-16 01:07:14 +00002215 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002216 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2217 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002218 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00002219 ArgTypes.push_back(t);
2220 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002221 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2222 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002223 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002224 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002225 }
2226 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002227 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002228
2229 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002230 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2231 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002232
2233 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2234 // If we don't do this cast, we get the following bizarre warning/note:
2235 // xx.m:13: warning: function called through a non-compatible type
2236 // xx.m:13: note: if this code is reached, the program will abort
2237 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2238 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002239
Steve Naroff0744c472007-11-04 22:37:50 +00002240 // Now do the "normal" pointer to function cast.
2241 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002242 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002243 // If we don't have a method decl, force a variadic cast.
2244 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroff0744c472007-11-04 22:37:50 +00002245 castType = Context->getPointerType(castType);
2246 cast = new CastExpr(castType, cast, SourceLocation());
2247
2248 // Don't forget the parens to enforce the proper binding.
2249 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2250
2251 const FunctionType *FT = msgSendType->getAsFunctionType();
2252 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2253 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002254 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002255 if (MsgSendStretFlavor) {
2256 // We have the method which returns a struct/union. Must also generate
2257 // call to objc_msgSend_stret and hang both varieties on a conditional
2258 // expression which dictate which one to envoke depending on size of
2259 // method's return type.
2260
2261 // Create a reference to the objc_msgSend_stret() declaration.
2262 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2263 SourceLocation());
2264 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2265 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2266 SourceLocation());
2267 // Now do the "normal" pointer to function cast.
2268 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002269 &ArgTypes[0], ArgTypes.size(),
2270 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002271 castType = Context->getPointerType(castType);
2272 cast = new CastExpr(castType, cast, SourceLocation());
2273
2274 // Don't forget the parens to enforce the proper binding.
2275 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2276
2277 FT = msgSendType->getAsFunctionType();
2278 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2279 FT->getResultType(), SourceLocation());
2280
2281 // Build sizeof(returnType)
2282 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2283 returnType, Context->getSizeType(),
2284 SourceLocation(), SourceLocation());
2285 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2286 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2287 // For X86 it is more complicated and some kind of target specific routine
2288 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002289 unsigned IntSize =
2290 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002291 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2292 Context->IntTy,
2293 SourceLocation());
2294 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2295 BinaryOperator::LE,
2296 Context->IntTy,
2297 SourceLocation());
2298 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2299 ConditionalOperator *CondExpr =
2300 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002301 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002302 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002303 return ReplacingStmt;
2304}
2305
Steve Naroff44e81222008-04-14 22:03:09 +00002306Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002307 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002308 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002309 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002310
Chris Lattner0021f452007-10-24 16:57:36 +00002311 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002312 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002313}
2314
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002315/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2316/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002317Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002318 if (!GetProtocolFunctionDecl)
2319 SynthGetProtocolFunctionDecl();
2320 // Create a call to objc_getProtocol("ProtocolName").
2321 llvm::SmallVector<Expr*, 8> ProtoExprs;
2322 QualType argType = Context->getPointerType(Context->CharTy);
2323 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2324 strlen(Exp->getProtocol()->getName()),
2325 false, argType, SourceLocation(),
2326 SourceLocation()));
2327 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2328 &ProtoExprs[0],
2329 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002330 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002331 delete Exp;
2332 return ProtoExp;
2333
2334}
2335
Steve Naroffef82b742008-05-31 14:15:04 +00002336bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2337 const char *endBuf) {
2338 while (startBuf < endBuf) {
2339 if (*startBuf == '#') {
2340 // Skip whitespace.
2341 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2342 ;
2343 if (!strncmp(startBuf, "if", strlen("if")) ||
2344 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2345 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2346 !strncmp(startBuf, "define", strlen("define")) ||
2347 !strncmp(startBuf, "undef", strlen("undef")) ||
2348 !strncmp(startBuf, "else", strlen("else")) ||
2349 !strncmp(startBuf, "elif", strlen("elif")) ||
2350 !strncmp(startBuf, "endif", strlen("endif")) ||
2351 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2352 !strncmp(startBuf, "include", strlen("include")) ||
2353 !strncmp(startBuf, "import", strlen("import")) ||
2354 !strncmp(startBuf, "include_next", strlen("include_next")))
2355 return true;
2356 }
2357 startBuf++;
2358 }
2359 return false;
2360}
2361
Ted Kremenek42730c52008-01-07 19:49:32 +00002362/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002363/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002364void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002365 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002366 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2367 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002368 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002369 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002370 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002371 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002372 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002373 SourceLocation LocStart = CDecl->getLocStart();
2374 SourceLocation LocEnd = CDecl->getLocEnd();
2375
2376 const char *startBuf = SM->getCharacterData(LocStart);
2377 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002378
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002379 // If no ivars and no root or if its root, directly or indirectly,
2380 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002381 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2382 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002383 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002384 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002385 return;
2386 }
2387
2388 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002389 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002390 Result += "\nstruct ";
2391 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002392 if (LangOpts.Microsoft)
2393 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002394
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002395 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002396 const char *cursor = strchr(startBuf, '{');
2397 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002398 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002399 // If the buffer contains preprocessor directives, we do more fine-grained
2400 // rewrites. This is intended to fix code that looks like (which occurs in
2401 // NSURL.h, for example):
2402 //
2403 // #ifdef XYZ
2404 // @interface Foo : NSObject
2405 // #else
2406 // @interface FooBar : NSObject
2407 // #endif
2408 // {
2409 // int i;
2410 // }
2411 // @end
2412 //
2413 // This clause is segregated to avoid breaking the common case.
2414 if (BufferContainsPPDirectives(startBuf, cursor)) {
2415 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2416 CDecl->getClassLoc();
2417 const char *endHeader = SM->getCharacterData(L);
2418 endHeader += Lexer::MeasureTokenLength(L, *SM);
2419
Chris Lattner8bcb5252008-07-21 18:19:38 +00002420 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002421 // advance to the end of the referenced protocols.
2422 while (endHeader < cursor && *endHeader != '>') endHeader++;
2423 endHeader++;
2424 }
2425 // rewrite the original header
2426 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2427 } else {
2428 // rewrite the original header *without* disturbing the '{'
2429 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2430 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002431 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002432 Result = "\n struct ";
2433 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002434 Result += "_IMPL ";
2435 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002436 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002437
2438 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002439 SourceLocation OnePastCurly =
2440 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2441 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002442 }
2443 cursor++; // past '{'
2444
2445 // Now comment out any visibility specifiers.
2446 while (cursor < endBuf) {
2447 if (*cursor == '@') {
2448 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002449 // Skip whitespace.
2450 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2451 /*scan*/;
2452
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002453 // FIXME: presence of @public, etc. inside comment results in
2454 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002455 if (!strncmp(cursor, "public", strlen("public")) ||
2456 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002457 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002458 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002459 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002460 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002461 // FIXME: If there are cases where '<' is used in ivar declaration part
2462 // of user code, then scan the ivar list and use needToScanForQualifiers
2463 // for type checking.
2464 else if (*cursor == '<') {
2465 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002466 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002467 cursor = strchr(cursor, '>');
2468 cursor++;
2469 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002470 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002471 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002472 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002473 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002474 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002475 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002476 } else { // we don't have any instance variables - insert super struct.
2477 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2478 Result += " {\n struct ";
2479 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002480 Result += "_IMPL ";
2481 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002482 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002483 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002484 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002485 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002486 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002487 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002488}
2489
Ted Kremenek42730c52008-01-07 19:49:32 +00002490// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002491/// class methods.
Steve Naroff44e81222008-04-14 22:03:09 +00002492void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002493 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002494 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002495 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002496 const char *ClassName,
2497 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002498 if (MethodBegin == MethodEnd) return;
2499
Fariborz Jahanian04455192007-10-22 21:41:37 +00002500 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002501 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002502 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002503 SEL _cmd;
2504 char *method_types;
2505 void *_imp;
2506 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002507 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002508 Result += "\nstruct _objc_method {\n";
2509 Result += "\tSEL _cmd;\n";
2510 Result += "\tchar *method_types;\n";
2511 Result += "\tvoid *_imp;\n";
2512 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002513
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002514 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002515 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002516
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002517 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002518
2519 /* struct {
2520 struct _objc_method_list *next_method;
2521 int method_count;
2522 struct _objc_method method_list[];
2523 }
2524 */
2525 Result += "\nstatic struct {\n";
2526 Result += "\tstruct _objc_method_list *next_method;\n";
2527 Result += "\tint method_count;\n";
2528 Result += "\tstruct _objc_method method_list[";
2529 Result += utostr(MethodEnd-MethodBegin);
2530 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002531 Result += prefix;
2532 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2533 Result += "_METHODS_";
2534 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002535 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002536 Result += IsInstanceMethod ? "inst" : "cls";
2537 Result += "_meth\")))= ";
2538 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002539
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002540 Result += "\t,{{(SEL)\"";
2541 Result += (*MethodBegin)->getSelector().getName().c_str();
2542 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002543 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002544 Result += "\", \"";
2545 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002546 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002547 Result += MethodInternalNames[*MethodBegin];
2548 Result += "}\n";
2549 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2550 Result += "\t ,{(SEL)\"";
2551 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002552 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002553 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002554 Result += "\", \"";
2555 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002556 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002557 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002558 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002559 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002560 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002561}
2562
Ted Kremenek42730c52008-01-07 19:49:32 +00002563/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002564void RewriteObjC::
2565RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2566 const char *prefix,
2567 const char *ClassName,
2568 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002569 static bool objc_protocol_methods = false;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002570 if (Protocols.empty()) return;
2571
2572 for (unsigned i = 0; i != Protocols.size(); i++) {
2573 ObjCProtocolDecl *PDecl = Protocols[i];
2574 // Output struct protocol_methods holder of method selector and type.
2575 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2576 /* struct protocol_methods {
2577 SEL _cmd;
2578 char *method_types;
2579 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002580 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002581 Result += "\nstruct protocol_methods {\n";
2582 Result += "\tSEL _cmd;\n";
2583 Result += "\tchar *method_types;\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002584 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002585
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002586 objc_protocol_methods = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002587 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002588 // Do not synthesize the protocol more than once.
2589 if (ObjCSynthesizedProtocols.count(PDecl))
2590 continue;
2591
2592 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2593 unsigned NumMethods = PDecl->getNumInstanceMethods();
2594 /* struct _objc_protocol_method_list {
2595 int protocol_method_count;
2596 struct protocol_methods protocols[];
2597 }
2598 */
2599 Result += "\nstatic struct {\n";
2600 Result += "\tint protocol_method_count;\n";
2601 Result += "\tstruct protocol_methods protocols[";
2602 Result += utostr(NumMethods);
2603 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2604 Result += PDecl->getName();
2605 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2606 "{\n\t" + utostr(NumMethods) + "\n";
2607
2608 // Output instance methods declared in this protocol.
2609 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2610 E = PDecl->instmeth_end(); I != E; ++I) {
2611 if (I == PDecl->instmeth_begin())
2612 Result += "\t ,{{(SEL)\"";
2613 else
2614 Result += "\t ,{(SEL)\"";
2615 Result += (*I)->getSelector().getName().c_str();
2616 std::string MethodTypeString;
2617 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2618 Result += "\", \"";
2619 Result += MethodTypeString;
2620 Result += "\"}\n";
2621 }
2622 Result += "\t }\n};\n";
2623 }
2624
2625 // Output class methods declared in this protocol.
2626 int NumMethods = PDecl->getNumClassMethods();
2627 if (NumMethods > 0) {
2628 /* struct _objc_protocol_method_list {
2629 int protocol_method_count;
2630 struct protocol_methods protocols[];
2631 }
2632 */
2633 Result += "\nstatic struct {\n";
2634 Result += "\tint protocol_method_count;\n";
2635 Result += "\tstruct protocol_methods protocols[";
2636 Result += utostr(NumMethods);
2637 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2638 Result += PDecl->getName();
2639 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2640 "{\n\t";
2641 Result += utostr(NumMethods);
2642 Result += "\n";
2643
2644 // Output instance methods declared in this protocol.
2645 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2646 E = PDecl->classmeth_end(); I != E; ++I) {
2647 if (I == PDecl->classmeth_begin())
2648 Result += "\t ,{{(SEL)\"";
2649 else
2650 Result += "\t ,{(SEL)\"";
2651 Result += (*I)->getSelector().getName().c_str();
2652 std::string MethodTypeString;
2653 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2654 Result += "\", \"";
2655 Result += MethodTypeString;
2656 Result += "\"}\n";
2657 }
2658 Result += "\t }\n};\n";
2659 }
2660
2661 // Output:
2662 /* struct _objc_protocol {
2663 // Objective-C 1.0 extensions
2664 struct _objc_protocol_extension *isa;
2665 char *protocol_name;
2666 struct _objc_protocol **protocol_list;
2667 struct _objc_protocol_method_list *instance_methods;
2668 struct _objc_protocol_method_list *class_methods;
2669 };
Steve Naroff27429432008-03-12 01:06:30 +00002670 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002671 static bool objc_protocol = false;
2672 if (!objc_protocol) {
2673 Result += "\nstruct _objc_protocol {\n";
2674 Result += "\tstruct _objc_protocol_extension *isa;\n";
2675 Result += "\tchar *protocol_name;\n";
2676 Result += "\tstruct _objc_protocol **protocol_list;\n";
2677 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2678 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2679 Result += "};\n";
2680
2681 objc_protocol = true;
2682 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002683
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002684 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2685 Result += PDecl->getName();
2686 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2687 "{\n\t0, \"";
2688 Result += PDecl->getName();
2689 Result += "\", 0, ";
2690 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2691 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2692 Result += PDecl->getName();
2693 Result += ", ";
2694 }
2695 else
2696 Result += "0, ";
2697 if (PDecl->getNumClassMethods() > 0) {
2698 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2699 Result += PDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002700 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002701 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002702 else
2703 Result += "0\n";
2704 Result += "};\n";
2705
2706 // Mark this protocol as having been generated.
2707 if (!ObjCSynthesizedProtocols.insert(PDecl))
2708 assert(false && "protocol already synthesized");
2709 }
2710 // Output the top lovel protocol meta-data for the class.
2711 /* struct _objc_protocol_list {
2712 struct _objc_protocol_list *next;
2713 int protocol_count;
2714 struct _objc_protocol *class_protocols[];
2715 }
2716 */
2717 Result += "\nstatic struct {\n";
2718 Result += "\tstruct _objc_protocol_list *next;\n";
2719 Result += "\tint protocol_count;\n";
2720 Result += "\tstruct _objc_protocol *class_protocols[";
2721 Result += utostr(Protocols.size());
2722 Result += "];\n} _OBJC_";
2723 Result += prefix;
2724 Result += "_PROTOCOLS_";
2725 Result += ClassName;
2726 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2727 "{\n\t0, ";
2728 Result += utostr(Protocols.size());
2729 Result += "\n";
2730
2731 Result += "\t,{&_OBJC_PROTOCOL_";
2732 Result += Protocols[0]->getName();
2733 Result += " \n";
2734
2735 for (unsigned i = 1; i != Protocols.size(); i++) {
2736 Result += "\t ,&_OBJC_PROTOCOL_";
2737 Result += Protocols[i]->getName();
2738 Result += "\n";
2739 }
2740 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002741}
2742
Ted Kremenek42730c52008-01-07 19:49:32 +00002743/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002744/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00002745void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002746 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002747 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002748 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002749 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002750 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2751 CDecl = CDecl->getNextClassCategory())
2752 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2753 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002754
Chris Lattnera661a4d2007-12-23 01:40:15 +00002755 std::string FullCategoryName = ClassDecl->getName();
2756 FullCategoryName += '_';
2757 FullCategoryName += IDecl->getName();
2758
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002759 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002760 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002761 true, "CATEGORY_", FullCategoryName.c_str(),
2762 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002763
2764 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002765 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002766 false, "CATEGORY_", FullCategoryName.c_str(),
2767 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002768
2769 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002770 // Null CDecl is case of a category implementation with no category interface
2771 if (CDecl)
Chris Lattner0be08822008-07-21 21:32:27 +00002772 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002773 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002774
2775 /* struct _objc_category {
2776 char *category_name;
2777 char *class_name;
2778 struct _objc_method_list *instance_methods;
2779 struct _objc_method_list *class_methods;
2780 struct _objc_protocol_list *protocols;
2781 // Objective-C 1.0 extensions
2782 uint32_t size; // sizeof (struct _objc_category)
2783 struct _objc_property_list *instance_properties; // category's own
2784 // @property decl.
2785 };
2786 */
2787
2788 static bool objc_category = false;
2789 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002790 Result += "\nstruct _objc_category {\n";
2791 Result += "\tchar *category_name;\n";
2792 Result += "\tchar *class_name;\n";
2793 Result += "\tstruct _objc_method_list *instance_methods;\n";
2794 Result += "\tstruct _objc_method_list *class_methods;\n";
2795 Result += "\tstruct _objc_protocol_list *protocols;\n";
2796 Result += "\tunsigned int size;\n";
2797 Result += "\tstruct _objc_property_list *instance_properties;\n";
2798 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002799 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002800 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002801 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2802 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002803 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002804 Result += IDecl->getName();
2805 Result += "\"\n\t, \"";
2806 Result += ClassDecl->getName();
2807 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002808
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002809 if (IDecl->getNumInstanceMethods() > 0) {
2810 Result += "\t, (struct _objc_method_list *)"
2811 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2812 Result += FullCategoryName;
2813 Result += "\n";
2814 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002815 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002816 Result += "\t, 0\n";
2817 if (IDecl->getNumClassMethods() > 0) {
2818 Result += "\t, (struct _objc_method_list *)"
2819 "&_OBJC_CATEGORY_CLASS_METHODS_";
2820 Result += FullCategoryName;
2821 Result += "\n";
2822 }
2823 else
2824 Result += "\t, 0\n";
2825
Chris Lattner0be08822008-07-21 21:32:27 +00002826 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002827 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2828 Result += FullCategoryName;
2829 Result += "\n";
2830 }
2831 else
2832 Result += "\t, 0\n";
2833 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002834}
2835
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002836/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2837/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00002838void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00002839 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002840 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00002841 if (ivar->isBitField()) {
2842 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2843 // place all bitfields at offset 0.
2844 Result += "0";
2845 } else {
2846 Result += "__OFFSETOFIVAR__(struct ";
2847 Result += IDecl->getName();
2848 if (LangOpts.Microsoft)
2849 Result += "_IMPL";
2850 Result += ", ";
2851 Result += ivar->getName();
2852 Result += ")";
2853 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002854}
2855
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002856//===----------------------------------------------------------------------===//
2857// Meta Data Emission
2858//===----------------------------------------------------------------------===//
2859
Steve Naroff44e81222008-04-14 22:03:09 +00002860void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002861 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002862 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002863
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002864 // Explictly declared @interface's are already synthesized.
2865 if (CDecl->ImplicitInterfaceDecl()) {
2866 // FIXME: Implementation of a class with no @interface (legacy) doese not
2867 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002868 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002869 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002870
Chris Lattnerc7b06752007-12-12 07:56:42 +00002871 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00002872 unsigned NumIvars = !IDecl->ivar_empty()
2873 ? IDecl->ivar_size()
2874 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002875 if (NumIvars > 0) {
2876 static bool objc_ivar = false;
2877 if (!objc_ivar) {
2878 /* struct _objc_ivar {
2879 char *ivar_name;
2880 char *ivar_type;
2881 int ivar_offset;
2882 };
2883 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002884 Result += "\nstruct _objc_ivar {\n";
2885 Result += "\tchar *ivar_name;\n";
2886 Result += "\tchar *ivar_type;\n";
2887 Result += "\tint ivar_offset;\n";
2888 Result += "};\n";
2889
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002890 objc_ivar = true;
2891 }
2892
Steve Naroffc723eec2008-03-11 00:12:29 +00002893 /* struct {
2894 int ivar_count;
2895 struct _objc_ivar ivar_list[nIvars];
2896 };
2897 */
2898 Result += "\nstatic struct {\n";
2899 Result += "\tint ivar_count;\n";
2900 Result += "\tstruct _objc_ivar ivar_list[";
2901 Result += utostr(NumIvars);
2902 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002903 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002904 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002905 "{\n\t";
2906 Result += utostr(NumIvars);
2907 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002908
Ted Kremenek42730c52008-01-07 19:49:32 +00002909 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00002910 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00002911 IVI = IDecl->ivar_begin();
2912 IVE = IDecl->ivar_end();
2913 } else {
2914 IVI = CDecl->ivar_begin();
2915 IVE = CDecl->ivar_end();
2916 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002917 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002918 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002919 Result += "\", \"";
2920 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002921 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2922 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002923 Result += StrEncoding;
2924 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002925 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002926 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002927 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002928 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002929 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002930 Result += "\", \"";
2931 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002932 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2933 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002934 Result += StrEncoding;
2935 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002936 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002937 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002938 }
2939
2940 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002941 }
2942
2943 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002944 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002945 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002946
2947 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002948 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002949 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002950
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002951 // Protocols referenced in class declaration?
Chris Lattner0be08822008-07-21 21:32:27 +00002952 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002953 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002954
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002955
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002956 // Declaration of class/meta-class metadata
2957 /* struct _objc_class {
2958 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002959 const char *super_class_name;
2960 char *name;
2961 long version;
2962 long info;
2963 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002964 struct _objc_ivar_list *ivars;
2965 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002966 struct objc_cache *cache;
2967 struct objc_protocol_list *protocols;
2968 const char *ivar_layout;
2969 struct _objc_class_ext *ext;
2970 };
2971 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002972 static bool objc_class = false;
2973 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002974 Result += "\nstruct _objc_class {\n";
2975 Result += "\tstruct _objc_class *isa;\n";
2976 Result += "\tconst char *super_class_name;\n";
2977 Result += "\tchar *name;\n";
2978 Result += "\tlong version;\n";
2979 Result += "\tlong info;\n";
2980 Result += "\tlong instance_size;\n";
2981 Result += "\tstruct _objc_ivar_list *ivars;\n";
2982 Result += "\tstruct _objc_method_list *methods;\n";
2983 Result += "\tstruct objc_cache *cache;\n";
2984 Result += "\tstruct _objc_protocol_list *protocols;\n";
2985 Result += "\tconst char *ivar_layout;\n";
2986 Result += "\tstruct _objc_class_ext *ext;\n";
2987 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002988 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002989 }
2990
2991 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002992 ObjCInterfaceDecl *RootClass = 0;
2993 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002994 while (SuperClass) {
2995 RootClass = SuperClass;
2996 SuperClass = SuperClass->getSuperClass();
2997 }
2998 SuperClass = CDecl->getSuperClass();
2999
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003000 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3001 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003002 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003003 "{\n\t(struct _objc_class *)\"";
3004 Result += (RootClass ? RootClass->getName() : CDecl->getName());
3005 Result += "\"";
3006
3007 if (SuperClass) {
3008 Result += ", \"";
3009 Result += SuperClass->getName();
3010 Result += "\", \"";
3011 Result += CDecl->getName();
3012 Result += "\"";
3013 }
3014 else {
3015 Result += ", 0, \"";
3016 Result += CDecl->getName();
3017 Result += "\"";
3018 }
Ted Kremenek42730c52008-01-07 19:49:32 +00003019 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003020 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003021 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00003022 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003023 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00003024 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003025 Result += "\n";
3026 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003027 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003028 Result += ", 0\n";
Chris Lattner8bcb5252008-07-21 18:19:38 +00003029 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff27429432008-03-12 01:06:30 +00003030 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003031 Result += CDecl->getName();
3032 Result += ",0,0\n";
3033 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003034 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003035 Result += "\t,0,0,0,0\n";
3036 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003037
3038 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003039 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3040 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003041 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003042 "{\n\t&_OBJC_METACLASS_";
3043 Result += CDecl->getName();
3044 if (SuperClass) {
3045 Result += ", \"";
3046 Result += SuperClass->getName();
3047 Result += "\", \"";
3048 Result += CDecl->getName();
3049 Result += "\"";
3050 }
3051 else {
3052 Result += ", 0, \"";
3053 Result += CDecl->getName();
3054 Result += "\"";
3055 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003056 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003057 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003058 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003059 Result += ",0";
3060 else {
3061 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003062 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003063 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003064 if (LangOpts.Microsoft)
3065 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003066 Result += ")";
3067 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003068 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003069 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003070 Result += CDecl->getName();
3071 Result += "\n\t";
3072 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003073 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003074 Result += ",0";
3075 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003076 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003077 Result += CDecl->getName();
3078 Result += ", 0\n\t";
3079 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003080 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003081 Result += ",0,0";
Chris Lattner8bcb5252008-07-21 18:19:38 +00003082 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff27429432008-03-12 01:06:30 +00003083 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003084 Result += CDecl->getName();
3085 Result += ", 0,0\n";
3086 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003087 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003088 Result += ",0,0,0\n";
3089 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003090}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003091
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003092/// RewriteImplementations - This routine rewrites all method implementations
3093/// and emits meta-data.
3094
Steve Naroff44e81222008-04-14 22:03:09 +00003095void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003096 int ClsDefCount = ClassImplementation.size();
3097 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003098
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003099 if (ClsDefCount == 0 && CatDefCount == 0)
3100 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003101 // Rewrite implemented methods
3102 for (int i = 0; i < ClsDefCount; i++)
3103 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003104
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003105 for (int i = 0; i < CatDefCount; i++)
3106 RewriteImplementationDecl(CategoryImplementation[i]);
3107
Steve Naroff5bf10222008-05-07 21:23:49 +00003108 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003109 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003110 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003111 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003112 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003113
3114 // For each implemented category, write out all its meta data.
3115 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003116 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003117
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003118 // Write objc_symtab metadata
3119 /*
3120 struct _objc_symtab
3121 {
3122 long sel_ref_cnt;
3123 SEL *refs;
3124 short cls_def_cnt;
3125 short cat_def_cnt;
3126 void *defs[cls_def_cnt + cat_def_cnt];
3127 };
3128 */
3129
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003130 Result += "\nstruct _objc_symtab {\n";
3131 Result += "\tlong sel_ref_cnt;\n";
3132 Result += "\tSEL *refs;\n";
3133 Result += "\tshort cls_def_cnt;\n";
3134 Result += "\tshort cat_def_cnt;\n";
3135 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3136 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003137
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003138 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003139 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003140 Result += "\t0, 0, " + utostr(ClsDefCount)
3141 + ", " + utostr(CatDefCount) + "\n";
3142 for (int i = 0; i < ClsDefCount; i++) {
3143 Result += "\t,&_OBJC_CLASS_";
3144 Result += ClassImplementation[i]->getName();
3145 Result += "\n";
3146 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003147
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003148 for (int i = 0; i < CatDefCount; i++) {
3149 Result += "\t,&_OBJC_CATEGORY_";
3150 Result += CategoryImplementation[i]->getClassInterface()->getName();
3151 Result += "_";
3152 Result += CategoryImplementation[i]->getName();
3153 Result += "\n";
3154 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003155
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003156 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003157
3158 // Write objc_module metadata
3159
3160 /*
3161 struct _objc_module {
3162 long version;
3163 long size;
3164 const char *name;
3165 struct _objc_symtab *symtab;
3166 }
3167 */
3168
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003169 Result += "\nstruct _objc_module {\n";
3170 Result += "\tlong version;\n";
3171 Result += "\tlong size;\n";
3172 Result += "\tconst char *name;\n";
3173 Result += "\tstruct _objc_symtab *symtab;\n";
3174 Result += "};\n\n";
3175 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003176 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003177 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3178 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003179 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003180
3181 if (LangOpts.Microsoft) {
3182 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003183 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003184 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3185 Result += "&_OBJC_MODULES;\n";
3186 Result += "#pragma data_seg(pop)\n\n";
3187 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003188}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003189
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003190
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003191
3192