blob: fe71e54a86b784d0494375c1f6eda5433610c88c [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 Naroffc8a92d12007-11-01 13:24:47 +0000166 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000167 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000168 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000169 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000170 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000171
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000172 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000173 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000174 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000175 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff296b74f2007-11-05 14:50:49 +0000176 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000177 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000178 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000179 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000180 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000181 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000182 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
183 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
184 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000185 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
186 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000187 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
188 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000189 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000190 Stmt *RewriteBreakStmt(BreakStmt *S);
191 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000192 void SynthCountByEnumWithState(std::string &buf);
193
Steve Naroff02a82aa2007-10-30 23:14:51 +0000194 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000195 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000196 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000197 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000198 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000199 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000200 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000201 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000202 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000203 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000204
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000205 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000206 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000207 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000208
Ted Kremenek42730c52008-01-07 19:49:32 +0000209 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000210 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000211
Ted Kremenek42730c52008-01-07 19:49:32 +0000212 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
213 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000214 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000215 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000216 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000217 const char *ClassName,
218 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000219
Ted Kremenek42730c52008-01-07 19:49:32 +0000220 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000221 int NumProtocols,
222 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000223 const char *ClassName,
224 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000225 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000226 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000227 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
228 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000229 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000230 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000231 };
232}
233
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000234static bool IsHeaderFile(const std::string &Filename) {
235 std::string::size_type DotPos = Filename.rfind('.');
236
237 if (DotPos == std::string::npos) {
238 // no file extension
239 return false;
240 }
241
242 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
243 // C header: .h
244 // C++ header: .hh or .H;
245 return Ext == "h" || Ext == "hh" || Ext == "H";
246}
247
Steve Naroff44e81222008-04-14 22:03:09 +0000248RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000249 Diagnostic &D, const LangOptions &LOpts)
250 : Diags(D), LangOpts(LOpts) {
251 IsHeader = IsHeaderFile(inFile);
252 InFileName = inFile;
253 OutFileName = outFile;
254 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
255 "rewriting sub-expression within a macro (may not be correct)");
256}
257
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000258ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000259 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000260 Diagnostic &Diags,
261 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000262 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000263}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000264
Steve Naroff44e81222008-04-14 22:03:09 +0000265void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000266 Context = &context;
267 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000268 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000269 MsgSendFunctionDecl = 0;
270 MsgSendSuperFunctionDecl = 0;
271 MsgSendStretFunctionDecl = 0;
272 MsgSendSuperStretFunctionDecl = 0;
273 MsgSendFpretFunctionDecl = 0;
274 GetClassFunctionDecl = 0;
275 GetMetaClassFunctionDecl = 0;
276 SelGetUidFunctionDecl = 0;
277 CFStringFunctionDecl = 0;
278 GetProtocolFunctionDecl = 0;
279 ConstantStringClassReference = 0;
280 NSStringRecord = 0;
281 CurMethodDecl = 0;
282 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000283 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000284 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000285 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000286 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000287
288 // Get the ID and start/end of the main file.
289 MainFileID = SM->getMainFileID();
290 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
291 MainFileStart = MainBuf->getBufferStart();
292 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000293
Chris Lattner12499682008-01-31 19:38:44 +0000294 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000295
Chris Lattner12499682008-01-31 19:38:44 +0000296 // declaring objc_selector outside the parameter list removes a silly
297 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000298 if (IsHeader)
299 Preamble = "#pragma once\n";
300 Preamble += "struct objc_selector; struct objc_class;\n";
301 Preamble += "#ifndef OBJC_SUPER\n";
302 Preamble += "struct objc_super { struct objc_object *object; ";
303 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000304 if (LangOpts.Microsoft) {
305 // Add a constructor for creating temporary objects.
Steve Narofffef037c2008-03-27 22:29:16 +0000306 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
307 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000308 }
Steve Narofffef037c2008-03-27 22:29:16 +0000309 Preamble += "};\n";
310 Preamble += "#define OBJC_SUPER\n";
311 Preamble += "#endif\n";
312 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
313 Preamble += "typedef struct objc_object Protocol;\n";
314 Preamble += "#define _REWRITER_typedef_Protocol\n";
315 Preamble += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000316 if (LangOpts.Microsoft)
Steve Naroff618c6a42008-05-06 22:45:19 +0000317 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
318 else
319 Preamble += "#define __OBJC_RW_EXTERN extern\n";
320 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000321 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000322 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000323 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000324 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000325 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000326 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000327 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff31316a12008-05-08 22:02:18 +0000328 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000329 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroffa9636222008-05-08 17:52:16 +0000330 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000331 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000332 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000333 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000334 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
335 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
336 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
337 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
338 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000339 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000340 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000341 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
342 Preamble += "struct __objcFastEnumerationState {\n\t";
343 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000344 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000345 Preamble += "unsigned long *mutationsPtr;\n\t";
346 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff37157242008-06-02 20:23:21 +0000347 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000348 Preamble += "#define __FASTENUMERATIONSTATE\n";
349 Preamble += "#endif\n";
350 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
351 Preamble += "struct __NSConstantStringImpl {\n";
352 Preamble += " int *isa;\n";
353 Preamble += " int flags;\n";
354 Preamble += " char *str;\n";
355 Preamble += " long length;\n";
356 Preamble += "};\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000357 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000358 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
359 Preamble += "#endif\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000360 if (LangOpts.Microsoft) {
361 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000362 Preamble += "#define __attribute__(X)\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000363 }
Chris Lattner12499682008-01-31 19:38:44 +0000364}
365
366
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000367//===----------------------------------------------------------------------===//
368// Top Level Driver Code
369//===----------------------------------------------------------------------===//
370
Steve Naroff44e81222008-04-14 22:03:09 +0000371void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000372 // Two cases: either the decl could be in the main file, or it could be in a
373 // #included file. If the former, rewrite it now. If the later, check to see
374 // if we rewrote the #include/#import.
375 SourceLocation Loc = D->getLocation();
376 Loc = SM->getLogicalLoc(Loc);
377
378 // If this is for a builtin, ignore it.
379 if (Loc.isInvalid()) return;
380
Steve Naroffe9780582007-10-23 23:50:29 +0000381 // Look for built-in declarations that we need to refer during the rewrite.
382 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000383 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000384 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000385 // declared in <Foundation/NSString.h>
386 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
387 ConstantStringClassReference = FVD;
388 return;
389 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000390 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000391 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000392 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000393 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000394 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000395 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000396 } else if (ObjCForwardProtocolDecl *FP =
397 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000398 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000399 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000400 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000401 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000402 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000403}
404
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000405/// HandleDeclInMainFile - This is called for each top-level decl defined in the
406/// main file of the input.
Steve Naroff44e81222008-04-14 22:03:09 +0000407void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000408 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
409 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000410 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000411
Ted Kremenek42730c52008-01-07 19:49:32 +0000412 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000413 if (Stmt *Body = MD->getBody()) {
414 //Body->dump();
415 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000416 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000417 CurMethodDecl = 0;
418 }
Steve Naroff18c83382007-11-13 23:01:27 +0000419 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000420 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000421 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000422 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000423 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000424 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000425 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000426 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000427 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000428 if (VD->getInit())
429 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
430 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000431 // Nothing yet.
432}
433
Steve Naroff44e81222008-04-14 22:03:09 +0000434RewriteObjC::~RewriteObjC() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000435 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000436
437 // Rewrite tabs if we care.
438 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000439
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000440 if (Diags.hasErrorOccurred())
441 return;
442
443 // Create the output file.
444
445 std::ostream *OutFile;
446 if (OutFileName == "-") {
447 OutFile = llvm::cout.stream();
448 } else if (!OutFileName.empty()) {
449 OutFile = new std::ofstream(OutFileName.c_str(),
450 std::ios_base::binary|std::ios_base::out);
451 } else if (InFileName == "-") {
452 OutFile = llvm::cout.stream();
453 } else {
454 llvm::sys::Path Path(InFileName);
455 Path.eraseSuffix();
456 Path.appendSuffix("cpp");
457 OutFile = new std::ofstream(Path.toString().c_str(),
458 std::ios_base::binary|std::ios_base::out);
459 }
460
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000461 RewriteInclude();
462
Steve Narofffef037c2008-03-27 22:29:16 +0000463 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
464 Preamble.c_str(), Preamble.size(), false);
465
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000466 // Rewrite Objective-c meta data*
467 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000468 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000469
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000470 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
471 // we are done.
472 if (const RewriteBuffer *RewriteBuf =
473 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000474 //printf("Changed:\n");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000475 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000476 } else {
Chris Lattner673f2bd2008-03-22 00:08:40 +0000477 fprintf(stderr, "No changes\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000478 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000479 // Emit metadata.
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000480 *OutFile << ResultStr;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000481}
482
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000483//===----------------------------------------------------------------------===//
484// Syntactic (non-AST) Rewriting Code
485//===----------------------------------------------------------------------===//
486
Steve Naroff44e81222008-04-14 22:03:09 +0000487void RewriteObjC::RewriteInclude() {
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000488 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
489 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
490 const char *MainBufStart = MainBuf.first;
491 const char *MainBufEnd = MainBuf.second;
492 size_t ImportLen = strlen("import");
493 size_t IncludeLen = strlen("include");
494
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000495 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000496 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
497 if (*BufPtr == '#') {
498 if (++BufPtr == MainBufEnd)
499 return;
500 while (*BufPtr == ' ' || *BufPtr == '\t')
501 if (++BufPtr == MainBufEnd)
502 return;
503 if (!strncmp(BufPtr, "import", ImportLen)) {
504 // replace import with include
505 SourceLocation ImportLoc =
506 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000507 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000508 BufPtr += ImportLen;
509 }
510 }
511 }
Chris Lattner74db1682007-10-16 21:07:07 +0000512}
513
Steve Naroff44e81222008-04-14 22:03:09 +0000514void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000515 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
516 const char *MainBufStart = MainBuf.first;
517 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000518
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000519 // Loop over the whole file, looking for tabs.
520 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
521 if (*BufPtr != '\t')
522 continue;
523
524 // Okay, we found a tab. This tab will turn into at least one character,
525 // but it depends on which 'virtual column' it is in. Compute that now.
526 unsigned VCol = 0;
527 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
528 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
529 ++VCol;
530
531 // Okay, now that we know the virtual column, we know how many spaces to
532 // insert. We assume 8-character tab-stops.
533 unsigned Spaces = 8-(VCol & 7);
534
535 // Get the location of the tab.
536 SourceLocation TabLoc =
537 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
538
539 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000540 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000541 }
Chris Lattner569faa62007-10-11 18:38:32 +0000542}
543
544
Steve Naroff44e81222008-04-14 22:03:09 +0000545void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000546 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000547 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000548
549 // Get the start location and compute the semi location.
550 SourceLocation startLoc = ClassDecl->getLocation();
551 const char *startBuf = SM->getCharacterData(startLoc);
552 const char *semiPtr = strchr(startBuf, ';');
553
554 // Translate to typedef's that forward reference structs with the same name
555 // as the class. As a convenience, we include the original declaration
556 // as a comment.
557 std::string typedefString;
558 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000559 typedefString.append(startBuf, semiPtr-startBuf+1);
560 typedefString += "\n";
561 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000562 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000563 typedefString += "#ifndef _REWRITER_typedef_";
564 typedefString += ForwardDecl->getName();
565 typedefString += "\n";
566 typedefString += "#define _REWRITER_typedef_";
567 typedefString += ForwardDecl->getName();
568 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000569 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000570 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000571 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000572 }
573
574 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000575 ReplaceText(startLoc, semiPtr-startBuf+1,
576 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000577}
578
Steve Naroff44e81222008-04-14 22:03:09 +0000579void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000580 SourceLocation LocStart = Method->getLocStart();
581 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000582
Steve Naroff2ce399a2007-12-14 23:37:57 +0000583 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattner6216f292008-01-31 19:42:41 +0000584 InsertText(LocStart, "/* ", 3);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000585 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000586 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000587 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000588 }
589}
590
Steve Naroff44e81222008-04-14 22:03:09 +0000591void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000592{
Chris Lattnercffe3662008-03-16 21:23:50 +0000593 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000594 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000595 SourceLocation Loc = Property->getLocation();
596
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000597 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000598
599 // FIXME: handle properties that are declared across multiple lines.
600 }
601}
602
Steve Naroff44e81222008-04-14 22:03:09 +0000603void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000604 SourceLocation LocStart = CatDecl->getLocStart();
605
606 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000607 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000608
Ted Kremenek42730c52008-01-07 19:49:32 +0000609 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000610 E = CatDecl->instmeth_end(); I != E; ++I)
611 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000612 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000613 E = CatDecl->classmeth_end(); I != E; ++I)
614 RewriteMethodDeclaration(*I);
615
Steve Naroff667f1682007-10-30 13:30:57 +0000616 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000617 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000618}
619
Steve Naroff44e81222008-04-14 22:03:09 +0000620void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000621 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000622
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000623 SourceLocation LocStart = PDecl->getLocStart();
624
625 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000626 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000627
Ted Kremenek42730c52008-01-07 19:49:32 +0000628 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000629 E = PDecl->instmeth_end(); I != E; ++I)
630 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000631 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000632 E = PDecl->classmeth_end(); I != E; ++I)
633 RewriteMethodDeclaration(*I);
634
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000635 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000636 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000637 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000638
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000639 // Must comment out @optional/@required
640 const char *startBuf = SM->getCharacterData(LocStart);
641 const char *endBuf = SM->getCharacterData(LocEnd);
642 for (const char *p = startBuf; p < endBuf; p++) {
643 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
644 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000645 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000646 ReplaceText(OptionalLoc, strlen("@optional"),
647 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000648
649 }
650 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
651 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000652 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000653 ReplaceText(OptionalLoc, strlen("@required"),
654 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000655
656 }
657 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000658}
659
Steve Naroff44e81222008-04-14 22:03:09 +0000660void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000661 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000662 if (LocStart.isInvalid())
663 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000664 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000665 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000666}
667
Steve Naroff44e81222008-04-14 22:03:09 +0000668void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000669 std::string &ResultStr) {
670 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000671 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000672 ResultStr += "id";
673 else
674 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000675 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000676
677 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000678 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000679
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000680 if (OMD->isInstance())
681 NameStr += "_I_";
682 else
683 NameStr += "_C_";
684
685 NameStr += OMD->getClassInterface()->getName();
686 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000687
688 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000689 if (ObjCCategoryImplDecl *CID =
690 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000691 NameStr += CID->getName();
692 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000693 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000694 // Append selector names, replacing ':' with '_'
695 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000696 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000697 else {
698 std::string selString = OMD->getSelector().getName();
699 int len = selString.size();
700 for (int i = 0; i < len; i++)
701 if (selString[i] == ':')
702 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000703 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000704 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000705 // Remember this name for metadata emission
706 MethodInternalNames[OMD] = NameStr;
707 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000708
709 // Rewrite arguments
710 ResultStr += "(";
711
712 // invisible arguments
713 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000714 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000715 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000716 if (!LangOpts.Microsoft) {
717 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
718 ResultStr += "struct ";
719 }
720 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroffde0da102008-03-10 23:16:54 +0000721 ResultStr += OMD->getClassInterface()->getName();
Steve Naroffde0da102008-03-10 23:16:54 +0000722 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000723 }
724 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000725 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000726
727 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000728 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000729 ResultStr += " _cmd";
730
731 // Method arguments.
Chris Lattner685d7922008-03-16 01:07:14 +0000732 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000733 ParmVarDecl *PDecl = OMD->getParamDecl(i);
734 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000735 if (PDecl->getType()->isObjCQualifiedIdType()) {
736 ResultStr += "id ";
737 ResultStr += PDecl->getName();
738 } else {
739 std::string Name = PDecl->getName();
740 PDecl->getType().getAsStringInternal(Name);
741 ResultStr += Name;
742 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000743 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000744 if (OMD->isVariadic())
745 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000746 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000747
748}
Steve Naroff44e81222008-04-14 22:03:09 +0000749void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000750 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
751 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000752
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000753 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000754 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000755 else
Chris Lattner6216f292008-01-31 19:42:41 +0000756 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000757
Ted Kremenek42730c52008-01-07 19:49:32 +0000758 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000759 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
760 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000761 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000762 ObjCMethodDecl *OMD = *I;
763 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000764 SourceLocation LocStart = OMD->getLocStart();
765 SourceLocation LocEnd = OMD->getBody()->getLocStart();
766
767 const char *startBuf = SM->getCharacterData(LocStart);
768 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000769 ReplaceText(LocStart, endBuf-startBuf,
770 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000771 }
772
Ted Kremenek42730c52008-01-07 19:49:32 +0000773 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000774 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
775 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000776 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000777 ObjCMethodDecl *OMD = *I;
778 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000779 SourceLocation LocStart = OMD->getLocStart();
780 SourceLocation LocEnd = OMD->getBody()->getLocStart();
781
782 const char *startBuf = SM->getCharacterData(LocStart);
783 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000784 ReplaceText(LocStart, endBuf-startBuf,
785 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000786 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000787 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000788 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000789 else
Chris Lattner6216f292008-01-31 19:42:41 +0000790 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000791}
792
Steve Naroff44e81222008-04-14 22:03:09 +0000793void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000794 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000795 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000796 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000797 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000798 ResultStr += ClassDecl->getName();
799 ResultStr += "\n";
800 ResultStr += "#define _REWRITER_typedef_";
801 ResultStr += ClassDecl->getName();
802 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000803 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000804 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000805 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000806 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000807 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000808 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000809 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000810
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000811 RewriteProperties(ClassDecl->getNumPropertyDecl(),
812 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000813 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000814 E = ClassDecl->instmeth_end(); I != E; ++I)
815 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000816 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000817 E = ClassDecl->classmeth_end(); I != E; ++I)
818 RewriteMethodDeclaration(*I);
819
Steve Naroff1ccf4632007-10-30 03:43:13 +0000820 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000821 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000822}
823
Chris Lattner343c82b2008-05-23 20:40:52 +0000824Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
825 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000826 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000827 if (CurMethodDecl) {
828 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000829 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
830 // lookup which class implements the instance variable.
831 ObjCInterfaceDecl *clsDeclared = 0;
832 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
833 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
834
835 // Synthesize an explicit cast to gain access to the ivar.
836 std::string RecName = clsDeclared->getIdentifier()->getName();
837 RecName += "_IMPL";
838 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000839 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Steve Naroffa9636222008-05-08 17:52:16 +0000840 SourceLocation(), II, 0);
841 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
842 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
843 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
844 // Don't forget the parens to enforce the proper binding.
Chris Lattner343c82b2008-05-23 20:40:52 +0000845 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
846 IV->getBase()->getLocEnd(),
847 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +0000848 if (IV->isFreeIvar() &&
849 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner343c82b2008-05-23 20:40:52 +0000850 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
851 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +0000852 ReplaceStmt(IV, ME);
853 delete IV;
854 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +0000855 }
Chris Lattner343c82b2008-05-23 20:40:52 +0000856
857 ReplaceStmt(IV->getBase(), PE);
858 // Cannot delete IV->getBase(), since PE points to it.
859 // Replace the old base with the cast. This is important when doing
860 // embedded rewrites. For example, [newInv->_container addObject:0].
861 IV->setBase(PE);
862 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000863 }
Steve Naroffe6155362008-04-18 21:55:08 +0000864 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +0000865 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
866
867 // Explicit ivar refs need to have a cast inserted.
868 // FIXME: consider sharing some of this code with the code above.
869 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000870 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +0000871 // lookup which class implements the instance variable.
872 ObjCInterfaceDecl *clsDeclared = 0;
Steve Naroffa9636222008-05-08 17:52:16 +0000873 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000874 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
875
876 // Synthesize an explicit cast to gain access to the ivar.
877 std::string RecName = clsDeclared->getIdentifier()->getName();
878 RecName += "_IMPL";
879 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000880 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Steve Naroffd8d30b92008-05-06 23:20:07 +0000881 SourceLocation(), II, 0);
882 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
883 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
884 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
885 // Don't forget the parens to enforce the proper binding.
Chris Lattner3cca6612008-05-28 16:38:23 +0000886 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
887 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000888 ReplaceStmt(IV->getBase(), PE);
889 // Cannot delete IV->getBase(), since PE points to it.
890 // Replace the old base with the cast. This is important when doing
891 // embedded rewrites. For example, [newInv->_container addObject:0].
892 IV->setBase(PE);
893 return IV;
894 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000895 }
Steve Naroffe6155362008-04-18 21:55:08 +0000896 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000897}
898
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000899//===----------------------------------------------------------------------===//
900// Function Body / Expression rewriting
901//===----------------------------------------------------------------------===//
902
Steve Naroff44e81222008-04-14 22:03:09 +0000903Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000904 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
905 isa<DoStmt>(S) || isa<ForStmt>(S))
906 Stmts.push_back(S);
907 else if (isa<ObjCForCollectionStmt>(S)) {
908 Stmts.push_back(S);
909 ObjCBcLabelNo.push_back(++BcLabelCount);
910 }
911
Chris Lattner343c82b2008-05-23 20:40:52 +0000912 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner2c022162008-01-31 05:10:40 +0000913
914 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000915 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
916 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000917 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000918 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000919 if (newStmt)
920 *CI = newStmt;
921 }
Steve Naroffe9780582007-10-23 23:50:29 +0000922
923 // Handle specific things.
924 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
925 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000926
927 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner343c82b2008-05-23 20:40:52 +0000928 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroff296b74f2007-11-05 14:50:49 +0000929
930 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
931 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000932
Steve Naroff0add5d22007-11-03 11:27:19 +0000933 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
934 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000935
Steve Naroff71226032007-10-24 22:48:43 +0000936 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
937 // Before we rewrite it, put the original message expression in a comment.
938 SourceLocation startLoc = MessExpr->getLocStart();
939 SourceLocation endLoc = MessExpr->getLocEnd();
940
941 const char *startBuf = SM->getCharacterData(startLoc);
942 const char *endBuf = SM->getCharacterData(endLoc);
943
944 std::string messString;
945 messString += "// ";
946 messString.append(startBuf, endBuf-startBuf+1);
947 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000948
Chris Lattner6216f292008-01-31 19:42:41 +0000949 // FIXME: Missing definition of
950 // InsertText(clang::SourceLocation, char const*, unsigned int).
951 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff71226032007-10-24 22:48:43 +0000952 // Tried this, but it didn't work either...
Chris Lattner6216f292008-01-31 19:42:41 +0000953 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000954 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000955 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000956
Ted Kremenek42730c52008-01-07 19:49:32 +0000957 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
958 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000959
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000960 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
961 return RewriteObjCSynchronizedStmt(StmtTry);
962
Ted Kremenek42730c52008-01-07 19:49:32 +0000963 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
964 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000965
966 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
967 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000968
969 if (ObjCForCollectionStmt *StmtForCollection =
970 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner343c82b2008-05-23 20:40:52 +0000971 return RewriteObjCForCollectionStmt(StmtForCollection,
972 OrigStmtRange.getEnd());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000973 if (BreakStmt *StmtBreakStmt =
974 dyn_cast<BreakStmt>(S))
975 return RewriteBreakStmt(StmtBreakStmt);
976 if (ContinueStmt *StmtContinueStmt =
977 dyn_cast<ContinueStmt>(S))
978 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000979
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000980 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
981 isa<DoStmt>(S) || isa<ForStmt>(S)) {
982 assert(!Stmts.empty() && "Statement stack is empty");
983 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
984 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
985 && "Statement stack mismatch");
986 Stmts.pop_back();
987 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000988#if 0
989 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
990 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
991 // Get the new text.
992 std::ostringstream Buf;
993 Replacement->printPretty(Buf);
994 const std::string &Str = Buf.str();
995
996 printf("CAST = %s\n", &Str[0]);
Chris Lattner6216f292008-01-31 19:42:41 +0000997 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff764c1ae2007-11-15 10:28:18 +0000998 delete S;
999 return Replacement;
1000 }
1001#endif
Chris Lattner0021f452007-10-24 16:57:36 +00001002 // Return this stmt unmodified.
1003 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001004}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001005
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001006/// SynthCountByEnumWithState - To print:
1007/// ((unsigned int (*)
1008/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1009/// (void *)objc_msgSend)((id)l_collection,
1010/// sel_registerName(
1011/// "countByEnumeratingWithState:objects:count:"),
1012/// &enumState,
1013/// (id *)items, (unsigned int)16)
1014///
Steve Naroff44e81222008-04-14 22:03:09 +00001015void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001016 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1017 "id *, unsigned int))(void *)objc_msgSend)";
1018 buf += "\n\t\t";
1019 buf += "((id)l_collection,\n\t\t";
1020 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1021 buf += "\n\t\t";
1022 buf += "&enumState, "
1023 "(id *)items, (unsigned int)16)";
1024}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001025
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001026/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1027/// statement to exit to its outer synthesized loop.
1028///
Steve Naroff44e81222008-04-14 22:03:09 +00001029Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001030 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1031 return S;
1032 // replace break with goto __break_label
1033 std::string buf;
1034
1035 SourceLocation startLoc = S->getLocStart();
1036 buf = "goto __break_label_";
1037 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001038 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001039
1040 return 0;
1041}
1042
1043/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1044/// statement to continue with its inner synthesized loop.
1045///
Steve Naroff44e81222008-04-14 22:03:09 +00001046Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001047 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1048 return S;
1049 // replace continue with goto __continue_label
1050 std::string buf;
1051
1052 SourceLocation startLoc = S->getLocStart();
1053 buf = "goto __continue_label_";
1054 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001055 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001056
1057 return 0;
1058}
1059
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001060/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001061/// It rewrites:
1062/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001063
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001064/// Into:
1065/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001066/// type elem;
1067/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001068/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001069/// id l_collection = (id)collection;
1070/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1071/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001072/// if (limit) {
1073/// unsigned long startMutations = *enumState.mutationsPtr;
1074/// do {
1075/// unsigned long counter = 0;
1076/// do {
1077/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001078/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001079/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001080/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001081/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001082/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001083/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1084/// objects:items count:16]);
1085/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001086/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001087/// }
1088/// else
1089/// elem = nil;
1090/// }
1091///
Steve Naroff44e81222008-04-14 22:03:09 +00001092Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001093 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001094 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1095 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1096 "ObjCForCollectionStmt Statement stack mismatch");
1097 assert(!ObjCBcLabelNo.empty() &&
1098 "ObjCForCollectionStmt - Label No stack empty");
1099
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001100 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001101 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001102 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001103 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001104 std::string buf;
1105 buf = "\n{\n\t";
1106 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1107 // type elem;
1108 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001109 elementTypeAsString = ElementType.getAsString();
1110 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001111 buf += " ";
1112 elementName = DS->getDecl()->getName();
1113 buf += elementName;
1114 buf += ";\n\t";
1115 }
Chris Lattner690c2872008-04-08 05:52:18 +00001116 else {
1117 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001118 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001119 elementTypeAsString = DR->getDecl()->getType().getAsString();
1120 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001121
1122 // struct __objcFastEnumerationState enumState = { 0 };
1123 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1124 // id items[16];
1125 buf += "id items[16];\n\t";
1126 // id l_collection = (id)
1127 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001128 // Find start location of 'collection' the hard way!
1129 const char *startCollectionBuf = startBuf;
1130 startCollectionBuf += 3; // skip 'for'
1131 startCollectionBuf = strchr(startCollectionBuf, '(');
1132 startCollectionBuf++; // skip '('
1133 // find 'in' and skip it.
1134 while (*startCollectionBuf != ' ' ||
1135 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1136 (*(startCollectionBuf+3) != ' ' &&
1137 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1138 startCollectionBuf++;
1139 startCollectionBuf += 3;
1140
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001141 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001142 ReplaceText(startLoc, startCollectionBuf - startBuf,
1143 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001144 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001145 SourceLocation rightParenLoc = S->getRParenLoc();
1146 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1147 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001148 buf = ";\n\t";
1149
1150 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1151 // objects:items count:16];
1152 // which is synthesized into:
1153 // unsigned int limit =
1154 // ((unsigned int (*)
1155 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1156 // (void *)objc_msgSend)((id)l_collection,
1157 // sel_registerName(
1158 // "countByEnumeratingWithState:objects:count:"),
1159 // (struct __objcFastEnumerationState *)&state,
1160 // (id *)items, (unsigned int)16);
1161 buf += "unsigned long limit =\n\t\t";
1162 SynthCountByEnumWithState(buf);
1163 buf += ";\n\t";
1164 /// if (limit) {
1165 /// unsigned long startMutations = *enumState.mutationsPtr;
1166 /// do {
1167 /// unsigned long counter = 0;
1168 /// do {
1169 /// if (startMutations != *enumState.mutationsPtr)
1170 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001171 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001172 buf += "if (limit) {\n\t";
1173 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1174 buf += "do {\n\t\t";
1175 buf += "unsigned long counter = 0;\n\t\t";
1176 buf += "do {\n\t\t\t";
1177 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1178 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1179 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001180 buf += " = (";
1181 buf += elementTypeAsString;
1182 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001183 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001184 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001185
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001186 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001187 /// } while (counter < limit);
1188 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1189 /// objects:items count:16]);
1190 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001191 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001192 /// }
1193 /// else
1194 /// elem = nil;
1195 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001196 ///
1197 buf = ";\n\t";
1198 buf += "__continue_label_";
1199 buf += utostr(ObjCBcLabelNo.back());
1200 buf += ": ;";
1201 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001202 buf += "} while (counter < limit);\n\t";
1203 buf += "} while (limit = ";
1204 SynthCountByEnumWithState(buf);
1205 buf += ");\n\t";
1206 buf += elementName;
1207 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001208 buf += "__break_label_";
1209 buf += utostr(ObjCBcLabelNo.back());
1210 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001211 buf += "}\n\t";
1212 buf += "else\n\t\t";
1213 buf += elementName;
1214 buf += " = nil;\n";
1215 buf += "}\n";
1216 // Insert all these *after* the statement body.
Chris Lattner2c022162008-01-31 05:10:40 +00001217 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattner6216f292008-01-31 19:42:41 +00001218 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001219 Stmts.pop_back();
1220 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001221 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001222}
1223
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001224/// RewriteObjCSynchronizedStmt -
1225/// This routine rewrites @synchronized(expr) stmt;
1226/// into:
1227/// objc_sync_enter(expr);
1228/// @try stmt @finally { objc_sync_exit(expr); }
1229///
Steve Naroff44e81222008-04-14 22:03:09 +00001230Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001231 // Get the start location and compute the semi location.
1232 SourceLocation startLoc = S->getLocStart();
1233 const char *startBuf = SM->getCharacterData(startLoc);
1234
1235 assert((*startBuf == '@') && "bogus @synchronized location");
1236
1237 std::string buf;
1238 buf = "objc_sync_enter";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001239 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001240 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1241 const char *endBuf = SM->getCharacterData(endLoc);
1242 endBuf++;
1243 const char *rparenBuf = strchr(endBuf, ')');
1244 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1245 buf = ");\n";
1246 // declare a new scope with two variables, _stack and _rethrow.
1247 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1248 buf += "int buf[18/*32-bit i386*/];\n";
1249 buf += "char *pointers[4];} _stack;\n";
1250 buf += "id volatile _rethrow = 0;\n";
1251 buf += "objc_exception_try_enter(&_stack);\n";
1252 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001253 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001254 startLoc = S->getSynchBody()->getLocEnd();
1255 startBuf = SM->getCharacterData(startLoc);
1256
1257 assert((*startBuf == '}') && "bogus @try block");
1258 SourceLocation lastCurlyLoc = startLoc;
1259 buf = "}\nelse {\n";
1260 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1261 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1262 // FIXME: This must be objc_sync_exit(syncExpr);
1263 buf += " objc_sync_exit();\n";
1264 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1265 buf += "}\n";
1266 buf += "}";
1267
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001268 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001269 return 0;
1270}
1271
Steve Naroff44e81222008-04-14 22:03:09 +00001272Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001273 // Get the start location and compute the semi location.
1274 SourceLocation startLoc = S->getLocStart();
1275 const char *startBuf = SM->getCharacterData(startLoc);
1276
1277 assert((*startBuf == '@') && "bogus @try location");
1278
1279 std::string buf;
1280 // declare a new scope with two variables, _stack and _rethrow.
1281 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1282 buf += "int buf[18/*32-bit i386*/];\n";
1283 buf += "char *pointers[4];} _stack;\n";
1284 buf += "id volatile _rethrow = 0;\n";
1285 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001286 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001287
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001288 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001289
1290 startLoc = S->getTryBody()->getLocEnd();
1291 startBuf = SM->getCharacterData(startLoc);
1292
1293 assert((*startBuf == '}') && "bogus @try block");
1294
1295 SourceLocation lastCurlyLoc = startLoc;
1296
1297 startLoc = startLoc.getFileLocWithOffset(1);
1298 buf = " /* @catch begin */ else {\n";
1299 buf += " id _caught = objc_exception_extract(&_stack);\n";
1300 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001301 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001302 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1303 buf += " else { /* @catch continue */";
1304
Chris Lattner6216f292008-01-31 19:42:41 +00001305 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001306
1307 bool sawIdTypedCatch = false;
1308 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001309 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001310 while (catchList) {
1311 Stmt *catchStmt = catchList->getCatchParamStmt();
1312
1313 if (catchList == S->getCatchStmts())
1314 buf = "if ("; // we are generating code for the first catch clause
1315 else
1316 buf = "else if (";
1317 startLoc = catchList->getLocStart();
1318 startBuf = SM->getCharacterData(startLoc);
1319
1320 assert((*startBuf == '@') && "bogus @catch location");
1321
1322 const char *lParenLoc = strchr(startBuf, '(');
1323
Steve Naroff397c4ce2008-02-01 22:08:12 +00001324 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001325 // Now rewrite the body...
1326 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001327 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1328 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001329 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1330 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001331 assert((*bodyBuf == '{') && "bogus @catch body location");
1332
1333 buf += "1) { id _tmp = _caught;";
1334 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1335 buf.c_str(), buf.size());
1336 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001337 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001338 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001339 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001340 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001341 sawIdTypedCatch = true;
1342 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001343 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001344
Ted Kremenek42730c52008-01-07 19:49:32 +00001345 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001346 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001347 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001348 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001349 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001350 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001351 }
1352 }
1353 // Now rewrite the body...
1354 lastCatchBody = catchList->getCatchBody();
1355 SourceLocation rParenLoc = catchList->getRParenLoc();
1356 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1357 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1358 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1359 assert((*rParenBuf == ')') && "bogus @catch paren location");
1360 assert((*bodyBuf == '{') && "bogus @catch body location");
1361
1362 buf = " = _caught;";
1363 // Here we replace ") {" with "= _caught;" (which initializes and
1364 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001365 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001366 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001367 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001368 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001369 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001370 catchList = catchList->getNextCatchStmt();
1371 }
1372 // Complete the catch list...
1373 if (lastCatchBody) {
1374 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001375 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1376 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001377 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1378 buf = " } } /* @catch end */\n";
1379
Chris Lattner6216f292008-01-31 19:42:41 +00001380 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001381
1382 // Set lastCurlyLoc
1383 lastCurlyLoc = lastCatchBody->getLocEnd();
1384 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001385 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001386 startLoc = finalStmt->getLocStart();
1387 startBuf = SM->getCharacterData(startLoc);
1388 assert((*startBuf == '@') && "bogus @finally start");
1389
1390 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001391 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001392
1393 Stmt *body = finalStmt->getFinallyBody();
1394 SourceLocation startLoc = body->getLocStart();
1395 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001396 assert(*SM->getCharacterData(startLoc) == '{' &&
1397 "bogus @finally body location");
1398 assert(*SM->getCharacterData(endLoc) == '}' &&
1399 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001400
1401 startLoc = startLoc.getFileLocWithOffset(1);
1402 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001403 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001404 endLoc = endLoc.getFileLocWithOffset(-1);
1405 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001406 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001407
1408 // Set lastCurlyLoc
1409 lastCurlyLoc = body->getLocEnd();
1410 }
1411 // Now emit the final closing curly brace...
1412 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1413 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001414 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001415 return 0;
1416}
1417
Steve Naroff44e81222008-04-14 22:03:09 +00001418Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001419 return 0;
1420}
1421
Steve Naroff44e81222008-04-14 22:03:09 +00001422Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001423 return 0;
1424}
1425
Chris Lattnerb1548372008-01-31 19:37:57 +00001426// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001427// the throw expression is typically a message expression that's already
1428// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001429Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001430 // Get the start location and compute the semi location.
1431 SourceLocation startLoc = S->getLocStart();
1432 const char *startBuf = SM->getCharacterData(startLoc);
1433
1434 assert((*startBuf == '@') && "bogus @throw location");
1435
1436 std::string buf;
1437 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001438 if (S->getThrowExpr())
1439 buf = "objc_exception_throw(";
1440 else // add an implicit argument
1441 buf = "objc_exception_throw(_caught";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001442 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001443 const char *semiBuf = strchr(startBuf, ';');
1444 assert((*semiBuf == ';') && "@throw: can't find ';'");
1445 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1446 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001447 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001448 return 0;
1449}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001450
Steve Naroff44e81222008-04-14 22:03:09 +00001451Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001452 // Create a new string expression.
1453 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001454 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001455 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1456 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001457 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1458 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001459 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001460 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001461
Chris Lattner4478db92007-11-30 22:53:43 +00001462 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001463 delete Exp;
1464 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001465}
1466
Steve Naroff44e81222008-04-14 22:03:09 +00001467Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff296b74f2007-11-05 14:50:49 +00001468 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1469 // Create a call to sel_registerName("selName").
1470 llvm::SmallVector<Expr*, 8> SelExprs;
1471 QualType argType = Context->getPointerType(Context->CharTy);
1472 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1473 Exp->getSelector().getName().size(),
1474 false, argType, SourceLocation(),
1475 SourceLocation()));
1476 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1477 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001478 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001479 delete Exp;
1480 return SelExp;
1481}
1482
Steve Naroff44e81222008-04-14 22:03:09 +00001483CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001484 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001485 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001486 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001487
1488 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001489 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001490
1491 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001492 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001493 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1494
1495 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001496
Steve Naroff71226032007-10-24 22:48:43 +00001497 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1498}
1499
Steve Naroffc8a92d12007-11-01 13:24:47 +00001500static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1501 const char *&startRef, const char *&endRef) {
1502 while (startBuf < endBuf) {
1503 if (*startBuf == '<')
1504 startRef = startBuf; // mark the start.
1505 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001506 if (startRef && *startRef == '<') {
1507 endRef = startBuf; // mark the end.
1508 return true;
1509 }
1510 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001511 }
1512 startBuf++;
1513 }
1514 return false;
1515}
1516
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001517static void scanToNextArgument(const char *&argRef) {
1518 int angle = 0;
1519 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1520 if (*argRef == '<')
1521 angle++;
1522 else if (*argRef == '>')
1523 angle--;
1524 argRef++;
1525 }
1526 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1527}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001528
Steve Naroff44e81222008-04-14 22:03:09 +00001529bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001530
Ted Kremenek42730c52008-01-07 19:49:32 +00001531 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001532 return true;
1533
Steve Naroffc8a92d12007-11-01 13:24:47 +00001534 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001535 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001536 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001537 return true; // we have "Class <Protocol> *".
1538 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001539 return false;
1540}
1541
Steve Naroff44e81222008-04-14 22:03:09 +00001542void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001543 SourceLocation Loc;
1544 QualType Type;
1545 const FunctionTypeProto *proto = 0;
1546 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1547 Loc = VD->getLocation();
1548 Type = VD->getType();
1549 }
1550 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1551 Loc = FD->getLocation();
1552 // Check for ObjC 'id' and class types that have been adorned with protocol
1553 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1554 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1555 assert(funcType && "missing function type");
1556 proto = dyn_cast<FunctionTypeProto>(funcType);
1557 if (!proto)
1558 return;
1559 Type = proto->getResultType();
1560 }
1561 else
1562 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001563
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001564 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001565 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001566
1567 const char *endBuf = SM->getCharacterData(Loc);
1568 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001569 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001570 startBuf--; // scan backward (from the decl location) for return type.
1571 const char *startRef = 0, *endRef = 0;
1572 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1573 // Get the locations of the startRef, endRef.
1574 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1575 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1576 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001577 InsertText(LessLoc, "/*", 2);
1578 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001579 }
1580 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001581 if (!proto)
1582 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001583 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001584 const char *startBuf = SM->getCharacterData(Loc);
1585 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001586 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1587 if (needToScanForQualifiers(proto->getArgType(i))) {
1588 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001589
Steve Naroffc8a92d12007-11-01 13:24:47 +00001590 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001591 // scan forward (from the decl location) for argument types.
1592 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001593 const char *startRef = 0, *endRef = 0;
1594 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1595 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001596 SourceLocation LessLoc =
1597 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1598 SourceLocation GreaterLoc =
1599 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001600 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001601 InsertText(LessLoc, "/*", 2);
1602 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001603 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001604 startBuf = ++endBuf;
1605 }
1606 else {
1607 while (*startBuf != ')' && *startBuf != ',')
1608 startBuf++; // scan forward (from the decl location) for argument types.
1609 startBuf++;
1610 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001611 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001612}
1613
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001614// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001615void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001616 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1617 llvm::SmallVector<QualType, 16> ArgTys;
1618 ArgTys.push_back(Context->getPointerType(
1619 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001620 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001621 &ArgTys[0], ArgTys.size(),
1622 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001623 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001624 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001625 SelGetUidIdent, getFuncType,
1626 FunctionDecl::Extern, false, 0);
1627}
1628
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001629// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001630void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001631 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1632 llvm::SmallVector<QualType, 16> ArgTys;
1633 ArgTys.push_back(Context->getPointerType(
1634 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001635 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001636 &ArgTys[0], ArgTys.size(),
1637 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001638 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001639 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001640 SelGetProtoIdent, getFuncType,
1641 FunctionDecl::Extern, false, 0);
1642}
1643
Steve Naroff44e81222008-04-14 22:03:09 +00001644void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001645 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001646 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001647 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001648 return;
1649 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001650 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001651}
1652
Steve Naroffbec4bf52008-03-11 17:37:02 +00001653// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001654void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001655 if (SuperContructorFunctionDecl)
1656 return;
1657 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1658 llvm::SmallVector<QualType, 16> ArgTys;
1659 QualType argT = Context->getObjCIdType();
1660 assert(!argT.isNull() && "Can't find 'id' type");
1661 ArgTys.push_back(argT);
1662 ArgTys.push_back(argT);
1663 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1664 &ArgTys[0], ArgTys.size(),
1665 false);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001666 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001667 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001668 msgSendIdent, msgSendType,
1669 FunctionDecl::Extern, false, 0);
1670}
1671
Steve Naroff02a82aa2007-10-30 23:14:51 +00001672// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001673void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001674 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1675 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001676 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001677 assert(!argT.isNull() && "Can't find 'id' type");
1678 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001679 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001680 assert(!argT.isNull() && "Can't find 'SEL' type");
1681 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001682 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001683 &ArgTys[0], ArgTys.size(),
1684 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001685 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001686 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001687 msgSendIdent, msgSendType,
1688 FunctionDecl::Extern, false, 0);
1689}
1690
Steve Naroff764c1ae2007-11-15 10:28:18 +00001691// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001692void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001693 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1694 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001695 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001696 SourceLocation(),
Chris Lattner58114f02008-03-15 21:32:50 +00001697 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001698 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1699 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1700 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001701 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001702 assert(!argT.isNull() && "Can't find 'SEL' type");
1703 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001704 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001705 &ArgTys[0], ArgTys.size(),
1706 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001707 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001708 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001709 msgSendIdent, msgSendType,
1710 FunctionDecl::Extern, false, 0);
1711}
1712
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001713// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001714void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001715 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1716 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001717 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001718 assert(!argT.isNull() && "Can't find 'id' type");
1719 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001720 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001721 assert(!argT.isNull() && "Can't find 'SEL' type");
1722 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001723 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001724 &ArgTys[0], ArgTys.size(),
1725 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001726 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001727 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001728 msgSendIdent, msgSendType,
1729 FunctionDecl::Extern, false, 0);
1730}
1731
1732// SynthMsgSendSuperStretFunctionDecl -
1733// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001734void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001735 IdentifierInfo *msgSendIdent =
1736 &Context->Idents.get("objc_msgSendSuper_stret");
1737 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001738 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001739 SourceLocation(),
Chris Lattner58114f02008-03-15 21:32:50 +00001740 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001741 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1742 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1743 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001744 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001745 assert(!argT.isNull() && "Can't find 'SEL' type");
1746 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001747 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001748 &ArgTys[0], ArgTys.size(),
1749 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001750 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00001751 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001752 msgSendIdent, msgSendType,
1753 FunctionDecl::Extern, false, 0);
1754}
1755
Steve Naroff31316a12008-05-08 22:02:18 +00001756// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001757void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001758 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1759 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001760 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001761 assert(!argT.isNull() && "Can't find 'id' type");
1762 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001763 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001764 assert(!argT.isNull() && "Can't find 'SEL' type");
1765 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00001766 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001767 &ArgTys[0], ArgTys.size(),
1768 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001769 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001770 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001771 msgSendIdent, msgSendType,
1772 FunctionDecl::Extern, false, 0);
1773}
1774
Steve Naroff02a82aa2007-10-30 23:14:51 +00001775// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001776void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001777 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1778 llvm::SmallVector<QualType, 16> ArgTys;
1779 ArgTys.push_back(Context->getPointerType(
1780 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001781 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001782 &ArgTys[0], ArgTys.size(),
1783 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001784 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001785 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001786 getClassIdent, getClassType,
1787 FunctionDecl::Extern, false, 0);
1788}
1789
Steve Naroff3b1caac2007-12-07 03:50:46 +00001790// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001791void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001792 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1793 llvm::SmallVector<QualType, 16> ArgTys;
1794 ArgTys.push_back(Context->getPointerType(
1795 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001796 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001797 &ArgTys[0], ArgTys.size(),
1798 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001799 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001800 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001801 getClassIdent, getClassType,
1802 FunctionDecl::Extern, false, 0);
1803}
1804
Steve Naroff44e81222008-04-14 22:03:09 +00001805Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001806 QualType strType = getConstantStringStructType();
1807
1808 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00001809
1810 std::string tmpName = InFileName;
1811 unsigned i;
1812 for (i=0; i < tmpName.length(); i++) {
1813 char c = tmpName.at(i);
1814 // replace any non alphanumeric characters with '_'.
1815 if (!isalpha(c) && (c < '0' || c > '9'))
1816 tmpName[i] = '_';
1817 }
1818 S += tmpName;
1819 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001820 S += utostr(NumObjCStringLiterals++);
1821
Steve Narofffef037c2008-03-27 22:29:16 +00001822 Preamble += "static __NSConstantStringImpl " + S;
1823 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1824 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00001825 // The pretty printer for StringLiteral handles escape characters properly.
1826 std::ostringstream prettyBuf;
1827 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00001828 Preamble += prettyBuf.str();
1829 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00001830 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00001831 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001832
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001833 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001834 &Context->Idents.get(S.c_str()), strType,
1835 VarDecl::Static, NULL);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001836 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1837 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1838 Context->getPointerType(DRE->getType()),
1839 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001840 // cast to NSConstantString *
Steve Naroff47e7fa22008-03-15 00:55:56 +00001841 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001842 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001843 delete Exp;
1844 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001845}
1846
Steve Naroff44e81222008-04-14 22:03:09 +00001847ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001848 // check if we are sending a message to 'super'
Chris Lattnere4650482008-03-15 06:12:44 +00001849 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1850
1851 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1852 if (!CE) return 0;
1853
1854 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1855 if (!DRE) return 0;
1856
1857 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1858 if (!PVD) return 0;
1859
1860 if (strcmp(PVD->getName(), "self") != 0)
1861 return 0;
1862
1863 // is this id<P1..> type?
1864 if (CE->getType()->isObjCQualifiedIdType())
1865 return 0;
1866 const PointerType *PT = CE->getType()->getAsPointerType();
1867 if (!PT) return 0;
1868
1869 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1870 if (!IT) return 0;
1871
1872 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1873 return 0;
1874
1875 return IT->getDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001876}
1877
1878// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00001879QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001880 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001881 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001882 SourceLocation(),
1883 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001884 QualType FieldTypes[2];
1885
1886 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001887 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001888 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001889 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001890 // Create fields
1891 FieldDecl *FieldDecls[2];
1892
1893 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001894 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001895 FieldTypes[i]);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001896
1897 SuperStructDecl->defineBody(FieldDecls, 4);
1898 }
1899 return Context->getTagDeclType(SuperStructDecl);
1900}
1901
Steve Naroff44e81222008-04-14 22:03:09 +00001902QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001903 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001904 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001905 SourceLocation(),
1906 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001907 QualType FieldTypes[4];
1908
1909 // struct objc_object *receiver;
1910 FieldTypes[0] = Context->getObjCIdType();
1911 // int flags;
1912 FieldTypes[1] = Context->IntTy;
1913 // char *str;
1914 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1915 // long length;
1916 FieldTypes[3] = Context->LongTy;
1917 // Create fields
Steve Naroff053ae3f2008-03-27 22:59:54 +00001918 FieldDecl *FieldDecls[4];
Steve Naroff47e7fa22008-03-15 00:55:56 +00001919
1920 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001921 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001922 FieldTypes[i]);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001923
1924 ConstantStringDecl->defineBody(FieldDecls, 4);
1925 }
1926 return Context->getTagDeclType(ConstantStringDecl);
1927}
1928
Steve Naroff44e81222008-04-14 22:03:09 +00001929Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001930 if (!SelGetUidFunctionDecl)
1931 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001932 if (!MsgSendFunctionDecl)
1933 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001934 if (!MsgSendSuperFunctionDecl)
1935 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001936 if (!MsgSendStretFunctionDecl)
1937 SynthMsgSendStretFunctionDecl();
1938 if (!MsgSendSuperStretFunctionDecl)
1939 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001940 if (!MsgSendFpretFunctionDecl)
1941 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001942 if (!GetClassFunctionDecl)
1943 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001944 if (!GetMetaClassFunctionDecl)
1945 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001946
Steve Naroff764c1ae2007-11-15 10:28:18 +00001947 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001948 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1949 // May need to use objc_msgSend_stret() as well.
1950 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001951 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001952 QualType resultType = mDecl->getResultType();
1953 if (resultType.getCanonicalType()->isStructureType()
1954 || resultType.getCanonicalType()->isUnionType())
1955 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001956 else if (resultType.getCanonicalType()->isRealFloatingType())
1957 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001958 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001959
Steve Naroff71226032007-10-24 22:48:43 +00001960 // Synthesize a call to objc_msgSend().
1961 llvm::SmallVector<Expr*, 8> MsgExprs;
1962 IdentifierInfo *clsName = Exp->getClassName();
1963
1964 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1965 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001966 if (!strcmp(clsName->getName(), "super")) {
1967 MsgSendFlavor = MsgSendSuperFunctionDecl;
1968 if (MsgSendStretFlavor)
1969 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1970 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1971
Ted Kremenek42730c52008-01-07 19:49:32 +00001972 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001973 CurMethodDecl->getClassInterface()->getSuperClass();
1974
1975 llvm::SmallVector<Expr*, 4> InitExprs;
1976
1977 // set the receiver to self, the first argument to all methods.
1978 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001979 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001980 SourceLocation()));
1981 llvm::SmallVector<Expr*, 8> ClsExprs;
1982 QualType argType = Context->getPointerType(Context->CharTy);
1983 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1984 SuperDecl->getIdentifier()->getLength(),
1985 false, argType, SourceLocation(),
1986 SourceLocation()));
1987 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1988 &ClsExprs[0],
1989 ClsExprs.size());
1990 // To turn off a warning, type-cast to 'id'
1991 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001992 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001993 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1994 // struct objc_super
1995 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00001996 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00001997
Steve Naroffdee066b2008-03-11 18:14:26 +00001998 if (LangOpts.Microsoft) {
1999 SynthSuperContructorFunctionDecl();
2000 // Simulate a contructor call...
2001 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2002 superType, SourceLocation());
2003 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2004 superType, SourceLocation());
2005 } else {
2006 // (struct objc_super) { <exprs from above> }
2007 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2008 &InitExprs[0], InitExprs.size(),
2009 SourceLocation());
2010 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2011 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00002012 // struct objc_super *
2013 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2014 Context->getPointerType(SuperRep->getType()),
2015 SourceLocation());
2016 MsgExprs.push_back(Unop);
2017 } else {
2018 llvm::SmallVector<Expr*, 8> ClsExprs;
2019 QualType argType = Context->getPointerType(Context->CharTy);
2020 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2021 clsName->getLength(),
2022 false, argType, SourceLocation(),
2023 SourceLocation()));
2024 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2025 &ClsExprs[0],
2026 ClsExprs.size());
2027 MsgExprs.push_back(Cls);
2028 }
Steve Naroff885e2122007-11-14 23:54:14 +00002029 } else { // instance message.
2030 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002031
Ted Kremenek42730c52008-01-07 19:49:32 +00002032 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002033 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002034 if (MsgSendStretFlavor)
2035 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002036 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2037
2038 llvm::SmallVector<Expr*, 4> InitExprs;
2039
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002040 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00002041 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002042 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002043
2044 llvm::SmallVector<Expr*, 8> ClsExprs;
2045 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002046 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2047 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002048 false, argType, SourceLocation(),
2049 SourceLocation()));
2050 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002051 &ClsExprs[0],
2052 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002053 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002054 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00002055 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002056 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00002057 // struct objc_super
2058 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002059 Expr *SuperRep;
2060
2061 if (LangOpts.Microsoft) {
2062 SynthSuperContructorFunctionDecl();
2063 // Simulate a contructor call...
2064 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2065 superType, SourceLocation());
2066 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2067 superType, SourceLocation());
2068 } else {
2069 // (struct objc_super) { <exprs from above> }
2070 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2071 &InitExprs[0], InitExprs.size(),
2072 SourceLocation());
2073 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2074 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002075 // struct objc_super *
2076 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2077 Context->getPointerType(SuperRep->getType()),
2078 SourceLocation());
2079 MsgExprs.push_back(Unop);
2080 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002081 // Remove all type-casts because it may contain objc-style types; e.g.
2082 // Foo<Proto> *.
2083 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2084 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002085 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002086 MsgExprs.push_back(recExpr);
2087 }
Steve Naroff885e2122007-11-14 23:54:14 +00002088 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002089 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002090 llvm::SmallVector<Expr*, 8> SelExprs;
2091 QualType argType = Context->getPointerType(Context->CharTy);
2092 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2093 Exp->getSelector().getName().size(),
2094 false, argType, SourceLocation(),
2095 SourceLocation()));
2096 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2097 &SelExprs[0], SelExprs.size());
2098 MsgExprs.push_back(SelExp);
2099
2100 // Now push any user supplied arguments.
2101 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002102 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002103 // Make all implicit casts explicit...ICE comes in handy:-)
2104 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2105 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00002106 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2107 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002108 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002109 }
2110 // Make id<P...> cast into an 'id' cast.
2111 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002112 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002113 while ((CE = dyn_cast<CastExpr>(userExpr)))
2114 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002115 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002116 userExpr, SourceLocation());
2117 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002118 }
Steve Naroff885e2122007-11-14 23:54:14 +00002119 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002120 // We've transferred the ownership to MsgExprs. Null out the argument in
2121 // the original expression, since we will delete it below.
2122 Exp->setArg(i, 0);
2123 }
Steve Naroff0744c472007-11-04 22:37:50 +00002124 // Generate the funky cast.
2125 CastExpr *cast;
2126 llvm::SmallVector<QualType, 8> ArgTypes;
2127 QualType returnType;
2128
2129 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002130 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2131 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2132 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002133 ArgTypes.push_back(Context->getObjCIdType());
2134 ArgTypes.push_back(Context->getObjCSelType());
2135 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002136 // Push any user argument types.
Chris Lattner685d7922008-03-16 01:07:14 +00002137 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002138 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2139 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002140 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00002141 ArgTypes.push_back(t);
2142 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002143 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2144 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002145 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002146 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002147 }
2148 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002149 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002150
2151 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002152 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2153 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002154
2155 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2156 // If we don't do this cast, we get the following bizarre warning/note:
2157 // xx.m:13: warning: function called through a non-compatible type
2158 // xx.m:13: note: if this code is reached, the program will abort
2159 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2160 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002161
Steve Naroff0744c472007-11-04 22:37:50 +00002162 // Now do the "normal" pointer to function cast.
2163 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002164 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002165 // If we don't have a method decl, force a variadic cast.
2166 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroff0744c472007-11-04 22:37:50 +00002167 castType = Context->getPointerType(castType);
2168 cast = new CastExpr(castType, cast, SourceLocation());
2169
2170 // Don't forget the parens to enforce the proper binding.
2171 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2172
2173 const FunctionType *FT = msgSendType->getAsFunctionType();
2174 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2175 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002176 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002177 if (MsgSendStretFlavor) {
2178 // We have the method which returns a struct/union. Must also generate
2179 // call to objc_msgSend_stret and hang both varieties on a conditional
2180 // expression which dictate which one to envoke depending on size of
2181 // method's return type.
2182
2183 // Create a reference to the objc_msgSend_stret() declaration.
2184 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2185 SourceLocation());
2186 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2187 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2188 SourceLocation());
2189 // Now do the "normal" pointer to function cast.
2190 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002191 &ArgTypes[0], ArgTypes.size(),
2192 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002193 castType = Context->getPointerType(castType);
2194 cast = new CastExpr(castType, cast, SourceLocation());
2195
2196 // Don't forget the parens to enforce the proper binding.
2197 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2198
2199 FT = msgSendType->getAsFunctionType();
2200 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2201 FT->getResultType(), SourceLocation());
2202
2203 // Build sizeof(returnType)
2204 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2205 returnType, Context->getSizeType(),
2206 SourceLocation(), SourceLocation());
2207 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2208 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2209 // For X86 it is more complicated and some kind of target specific routine
2210 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002211 unsigned IntSize =
2212 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002213 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2214 Context->IntTy,
2215 SourceLocation());
2216 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2217 BinaryOperator::LE,
2218 Context->IntTy,
2219 SourceLocation());
2220 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2221 ConditionalOperator *CondExpr =
2222 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002223 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002224 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002225 return ReplacingStmt;
2226}
2227
Steve Naroff44e81222008-04-14 22:03:09 +00002228Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002229 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002230 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002231 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002232
Chris Lattner0021f452007-10-24 16:57:36 +00002233 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002234 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002235}
2236
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002237/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2238/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002239Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002240 if (!GetProtocolFunctionDecl)
2241 SynthGetProtocolFunctionDecl();
2242 // Create a call to objc_getProtocol("ProtocolName").
2243 llvm::SmallVector<Expr*, 8> ProtoExprs;
2244 QualType argType = Context->getPointerType(Context->CharTy);
2245 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2246 strlen(Exp->getProtocol()->getName()),
2247 false, argType, SourceLocation(),
2248 SourceLocation()));
2249 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2250 &ProtoExprs[0],
2251 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002252 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002253 delete Exp;
2254 return ProtoExp;
2255
2256}
2257
Steve Naroffef82b742008-05-31 14:15:04 +00002258bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2259 const char *endBuf) {
2260 while (startBuf < endBuf) {
2261 if (*startBuf == '#') {
2262 // Skip whitespace.
2263 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2264 ;
2265 if (!strncmp(startBuf, "if", strlen("if")) ||
2266 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2267 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2268 !strncmp(startBuf, "define", strlen("define")) ||
2269 !strncmp(startBuf, "undef", strlen("undef")) ||
2270 !strncmp(startBuf, "else", strlen("else")) ||
2271 !strncmp(startBuf, "elif", strlen("elif")) ||
2272 !strncmp(startBuf, "endif", strlen("endif")) ||
2273 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2274 !strncmp(startBuf, "include", strlen("include")) ||
2275 !strncmp(startBuf, "import", strlen("import")) ||
2276 !strncmp(startBuf, "include_next", strlen("include_next")))
2277 return true;
2278 }
2279 startBuf++;
2280 }
2281 return false;
2282}
2283
Ted Kremenek42730c52008-01-07 19:49:32 +00002284/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002285/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002286void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002287 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002288 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2289 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002290 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002291 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002292 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002293 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002294 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002295 SourceLocation LocStart = CDecl->getLocStart();
2296 SourceLocation LocEnd = CDecl->getLocEnd();
2297
2298 const char *startBuf = SM->getCharacterData(LocStart);
2299 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002300
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002301 // If no ivars and no root or if its root, directly or indirectly,
2302 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002303 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2304 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002305 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002306 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002307 return;
2308 }
2309
2310 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002311 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002312 Result += "\nstruct ";
2313 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002314 if (LangOpts.Microsoft)
2315 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002316
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002317 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002318 const char *cursor = strchr(startBuf, '{');
2319 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002320 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002321 // If the buffer contains preprocessor directives, we do more fine-grained
2322 // rewrites. This is intended to fix code that looks like (which occurs in
2323 // NSURL.h, for example):
2324 //
2325 // #ifdef XYZ
2326 // @interface Foo : NSObject
2327 // #else
2328 // @interface FooBar : NSObject
2329 // #endif
2330 // {
2331 // int i;
2332 // }
2333 // @end
2334 //
2335 // This clause is segregated to avoid breaking the common case.
2336 if (BufferContainsPPDirectives(startBuf, cursor)) {
2337 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2338 CDecl->getClassLoc();
2339 const char *endHeader = SM->getCharacterData(L);
2340 endHeader += Lexer::MeasureTokenLength(L, *SM);
2341
2342 if (CDecl->getNumIntfRefProtocols()) {
2343 // advance to the end of the referenced protocols.
2344 while (endHeader < cursor && *endHeader != '>') endHeader++;
2345 endHeader++;
2346 }
2347 // rewrite the original header
2348 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2349 } else {
2350 // rewrite the original header *without* disturbing the '{'
2351 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2352 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002353 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002354 Result = "\n struct ";
2355 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002356 Result += "_IMPL ";
2357 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002358 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002359
2360 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002361 SourceLocation OnePastCurly =
2362 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2363 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002364 }
2365 cursor++; // past '{'
2366
2367 // Now comment out any visibility specifiers.
2368 while (cursor < endBuf) {
2369 if (*cursor == '@') {
2370 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002371 // Skip whitespace.
2372 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2373 /*scan*/;
2374
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002375 // FIXME: presence of @public, etc. inside comment results in
2376 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002377 if (!strncmp(cursor, "public", strlen("public")) ||
2378 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002379 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002380 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002381 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002382 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002383 // FIXME: If there are cases where '<' is used in ivar declaration part
2384 // of user code, then scan the ivar list and use needToScanForQualifiers
2385 // for type checking.
2386 else if (*cursor == '<') {
2387 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002388 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002389 cursor = strchr(cursor, '>');
2390 cursor++;
2391 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002392 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002393 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002394 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002395 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002396 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002397 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002398 } else { // we don't have any instance variables - insert super struct.
2399 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2400 Result += " {\n struct ";
2401 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002402 Result += "_IMPL ";
2403 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002404 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002405 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002406 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002407 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002408 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002409 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002410}
2411
Ted Kremenek42730c52008-01-07 19:49:32 +00002412// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002413/// class methods.
Steve Naroff44e81222008-04-14 22:03:09 +00002414void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002415 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002416 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002417 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002418 const char *ClassName,
2419 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002420 if (MethodBegin == MethodEnd) return;
2421
Fariborz Jahanian04455192007-10-22 21:41:37 +00002422 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002423 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002424 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002425 SEL _cmd;
2426 char *method_types;
2427 void *_imp;
2428 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002429 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002430 Result += "\nstruct _objc_method {\n";
2431 Result += "\tSEL _cmd;\n";
2432 Result += "\tchar *method_types;\n";
2433 Result += "\tvoid *_imp;\n";
2434 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002435
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002436 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002437 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002438
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002439 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002440
2441 /* struct {
2442 struct _objc_method_list *next_method;
2443 int method_count;
2444 struct _objc_method method_list[];
2445 }
2446 */
2447 Result += "\nstatic struct {\n";
2448 Result += "\tstruct _objc_method_list *next_method;\n";
2449 Result += "\tint method_count;\n";
2450 Result += "\tstruct _objc_method method_list[";
2451 Result += utostr(MethodEnd-MethodBegin);
2452 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002453 Result += prefix;
2454 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2455 Result += "_METHODS_";
2456 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002457 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002458 Result += IsInstanceMethod ? "inst" : "cls";
2459 Result += "_meth\")))= ";
2460 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002461
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002462 Result += "\t,{{(SEL)\"";
2463 Result += (*MethodBegin)->getSelector().getName().c_str();
2464 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002465 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002466 Result += "\", \"";
2467 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002468 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002469 Result += MethodInternalNames[*MethodBegin];
2470 Result += "}\n";
2471 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2472 Result += "\t ,{(SEL)\"";
2473 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002474 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002475 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002476 Result += "\", \"";
2477 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002478 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002479 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002480 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002481 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002482 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002483}
2484
Ted Kremenek42730c52008-01-07 19:49:32 +00002485/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Steve Naroff44e81222008-04-14 22:03:09 +00002486void RewriteObjC::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002487 int NumProtocols,
2488 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002489 const char *ClassName,
2490 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002491 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002492 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002493 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002494 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002495 // Output struct protocol_methods holder of method selector and type.
Chris Lattner7afba9c2008-03-16 20:19:15 +00002496 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002497 /* struct protocol_methods {
2498 SEL _cmd;
2499 char *method_types;
2500 }
2501 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002502 Result += "\nstruct protocol_methods {\n";
2503 Result += "\tSEL _cmd;\n";
2504 Result += "\tchar *method_types;\n";
2505 Result += "};\n";
2506
Steve Naroff27429432008-03-12 01:06:30 +00002507 objc_protocol_methods = true;
2508 }
Steve Naroff04eaa192008-05-06 18:26:51 +00002509 // Do not synthesize the protocol more than once.
2510 if (ObjCSynthesizedProtocols.count(PDecl))
2511 continue;
2512
Chris Lattner7afba9c2008-03-16 20:19:15 +00002513 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2514 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002515 /* struct _objc_protocol_method_list {
2516 int protocol_method_count;
2517 struct protocol_methods protocols[];
2518 }
2519 */
Steve Naroff27429432008-03-12 01:06:30 +00002520 Result += "\nstatic struct {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002521 Result += "\tint protocol_method_count;\n";
Steve Naroff27429432008-03-12 01:06:30 +00002522 Result += "\tstruct protocol_methods protocols[";
2523 Result += utostr(NumMethods);
2524 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002525 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002526 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002527 "{\n\t" + utostr(NumMethods) + "\n";
2528
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002529 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002530 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002531 E = PDecl->instmeth_end(); I != E; ++I) {
2532 if (I == PDecl->instmeth_begin())
2533 Result += "\t ,{{(SEL)\"";
2534 else
2535 Result += "\t ,{(SEL)\"";
2536 Result += (*I)->getSelector().getName().c_str();
2537 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002538 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002539 Result += "\", \"";
2540 Result += MethodTypeString;
2541 Result += "\"}\n";
2542 }
2543 Result += "\t }\n};\n";
2544 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002545
2546 // Output class methods declared in this protocol.
Chris Lattner7afba9c2008-03-16 20:19:15 +00002547 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahanian04455192007-10-22 21:41:37 +00002548 if (NumMethods > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002549 /* struct _objc_protocol_method_list {
2550 int protocol_method_count;
2551 struct protocol_methods protocols[];
2552 }
2553 */
2554 Result += "\nstatic struct {\n";
2555 Result += "\tint protocol_method_count;\n";
2556 Result += "\tstruct protocol_methods protocols[";
2557 Result += utostr(NumMethods);
2558 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002559 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002560 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002561 "{\n\t";
2562 Result += utostr(NumMethods);
2563 Result += "\n";
2564
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002565 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002566 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002567 E = PDecl->classmeth_end(); I != E; ++I) {
2568 if (I == PDecl->classmeth_begin())
2569 Result += "\t ,{{(SEL)\"";
2570 else
2571 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002572 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002573 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002574 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002575 Result += "\", \"";
2576 Result += MethodTypeString;
2577 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002578 }
2579 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002580 }
Steve Naroff04eaa192008-05-06 18:26:51 +00002581
Fariborz Jahanian04455192007-10-22 21:41:37 +00002582 // Output:
2583 /* struct _objc_protocol {
2584 // Objective-C 1.0 extensions
2585 struct _objc_protocol_extension *isa;
2586 char *protocol_name;
2587 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002588 struct _objc_protocol_method_list *instance_methods;
2589 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002590 };
2591 */
2592 static bool objc_protocol = false;
2593 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002594 Result += "\nstruct _objc_protocol {\n";
2595 Result += "\tstruct _objc_protocol_extension *isa;\n";
2596 Result += "\tchar *protocol_name;\n";
2597 Result += "\tstruct _objc_protocol **protocol_list;\n";
2598 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2599 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2600 Result += "};\n";
2601
Fariborz Jahanian04455192007-10-22 21:41:37 +00002602 objc_protocol = true;
2603 }
2604
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002605 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2606 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002607 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002608 "{\n\t0, \"";
2609 Result += PDecl->getName();
2610 Result += "\", 0, ";
Chris Lattner7afba9c2008-03-16 20:19:15 +00002611 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00002612 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002613 Result += PDecl->getName();
2614 Result += ", ";
2615 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002616 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002617 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002618 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002619 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002620 Result += PDecl->getName();
2621 Result += "\n";
2622 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002623 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002624 Result += "0\n";
2625 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002626
2627 // Mark this protocol as having been generated.
2628 if (!ObjCSynthesizedProtocols.insert(PDecl))
2629 assert(false && "protocol already synthesized");
Fariborz Jahanian04455192007-10-22 21:41:37 +00002630 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002631 // Output the top lovel protocol meta-data for the class.
Steve Naroff27429432008-03-12 01:06:30 +00002632 /* struct _objc_protocol_list {
2633 struct _objc_protocol_list *next;
2634 int protocol_count;
2635 struct _objc_protocol *class_protocols[];
2636 }
2637 */
2638 Result += "\nstatic struct {\n";
2639 Result += "\tstruct _objc_protocol_list *next;\n";
2640 Result += "\tint protocol_count;\n";
2641 Result += "\tstruct _objc_protocol *class_protocols[";
2642 Result += utostr(NumProtocols);
2643 Result += "];\n} _OBJC_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002644 Result += prefix;
2645 Result += "_PROTOCOLS_";
2646 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002647 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002648 "{\n\t0, ";
2649 Result += utostr(NumProtocols);
2650 Result += "\n";
2651
2652 Result += "\t,{&_OBJC_PROTOCOL_";
2653 Result += Protocols[0]->getName();
2654 Result += " \n";
2655
2656 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002657 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroffb6ed80a2008-04-18 22:15:15 +00002658 Result += "\t ,&_OBJC_PROTOCOL_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002659 Result += PDecl->getName();
2660 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002661 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002662 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002663 }
2664}
2665
Ted Kremenek42730c52008-01-07 19:49:32 +00002666/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002667/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00002668void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002669 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002670 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002671 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002672 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002673 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2674 CDecl = CDecl->getNextClassCategory())
2675 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2676 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002677
Chris Lattnera661a4d2007-12-23 01:40:15 +00002678 std::string FullCategoryName = ClassDecl->getName();
2679 FullCategoryName += '_';
2680 FullCategoryName += IDecl->getName();
2681
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002682 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002683 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002684 true, "CATEGORY_", FullCategoryName.c_str(),
2685 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002686
2687 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002688 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002689 false, "CATEGORY_", FullCategoryName.c_str(),
2690 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002691
2692 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002693 // Null CDecl is case of a category implementation with no category interface
2694 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002695 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002696 CDecl->getNumReferencedProtocols(),
2697 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002698 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002699
2700 /* struct _objc_category {
2701 char *category_name;
2702 char *class_name;
2703 struct _objc_method_list *instance_methods;
2704 struct _objc_method_list *class_methods;
2705 struct _objc_protocol_list *protocols;
2706 // Objective-C 1.0 extensions
2707 uint32_t size; // sizeof (struct _objc_category)
2708 struct _objc_property_list *instance_properties; // category's own
2709 // @property decl.
2710 };
2711 */
2712
2713 static bool objc_category = false;
2714 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002715 Result += "\nstruct _objc_category {\n";
2716 Result += "\tchar *category_name;\n";
2717 Result += "\tchar *class_name;\n";
2718 Result += "\tstruct _objc_method_list *instance_methods;\n";
2719 Result += "\tstruct _objc_method_list *class_methods;\n";
2720 Result += "\tstruct _objc_protocol_list *protocols;\n";
2721 Result += "\tunsigned int size;\n";
2722 Result += "\tstruct _objc_property_list *instance_properties;\n";
2723 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002724 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002725 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002726 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2727 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002728 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002729 Result += IDecl->getName();
2730 Result += "\"\n\t, \"";
2731 Result += ClassDecl->getName();
2732 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002733
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002734 if (IDecl->getNumInstanceMethods() > 0) {
2735 Result += "\t, (struct _objc_method_list *)"
2736 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2737 Result += FullCategoryName;
2738 Result += "\n";
2739 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002740 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002741 Result += "\t, 0\n";
2742 if (IDecl->getNumClassMethods() > 0) {
2743 Result += "\t, (struct _objc_method_list *)"
2744 "&_OBJC_CATEGORY_CLASS_METHODS_";
2745 Result += FullCategoryName;
2746 Result += "\n";
2747 }
2748 else
2749 Result += "\t, 0\n";
2750
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002751 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002752 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2753 Result += FullCategoryName;
2754 Result += "\n";
2755 }
2756 else
2757 Result += "\t, 0\n";
2758 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002759}
2760
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002761/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2762/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00002763void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00002764 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002765 std::string &Result) {
Steve Naroff5bf10222008-05-07 21:23:49 +00002766 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002767 Result += IDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002768 if (LangOpts.Microsoft)
2769 Result += "_IMPL";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002770 Result += ", ";
2771 Result += ivar->getName();
2772 Result += ")";
2773}
2774
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002775//===----------------------------------------------------------------------===//
2776// Meta Data Emission
2777//===----------------------------------------------------------------------===//
2778
Steve Naroff44e81222008-04-14 22:03:09 +00002779void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002780 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002781 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002782
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002783 // Explictly declared @interface's are already synthesized.
2784 if (CDecl->ImplicitInterfaceDecl()) {
2785 // FIXME: Implementation of a class with no @interface (legacy) doese not
2786 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002787 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002788 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002789
Chris Lattnerc7b06752007-12-12 07:56:42 +00002790 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00002791 unsigned NumIvars = !IDecl->ivar_empty()
2792 ? IDecl->ivar_size()
2793 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002794 if (NumIvars > 0) {
2795 static bool objc_ivar = false;
2796 if (!objc_ivar) {
2797 /* struct _objc_ivar {
2798 char *ivar_name;
2799 char *ivar_type;
2800 int ivar_offset;
2801 };
2802 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002803 Result += "\nstruct _objc_ivar {\n";
2804 Result += "\tchar *ivar_name;\n";
2805 Result += "\tchar *ivar_type;\n";
2806 Result += "\tint ivar_offset;\n";
2807 Result += "};\n";
2808
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002809 objc_ivar = true;
2810 }
2811
Steve Naroffc723eec2008-03-11 00:12:29 +00002812 /* struct {
2813 int ivar_count;
2814 struct _objc_ivar ivar_list[nIvars];
2815 };
2816 */
2817 Result += "\nstatic struct {\n";
2818 Result += "\tint ivar_count;\n";
2819 Result += "\tstruct _objc_ivar ivar_list[";
2820 Result += utostr(NumIvars);
2821 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002822 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002823 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002824 "{\n\t";
2825 Result += utostr(NumIvars);
2826 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002827
Ted Kremenek42730c52008-01-07 19:49:32 +00002828 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00002829 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00002830 IVI = IDecl->ivar_begin();
2831 IVE = IDecl->ivar_end();
2832 } else {
2833 IVI = CDecl->ivar_begin();
2834 IVE = CDecl->ivar_end();
2835 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002836 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002837 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002838 Result += "\", \"";
2839 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002840 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2841 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002842 Result += StrEncoding;
2843 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002844 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002845 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002846 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002847 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002848 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002849 Result += "\", \"";
2850 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002851 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2852 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002853 Result += StrEncoding;
2854 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002855 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002856 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002857 }
2858
2859 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002860 }
2861
2862 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002863 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002864 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002865
2866 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002867 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002868 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002869
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002870 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002871 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002872 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002873 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002874
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002875
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002876 // Declaration of class/meta-class metadata
2877 /* struct _objc_class {
2878 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002879 const char *super_class_name;
2880 char *name;
2881 long version;
2882 long info;
2883 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002884 struct _objc_ivar_list *ivars;
2885 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002886 struct objc_cache *cache;
2887 struct objc_protocol_list *protocols;
2888 const char *ivar_layout;
2889 struct _objc_class_ext *ext;
2890 };
2891 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002892 static bool objc_class = false;
2893 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002894 Result += "\nstruct _objc_class {\n";
2895 Result += "\tstruct _objc_class *isa;\n";
2896 Result += "\tconst char *super_class_name;\n";
2897 Result += "\tchar *name;\n";
2898 Result += "\tlong version;\n";
2899 Result += "\tlong info;\n";
2900 Result += "\tlong instance_size;\n";
2901 Result += "\tstruct _objc_ivar_list *ivars;\n";
2902 Result += "\tstruct _objc_method_list *methods;\n";
2903 Result += "\tstruct objc_cache *cache;\n";
2904 Result += "\tstruct _objc_protocol_list *protocols;\n";
2905 Result += "\tconst char *ivar_layout;\n";
2906 Result += "\tstruct _objc_class_ext *ext;\n";
2907 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002908 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002909 }
2910
2911 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002912 ObjCInterfaceDecl *RootClass = 0;
2913 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002914 while (SuperClass) {
2915 RootClass = SuperClass;
2916 SuperClass = SuperClass->getSuperClass();
2917 }
2918 SuperClass = CDecl->getSuperClass();
2919
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002920 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2921 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002922 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002923 "{\n\t(struct _objc_class *)\"";
2924 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2925 Result += "\"";
2926
2927 if (SuperClass) {
2928 Result += ", \"";
2929 Result += SuperClass->getName();
2930 Result += "\", \"";
2931 Result += CDecl->getName();
2932 Result += "\"";
2933 }
2934 else {
2935 Result += ", 0, \"";
2936 Result += CDecl->getName();
2937 Result += "\"";
2938 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002939 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002940 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002941 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002942 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00002943 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002944 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002945 Result += "\n";
2946 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002947 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002948 Result += ", 0\n";
2949 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002950 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002951 Result += CDecl->getName();
2952 Result += ",0,0\n";
2953 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002954 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002955 Result += "\t,0,0,0,0\n";
2956 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002957
2958 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002959 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2960 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002961 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002962 "{\n\t&_OBJC_METACLASS_";
2963 Result += CDecl->getName();
2964 if (SuperClass) {
2965 Result += ", \"";
2966 Result += SuperClass->getName();
2967 Result += "\", \"";
2968 Result += CDecl->getName();
2969 Result += "\"";
2970 }
2971 else {
2972 Result += ", 0, \"";
2973 Result += CDecl->getName();
2974 Result += "\"";
2975 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002976 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002977 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002978 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002979 Result += ",0";
2980 else {
2981 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002982 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002983 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00002984 if (LangOpts.Microsoft)
2985 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002986 Result += ")";
2987 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002988 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00002989 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002990 Result += CDecl->getName();
2991 Result += "\n\t";
2992 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002993 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002994 Result += ",0";
2995 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00002996 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002997 Result += CDecl->getName();
2998 Result += ", 0\n\t";
2999 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003000 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003001 Result += ",0,0";
3002 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00003003 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003004 Result += CDecl->getName();
3005 Result += ", 0,0\n";
3006 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003007 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003008 Result += ",0,0,0\n";
3009 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003010}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003011
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003012/// RewriteImplementations - This routine rewrites all method implementations
3013/// and emits meta-data.
3014
Steve Naroff44e81222008-04-14 22:03:09 +00003015void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003016 int ClsDefCount = ClassImplementation.size();
3017 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003018
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003019 if (ClsDefCount == 0 && CatDefCount == 0)
3020 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003021 // Rewrite implemented methods
3022 for (int i = 0; i < ClsDefCount; i++)
3023 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003024
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003025 for (int i = 0; i < CatDefCount; i++)
3026 RewriteImplementationDecl(CategoryImplementation[i]);
3027
Steve Naroff5bf10222008-05-07 21:23:49 +00003028 // This is needed for determining instance variable offsets.
3029 Result += "#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003030 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003031 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003032 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003033
3034 // For each implemented category, write out all its meta data.
3035 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003036 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003037
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003038 // Write objc_symtab metadata
3039 /*
3040 struct _objc_symtab
3041 {
3042 long sel_ref_cnt;
3043 SEL *refs;
3044 short cls_def_cnt;
3045 short cat_def_cnt;
3046 void *defs[cls_def_cnt + cat_def_cnt];
3047 };
3048 */
3049
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003050 Result += "\nstruct _objc_symtab {\n";
3051 Result += "\tlong sel_ref_cnt;\n";
3052 Result += "\tSEL *refs;\n";
3053 Result += "\tshort cls_def_cnt;\n";
3054 Result += "\tshort cat_def_cnt;\n";
3055 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3056 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003057
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003058 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003059 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003060 Result += "\t0, 0, " + utostr(ClsDefCount)
3061 + ", " + utostr(CatDefCount) + "\n";
3062 for (int i = 0; i < ClsDefCount; i++) {
3063 Result += "\t,&_OBJC_CLASS_";
3064 Result += ClassImplementation[i]->getName();
3065 Result += "\n";
3066 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003067
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003068 for (int i = 0; i < CatDefCount; i++) {
3069 Result += "\t,&_OBJC_CATEGORY_";
3070 Result += CategoryImplementation[i]->getClassInterface()->getName();
3071 Result += "_";
3072 Result += CategoryImplementation[i]->getName();
3073 Result += "\n";
3074 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003075
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003076 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003077
3078 // Write objc_module metadata
3079
3080 /*
3081 struct _objc_module {
3082 long version;
3083 long size;
3084 const char *name;
3085 struct _objc_symtab *symtab;
3086 }
3087 */
3088
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003089 Result += "\nstruct _objc_module {\n";
3090 Result += "\tlong version;\n";
3091 Result += "\tlong size;\n";
3092 Result += "\tconst char *name;\n";
3093 Result += "\tstruct _objc_symtab *symtab;\n";
3094 Result += "};\n\n";
3095 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003096 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003097 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3098 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003099 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003100
3101 if (LangOpts.Microsoft) {
3102 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003103 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003104 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3105 Result += "&_OBJC_MODULES;\n";
3106 Result += "#pragma data_seg(pop)\n\n";
3107 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003108}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003109
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003110
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003111
3112