blob: 3e8216e6679f1e7d018dfad7ece73e71e9b2e8b1 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner77cd2a02007-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 Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Steve Naroff0113c9d2008-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 Lattner77cd2a02007-10-11 00:43:27 +000038namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattner01c57482007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000046 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000051
Ted Kremeneka526c5c2008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000083 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
94
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000095 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000096 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +000097 virtual void Initialize(ASTContext &context);
98
99 virtual void InitializeTU(TranslationUnit &TU) {
100 TU.SetOwnsDecls(false);
101 Initialize(TU.getContext());
102 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000103
Chris Lattner8a12c272007-10-11 18:38:32 +0000104
Chris Lattnerf04da132007-10-24 17:06:59 +0000105 // Top Level Driver code.
106 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000107 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000108 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000109 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000110
111 ~RewriteObjC() {}
112
113 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000114
115 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000116 // If replacement succeeded or warning disabled return with no warning.
117 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000118 return;
119
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000120 SourceRange Range = Old->getSourceRange();
121 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
122 0, 0, &Range, 1);
123 }
124
Steve Naroffba92b2e2008-03-27 22:29:16 +0000125 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
126 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000127 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000128 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000129 SilenceRewriteMacroWarning)
130 return;
131
132 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
133 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000134
Chris Lattneraadaf782008-01-31 19:51:04 +0000135 void RemoveText(SourceLocation Loc, unsigned StrLen) {
136 // If removal succeeded or warning disabled return with no warning.
137 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
138 return;
139
140 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
141 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000142
Chris Lattneraadaf782008-01-31 19:51:04 +0000143 void ReplaceText(SourceLocation Start, unsigned OrigLength,
144 const char *NewStr, unsigned NewLength) {
145 // If removal succeeded or warning disabled return with no warning.
146 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
147 SilenceRewriteMacroWarning)
148 return;
149
150 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
151 }
152
Chris Lattnerf04da132007-10-24 17:06:59 +0000153 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000154 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000155 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000156 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000157 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
158 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000159 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000160 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
161 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
162 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
163 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
164 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000165 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000166 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000167 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000168 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000169 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000170 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000171 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000172 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000173 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000174
Chris Lattnerf04da132007-10-24 17:06:59 +0000175 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000176 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000177 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000178 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000179 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000180 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000181 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000182 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000183 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000184 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000185 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
186 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
187 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000188 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
189 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000190 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
191 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000192 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000193 Stmt *RewriteBreakStmt(BreakStmt *S);
194 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000195 void SynthCountByEnumWithState(std::string &buf);
196
Steve Naroff09b266e2007-10-30 23:14:51 +0000197 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000198 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000199 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000200 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000201 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000202 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000203 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000204 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000205 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000206 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000207
Chris Lattnerf04da132007-10-24 17:06:59 +0000208 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000209 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000210 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000211
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000212 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000213 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000214
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000215 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
216 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000217 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000218 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000219 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000220 const char *ClassName,
221 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000222
Chris Lattner780f3292008-07-21 21:32:27 +0000223 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
224 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000225 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000226 const char *ClassName,
227 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000228 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000229 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000230 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
231 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000232 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000233 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000234 };
235}
236
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000237static bool IsHeaderFile(const std::string &Filename) {
238 std::string::size_type DotPos = Filename.rfind('.');
239
240 if (DotPos == std::string::npos) {
241 // no file extension
242 return false;
243 }
244
245 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
246 // C header: .h
247 // C++ header: .hh or .H;
248 return Ext == "h" || Ext == "hh" || Ext == "H";
249}
250
Steve Naroffb29b4272008-04-14 22:03:09 +0000251RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000252 Diagnostic &D, const LangOptions &LOpts)
253 : Diags(D), LangOpts(LOpts) {
254 IsHeader = IsHeaderFile(inFile);
255 InFileName = inFile;
256 OutFileName = outFile;
257 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
258 "rewriting sub-expression within a macro (may not be correct)");
259}
260
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000261ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000262 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000263 Diagnostic &Diags,
264 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000265 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000266}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000267
Steve Naroffb29b4272008-04-14 22:03:09 +0000268void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000269 Context = &context;
270 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000271 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000272 MsgSendFunctionDecl = 0;
273 MsgSendSuperFunctionDecl = 0;
274 MsgSendStretFunctionDecl = 0;
275 MsgSendSuperStretFunctionDecl = 0;
276 MsgSendFpretFunctionDecl = 0;
277 GetClassFunctionDecl = 0;
278 GetMetaClassFunctionDecl = 0;
279 SelGetUidFunctionDecl = 0;
280 CFStringFunctionDecl = 0;
281 GetProtocolFunctionDecl = 0;
282 ConstantStringClassReference = 0;
283 NSStringRecord = 0;
284 CurMethodDecl = 0;
285 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000286 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000287 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000288 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000289 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000290
291 // Get the ID and start/end of the main file.
292 MainFileID = SM->getMainFileID();
293 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
294 MainFileStart = MainBuf->getBufferStart();
295 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000296
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000297 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000298
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000299 // declaring objc_selector outside the parameter list removes a silly
300 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000301 if (IsHeader)
302 Preamble = "#pragma once\n";
303 Preamble += "struct objc_selector; struct objc_class;\n";
304 Preamble += "#ifndef OBJC_SUPER\n";
305 Preamble += "struct objc_super { struct objc_object *object; ";
306 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000307 if (LangOpts.Microsoft) {
308 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000309 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
310 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000311 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000312 Preamble += "};\n";
313 Preamble += "#define OBJC_SUPER\n";
314 Preamble += "#endif\n";
315 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
316 Preamble += "typedef struct objc_object Protocol;\n";
317 Preamble += "#define _REWRITER_typedef_Protocol\n";
318 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000319 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000320 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
321 else
322 Preamble += "#define __OBJC_RW_EXTERN extern\n";
323 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000324 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000325 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000326 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000327 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000328 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000329 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000330 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000331 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000332 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000333 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000334 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000335 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000336 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000337 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
338 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
339 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
340 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
341 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000342 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000343 // @synchronized hooks.
344 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
345 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000346 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000347 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
348 Preamble += "struct __objcFastEnumerationState {\n\t";
349 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000350 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000351 Preamble += "unsigned long *mutationsPtr;\n\t";
352 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000353 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000354 Preamble += "#define __FASTENUMERATIONSTATE\n";
355 Preamble += "#endif\n";
356 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
357 Preamble += "struct __NSConstantStringImpl {\n";
358 Preamble += " int *isa;\n";
359 Preamble += " int flags;\n";
360 Preamble += " char *str;\n";
361 Preamble += " long length;\n";
362 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000363 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
364 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
365 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000366 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000367 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000368 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
369 Preamble += "#endif\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000370 if (LangOpts.Microsoft) {
371 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000372 Preamble += "#define __attribute__(X)\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000373 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000374}
375
376
Chris Lattnerf04da132007-10-24 17:06:59 +0000377//===----------------------------------------------------------------------===//
378// Top Level Driver Code
379//===----------------------------------------------------------------------===//
380
Steve Naroffb29b4272008-04-14 22:03:09 +0000381void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000382 // Two cases: either the decl could be in the main file, or it could be in a
383 // #included file. If the former, rewrite it now. If the later, check to see
384 // if we rewrote the #include/#import.
385 SourceLocation Loc = D->getLocation();
386 Loc = SM->getLogicalLoc(Loc);
387
388 // If this is for a builtin, ignore it.
389 if (Loc.isInvalid()) return;
390
Steve Naroffebf2b562007-10-23 23:50:29 +0000391 // Look for built-in declarations that we need to refer during the rewrite.
392 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000393 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000394 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000395 // declared in <Foundation/NSString.h>
396 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
397 ConstantStringClassReference = FVD;
398 return;
399 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000400 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000401 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000402 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000403 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000404 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000405 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000406 } else if (ObjCForwardProtocolDecl *FP =
407 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000408 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000409 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000410 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000411 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000412 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000413}
414
Chris Lattnerf04da132007-10-24 17:06:59 +0000415/// HandleDeclInMainFile - This is called for each top-level decl defined in the
416/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000417void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000418 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
419 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000420 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000421
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000422 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000423 if (Stmt *Body = MD->getBody()) {
424 //Body->dump();
425 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000426 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000427 CurMethodDecl = 0;
428 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000429 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000430 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000431 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000432 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000433 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000434 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000435 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000436 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000437 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000438 if (VD->getInit())
439 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
440 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000441 // Nothing yet.
442}
443
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000444void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000445 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000446
447 // Rewrite tabs if we care.
448 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000449
Steve Naroffa7b402d2008-03-28 22:26:09 +0000450 if (Diags.hasErrorOccurred())
451 return;
452
453 // Create the output file.
454
Ted Kremeneka95d3752008-09-13 05:16:45 +0000455 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
456 llvm::raw_ostream *OutFile;
Steve Naroffa7b402d2008-03-28 22:26:09 +0000457 if (OutFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000458 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000459 } else if (!OutFileName.empty()) {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000460 std::string Err;
461 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), Err);
462 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000463 } else if (InFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000464 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000465 } else {
466 llvm::sys::Path Path(InFileName);
467 Path.eraseSuffix();
468 Path.appendSuffix("cpp");
Ted Kremeneka95d3752008-09-13 05:16:45 +0000469 std::string Err;
470 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), Err);
471 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000472 }
473
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000474 RewriteInclude();
475
Steve Naroffba92b2e2008-03-27 22:29:16 +0000476 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
477 Preamble.c_str(), Preamble.size(), false);
478
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000479 // Rewrite Objective-c meta data*
480 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000481 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000482
Chris Lattnerf04da132007-10-24 17:06:59 +0000483 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
484 // we are done.
485 if (const RewriteBuffer *RewriteBuf =
486 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000487 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000488 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000489 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000490 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000491 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000492 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000493 *OutFile << ResultStr;
Ted Kremeneka95d3752008-09-13 05:16:45 +0000494 OutFile->flush();
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000495}
496
Chris Lattnerf04da132007-10-24 17:06:59 +0000497//===----------------------------------------------------------------------===//
498// Syntactic (non-AST) Rewriting Code
499//===----------------------------------------------------------------------===//
500
Steve Naroffb29b4272008-04-14 22:03:09 +0000501void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000502 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
503 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
504 const char *MainBufStart = MainBuf.first;
505 const char *MainBufEnd = MainBuf.second;
506 size_t ImportLen = strlen("import");
507 size_t IncludeLen = strlen("include");
508
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000509 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000510 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
511 if (*BufPtr == '#') {
512 if (++BufPtr == MainBufEnd)
513 return;
514 while (*BufPtr == ' ' || *BufPtr == '\t')
515 if (++BufPtr == MainBufEnd)
516 return;
517 if (!strncmp(BufPtr, "import", ImportLen)) {
518 // replace import with include
519 SourceLocation ImportLoc =
520 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000521 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000522 BufPtr += ImportLen;
523 }
524 }
525 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000526}
527
Steve Naroffb29b4272008-04-14 22:03:09 +0000528void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000529 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
530 const char *MainBufStart = MainBuf.first;
531 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000532
Chris Lattnerf04da132007-10-24 17:06:59 +0000533 // Loop over the whole file, looking for tabs.
534 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
535 if (*BufPtr != '\t')
536 continue;
537
538 // Okay, we found a tab. This tab will turn into at least one character,
539 // but it depends on which 'virtual column' it is in. Compute that now.
540 unsigned VCol = 0;
541 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
542 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
543 ++VCol;
544
545 // Okay, now that we know the virtual column, we know how many spaces to
546 // insert. We assume 8-character tab-stops.
547 unsigned Spaces = 8-(VCol & 7);
548
549 // Get the location of the tab.
550 SourceLocation TabLoc =
551 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
552
553 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000554 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000555 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000556}
557
558
Steve Naroffb29b4272008-04-14 22:03:09 +0000559void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000560 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000561 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000562
563 // Get the start location and compute the semi location.
564 SourceLocation startLoc = ClassDecl->getLocation();
565 const char *startBuf = SM->getCharacterData(startLoc);
566 const char *semiPtr = strchr(startBuf, ';');
567
568 // Translate to typedef's that forward reference structs with the same name
569 // as the class. As a convenience, we include the original declaration
570 // as a comment.
571 std::string typedefString;
572 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000573 typedefString.append(startBuf, semiPtr-startBuf+1);
574 typedefString += "\n";
575 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000576 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000577 typedefString += "#ifndef _REWRITER_typedef_";
578 typedefString += ForwardDecl->getName();
579 typedefString += "\n";
580 typedefString += "#define _REWRITER_typedef_";
581 typedefString += ForwardDecl->getName();
582 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000583 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000584 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000585 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000586 }
587
588 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000589 ReplaceText(startLoc, semiPtr-startBuf+1,
590 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000591}
592
Steve Naroffb29b4272008-04-14 22:03:09 +0000593void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000594 SourceLocation LocStart = Method->getLocStart();
595 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000596
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000597 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000598 InsertText(LocStart, "#if 0\n", 6);
599 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000600 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000601 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000602 }
603}
604
Steve Naroffb29b4272008-04-14 22:03:09 +0000605void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000606{
Chris Lattner55d13b42008-03-16 21:23:50 +0000607 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000608 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000609 SourceLocation Loc = Property->getLocation();
610
Chris Lattneraadaf782008-01-31 19:51:04 +0000611 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000612
613 // FIXME: handle properties that are declared across multiple lines.
614 }
615}
616
Steve Naroffb29b4272008-04-14 22:03:09 +0000617void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000618 SourceLocation LocStart = CatDecl->getLocStart();
619
620 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000621 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000622
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000623 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000624 E = CatDecl->instmeth_end(); I != E; ++I)
625 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000626 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000627 E = CatDecl->classmeth_end(); I != E; ++I)
628 RewriteMethodDeclaration(*I);
629
Steve Naroff423cb562007-10-30 13:30:57 +0000630 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000631 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000632}
633
Steve Naroffb29b4272008-04-14 22:03:09 +0000634void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000635 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000636
Steve Naroff752d6ef2007-10-30 16:42:30 +0000637 SourceLocation LocStart = PDecl->getLocStart();
638
639 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000640 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000641
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000642 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000643 E = PDecl->instmeth_end(); I != E; ++I)
644 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000645 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000646 E = PDecl->classmeth_end(); I != E; ++I)
647 RewriteMethodDeclaration(*I);
648
Steve Naroff752d6ef2007-10-30 16:42:30 +0000649 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000650 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000651 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000652
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000653 // Must comment out @optional/@required
654 const char *startBuf = SM->getCharacterData(LocStart);
655 const char *endBuf = SM->getCharacterData(LocEnd);
656 for (const char *p = startBuf; p < endBuf; p++) {
657 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
658 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000659 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000660 ReplaceText(OptionalLoc, strlen("@optional"),
661 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000662
663 }
664 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
665 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000666 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000667 ReplaceText(OptionalLoc, strlen("@required"),
668 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000669
670 }
671 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000672}
673
Steve Naroffb29b4272008-04-14 22:03:09 +0000674void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000675 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000676 if (LocStart.isInvalid())
677 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000678 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000679 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000680}
681
Steve Naroffb29b4272008-04-14 22:03:09 +0000682void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000683 std::string &ResultStr) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000684 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000685 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000686 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000687 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000688 else if (OMD->getResultType()->isFunctionPointerType()) {
689 // needs special handling, since pointer-to-functions have special
690 // syntax (where a decaration models use).
691 QualType retType = OMD->getResultType();
692 if (const PointerType* PT = retType->getAsPointerType()) {
693 QualType PointeeTy = PT->getPointeeType();
694 if ((FPRetType = PointeeTy->getAsFunctionType())) {
695 ResultStr += FPRetType->getResultType().getAsString();
696 ResultStr += "(*";
697 }
698 }
699 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000700 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000701 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000702
703 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000704 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000705
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000706 if (OMD->isInstance())
707 NameStr += "_I_";
708 else
709 NameStr += "_C_";
710
711 NameStr += OMD->getClassInterface()->getName();
712 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000713
714 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000715 if (ObjCCategoryImplDecl *CID =
716 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000717 NameStr += CID->getName();
718 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000719 }
Steve Naroff563b8282008-04-04 22:23:44 +0000720 // Append selector names, replacing ':' with '_'
721 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000722 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000723 else {
724 std::string selString = OMD->getSelector().getName();
725 int len = selString.size();
726 for (int i = 0; i < len; i++)
727 if (selString[i] == ':')
728 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000729 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000730 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000731 // Remember this name for metadata emission
732 MethodInternalNames[OMD] = NameStr;
733 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000734
735 // Rewrite arguments
736 ResultStr += "(";
737
738 // invisible arguments
739 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000740 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000741 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000742 if (!LangOpts.Microsoft) {
743 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
744 ResultStr += "struct ";
745 }
746 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000747 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000748 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000749 }
750 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000751 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000752
753 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000754 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000755 ResultStr += " _cmd";
756
757 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000758 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000759 ParmVarDecl *PDecl = OMD->getParamDecl(i);
760 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000761 if (PDecl->getType()->isObjCQualifiedIdType()) {
762 ResultStr += "id ";
763 ResultStr += PDecl->getName();
764 } else {
765 std::string Name = PDecl->getName();
766 PDecl->getType().getAsStringInternal(Name);
767 ResultStr += Name;
768 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000769 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000770 if (OMD->isVariadic())
771 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000772 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000773
Steve Naroff76e429d2008-07-16 14:40:40 +0000774 if (FPRetType) {
775 ResultStr += ")"; // close the precedence "scope" for "*".
776
777 // Now, emit the argument types (if any).
778 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
779 ResultStr += "(";
780 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
781 if (i) ResultStr += ", ";
782 std::string ParamStr = FT->getArgType(i).getAsString();
783 ResultStr += ParamStr;
784 }
785 if (FT->isVariadic()) {
786 if (FT->getNumArgs()) ResultStr += ", ";
787 ResultStr += "...";
788 }
789 ResultStr += ")";
790 } else {
791 ResultStr += "()";
792 }
793 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000794}
Steve Naroffb29b4272008-04-14 22:03:09 +0000795void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000796 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
797 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000798
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000799 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000800 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000801 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000802 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000803
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000804 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000805 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
806 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000807 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000808 ObjCMethodDecl *OMD = *I;
809 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000810 SourceLocation LocStart = OMD->getLocStart();
811 SourceLocation LocEnd = OMD->getBody()->getLocStart();
812
813 const char *startBuf = SM->getCharacterData(LocStart);
814 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000815 ReplaceText(LocStart, endBuf-startBuf,
816 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000817 }
818
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000819 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000820 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
821 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000822 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000823 ObjCMethodDecl *OMD = *I;
824 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000825 SourceLocation LocStart = OMD->getLocStart();
826 SourceLocation LocEnd = OMD->getBody()->getLocStart();
827
828 const char *startBuf = SM->getCharacterData(LocStart);
829 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000830 ReplaceText(LocStart, endBuf-startBuf,
831 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000832 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000833 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000834 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000835 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000836 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000837}
838
Steve Naroffb29b4272008-04-14 22:03:09 +0000839void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000840 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000841 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000842 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000843 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000844 ResultStr += ClassDecl->getName();
845 ResultStr += "\n";
846 ResultStr += "#define _REWRITER_typedef_";
847 ResultStr += ClassDecl->getName();
848 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000849 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000850 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000851 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000852 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000853 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000854 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000855 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000856
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000857 RewriteProperties(ClassDecl->getNumPropertyDecl(),
858 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000859 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000860 E = ClassDecl->instmeth_end(); I != E; ++I)
861 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000862 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000863 E = ClassDecl->classmeth_end(); I != E; ++I)
864 RewriteMethodDeclaration(*I);
865
Steve Naroff2feac5e2007-10-30 03:43:13 +0000866 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000867 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000868}
869
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000870Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
871 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000872 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000873 if (CurMethodDecl) {
874 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000875 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
876 // lookup which class implements the instance variable.
877 ObjCInterfaceDecl *clsDeclared = 0;
878 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
879 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
880
881 // Synthesize an explicit cast to gain access to the ivar.
882 std::string RecName = clsDeclared->getIdentifier()->getName();
883 RecName += "_IMPL";
884 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000885 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000886 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +0000887 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
888 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000889 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
890 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +0000891 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000892 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
893 IV->getBase()->getLocEnd(),
894 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000895 if (IV->isFreeIvar() &&
896 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000897 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
898 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000899 ReplaceStmt(IV, ME);
900 delete IV;
901 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000902 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000903
904 ReplaceStmt(IV->getBase(), PE);
905 // Cannot delete IV->getBase(), since PE points to it.
906 // Replace the old base with the cast. This is important when doing
907 // embedded rewrites. For example, [newInv->_container addObject:0].
908 IV->setBase(PE);
909 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000910 }
Steve Naroff84472a82008-04-18 21:55:08 +0000911 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000912 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
913
914 // Explicit ivar refs need to have a cast inserted.
915 // FIXME: consider sharing some of this code with the code above.
916 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000917 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000918 // lookup which class implements the instance variable.
919 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000920 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000921 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
922
923 // Synthesize an explicit cast to gain access to the ivar.
924 std::string RecName = clsDeclared->getIdentifier()->getName();
925 RecName += "_IMPL";
926 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000927 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000928 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +0000929 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
930 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000931 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
932 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +0000933 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +0000934 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
935 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +0000936 ReplaceStmt(IV->getBase(), PE);
937 // Cannot delete IV->getBase(), since PE points to it.
938 // Replace the old base with the cast. This is important when doing
939 // embedded rewrites. For example, [newInv->_container addObject:0].
940 IV->setBase(PE);
941 return IV;
942 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000943 }
Steve Naroff84472a82008-04-18 21:55:08 +0000944 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000945}
946
Chris Lattnerf04da132007-10-24 17:06:59 +0000947//===----------------------------------------------------------------------===//
948// Function Body / Expression rewriting
949//===----------------------------------------------------------------------===//
950
Steve Naroffb29b4272008-04-14 22:03:09 +0000951Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000952 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
953 isa<DoStmt>(S) || isa<ForStmt>(S))
954 Stmts.push_back(S);
955 else if (isa<ObjCForCollectionStmt>(S)) {
956 Stmts.push_back(S);
957 ObjCBcLabelNo.push_back(++BcLabelCount);
958 }
959
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000960 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner338d1e22008-01-31 05:10:40 +0000961
962 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000963 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
964 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000965 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000966 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000967 if (newStmt)
968 *CI = newStmt;
969 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000970
971 // Handle specific things.
972 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
973 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000974
975 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000976 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroffb42f8412007-11-05 14:50:49 +0000977
978 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
979 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000980
Steve Naroffbeaf2992007-11-03 11:27:19 +0000981 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
982 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000983
Steve Naroff934f2762007-10-24 22:48:43 +0000984 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
985 // Before we rewrite it, put the original message expression in a comment.
986 SourceLocation startLoc = MessExpr->getLocStart();
987 SourceLocation endLoc = MessExpr->getLocEnd();
988
989 const char *startBuf = SM->getCharacterData(startLoc);
990 const char *endBuf = SM->getCharacterData(endLoc);
991
992 std::string messString;
993 messString += "// ";
994 messString.append(startBuf, endBuf-startBuf+1);
995 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000996
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000997 // FIXME: Missing definition of
998 // InsertText(clang::SourceLocation, char const*, unsigned int).
999 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +00001000 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001001 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +00001002 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001003 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001004
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
1006 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +00001007
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001008 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
1009 return RewriteObjCSynchronizedStmt(StmtTry);
1010
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001011 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
1012 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001013
1014 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
1015 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001016
1017 if (ObjCForCollectionStmt *StmtForCollection =
1018 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001019 return RewriteObjCForCollectionStmt(StmtForCollection,
1020 OrigStmtRange.getEnd());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001021 if (BreakStmt *StmtBreakStmt =
1022 dyn_cast<BreakStmt>(S))
1023 return RewriteBreakStmt(StmtBreakStmt);
1024 if (ContinueStmt *StmtContinueStmt =
1025 dyn_cast<ContinueStmt>(S))
1026 return RewriteContinueStmt(StmtContinueStmt);
Steve Naroff4f95b752008-07-29 18:15:38 +00001027
Ted Kremenekab9bae72008-10-06 22:45:07 +00001028 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
1029 // and cast exprs.
1030 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
1031 // FIXME: What we're doing here is modifying the type-specifier that
1032 // precedes the first Decl. In the future the DeclGroup should have
1033 // a separate type-specifier that we can rewrite.
1034 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
1035 }
1036
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001037 if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(S))
Steve Naroff4f95b752008-07-29 18:15:38 +00001038 RewriteObjCQualifiedInterfaceTypes(CE);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001039
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001040 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1041 isa<DoStmt>(S) || isa<ForStmt>(S)) {
1042 assert(!Stmts.empty() && "Statement stack is empty");
1043 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
1044 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
1045 && "Statement stack mismatch");
1046 Stmts.pop_back();
1047 }
Steve Naroff874e2322007-11-15 10:28:18 +00001048#if 0
1049 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
1050 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
1051 // Get the new text.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001052 std::string SStr;
1053 llvm::raw_string_ostream Buf(SStr);
Steve Naroff874e2322007-11-15 10:28:18 +00001054 Replacement->printPretty(Buf);
1055 const std::string &Str = Buf.str();
1056
1057 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001058 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +00001059 delete S;
1060 return Replacement;
1061 }
1062#endif
Chris Lattnere64b7772007-10-24 16:57:36 +00001063 // Return this stmt unmodified.
1064 return S;
Chris Lattner311ff022007-10-16 22:36:42 +00001065}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001066
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001067/// SynthCountByEnumWithState - To print:
1068/// ((unsigned int (*)
1069/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1070/// (void *)objc_msgSend)((id)l_collection,
1071/// sel_registerName(
1072/// "countByEnumeratingWithState:objects:count:"),
1073/// &enumState,
1074/// (id *)items, (unsigned int)16)
1075///
Steve Naroffb29b4272008-04-14 22:03:09 +00001076void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001077 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1078 "id *, unsigned int))(void *)objc_msgSend)";
1079 buf += "\n\t\t";
1080 buf += "((id)l_collection,\n\t\t";
1081 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1082 buf += "\n\t\t";
1083 buf += "&enumState, "
1084 "(id *)items, (unsigned int)16)";
1085}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001086
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001087/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1088/// statement to exit to its outer synthesized loop.
1089///
Steve Naroffb29b4272008-04-14 22:03:09 +00001090Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001091 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1092 return S;
1093 // replace break with goto __break_label
1094 std::string buf;
1095
1096 SourceLocation startLoc = S->getLocStart();
1097 buf = "goto __break_label_";
1098 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001099 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001100
1101 return 0;
1102}
1103
1104/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1105/// statement to continue with its inner synthesized loop.
1106///
Steve Naroffb29b4272008-04-14 22:03:09 +00001107Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001108 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1109 return S;
1110 // replace continue with goto __continue_label
1111 std::string buf;
1112
1113 SourceLocation startLoc = S->getLocStart();
1114 buf = "goto __continue_label_";
1115 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001116 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001117
1118 return 0;
1119}
1120
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001121/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001122/// It rewrites:
1123/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001124
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001125/// Into:
1126/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001127/// type elem;
1128/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001129/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001130/// id l_collection = (id)collection;
1131/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1132/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001133/// if (limit) {
1134/// unsigned long startMutations = *enumState.mutationsPtr;
1135/// do {
1136/// unsigned long counter = 0;
1137/// do {
1138/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001139/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001140/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001141/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001142/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001143/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001144/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1145/// objects:items count:16]);
1146/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001147/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001148/// }
1149/// else
1150/// elem = nil;
1151/// }
1152///
Steve Naroffb29b4272008-04-14 22:03:09 +00001153Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001154 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001155 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1156 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1157 "ObjCForCollectionStmt Statement stack mismatch");
1158 assert(!ObjCBcLabelNo.empty() &&
1159 "ObjCForCollectionStmt - Label No stack empty");
1160
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001161 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001162 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001163 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001164 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001165 std::string buf;
1166 buf = "\n{\n\t";
1167 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1168 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001169 ScopedDecl* D = DS->getSolitaryDecl();
1170 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001171 elementTypeAsString = ElementType.getAsString();
1172 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001173 buf += " ";
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001174 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001175 buf += elementName;
1176 buf += ";\n\t";
1177 }
Chris Lattner06767512008-04-08 05:52:18 +00001178 else {
1179 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001180 elementName = DR->getDecl()->getName();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001181 elementTypeAsString
1182 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001183 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001184
1185 // struct __objcFastEnumerationState enumState = { 0 };
1186 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1187 // id items[16];
1188 buf += "id items[16];\n\t";
1189 // id l_collection = (id)
1190 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001191 // Find start location of 'collection' the hard way!
1192 const char *startCollectionBuf = startBuf;
1193 startCollectionBuf += 3; // skip 'for'
1194 startCollectionBuf = strchr(startCollectionBuf, '(');
1195 startCollectionBuf++; // skip '('
1196 // find 'in' and skip it.
1197 while (*startCollectionBuf != ' ' ||
1198 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1199 (*(startCollectionBuf+3) != ' ' &&
1200 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1201 startCollectionBuf++;
1202 startCollectionBuf += 3;
1203
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001204 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001205 ReplaceText(startLoc, startCollectionBuf - startBuf,
1206 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001207 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001208 SourceLocation rightParenLoc = S->getRParenLoc();
1209 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1210 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001211 buf = ";\n\t";
1212
1213 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1214 // objects:items count:16];
1215 // which is synthesized into:
1216 // unsigned int limit =
1217 // ((unsigned int (*)
1218 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1219 // (void *)objc_msgSend)((id)l_collection,
1220 // sel_registerName(
1221 // "countByEnumeratingWithState:objects:count:"),
1222 // (struct __objcFastEnumerationState *)&state,
1223 // (id *)items, (unsigned int)16);
1224 buf += "unsigned long limit =\n\t\t";
1225 SynthCountByEnumWithState(buf);
1226 buf += ";\n\t";
1227 /// if (limit) {
1228 /// unsigned long startMutations = *enumState.mutationsPtr;
1229 /// do {
1230 /// unsigned long counter = 0;
1231 /// do {
1232 /// if (startMutations != *enumState.mutationsPtr)
1233 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001234 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001235 buf += "if (limit) {\n\t";
1236 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1237 buf += "do {\n\t\t";
1238 buf += "unsigned long counter = 0;\n\t\t";
1239 buf += "do {\n\t\t\t";
1240 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1241 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1242 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001243 buf += " = (";
1244 buf += elementTypeAsString;
1245 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001246 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001247 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001248
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001249 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001250 /// } while (counter < limit);
1251 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1252 /// objects:items count:16]);
1253 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001254 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001255 /// }
1256 /// else
1257 /// elem = nil;
1258 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001259 ///
1260 buf = ";\n\t";
1261 buf += "__continue_label_";
1262 buf += utostr(ObjCBcLabelNo.back());
1263 buf += ": ;";
1264 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001265 buf += "} while (counter < limit);\n\t";
1266 buf += "} while (limit = ";
1267 SynthCountByEnumWithState(buf);
1268 buf += ");\n\t";
1269 buf += elementName;
1270 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001271 buf += "__break_label_";
1272 buf += utostr(ObjCBcLabelNo.back());
1273 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001274 buf += "}\n\t";
1275 buf += "else\n\t\t";
1276 buf += elementName;
1277 buf += " = nil;\n";
1278 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001279
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001280 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001281 if (isa<CompoundStmt>(S->getBody())) {
1282 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1283 InsertText(endBodyLoc, buf.c_str(), buf.size());
1284 } else {
1285 /* Need to treat single statements specially. For example:
1286 *
1287 * for (A *a in b) if (stuff()) break;
1288 * for (A *a in b) xxxyy;
1289 *
1290 * The following code simply scans ahead to the semi to find the actual end.
1291 */
1292 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1293 const char *semiBuf = strchr(stmtBuf, ';');
1294 assert(semiBuf && "Can't find ';'");
1295 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1296 InsertText(endBodyLoc, buf.c_str(), buf.size());
1297 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001298 Stmts.pop_back();
1299 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001300 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001301}
1302
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001303/// RewriteObjCSynchronizedStmt -
1304/// This routine rewrites @synchronized(expr) stmt;
1305/// into:
1306/// objc_sync_enter(expr);
1307/// @try stmt @finally { objc_sync_exit(expr); }
1308///
Steve Naroffb29b4272008-04-14 22:03:09 +00001309Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001310 // Get the start location and compute the semi location.
1311 SourceLocation startLoc = S->getLocStart();
1312 const char *startBuf = SM->getCharacterData(startLoc);
1313
1314 assert((*startBuf == '@') && "bogus @synchronized location");
1315
1316 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001317 buf = "objc_sync_enter((id)";
1318 const char *lparenBuf = startBuf;
1319 while (*lparenBuf != '(') lparenBuf++;
1320 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001321 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1322 // the sync expression is typically a message expression that's already
1323 // been rewritten! (which implies the SourceLocation's are invalid).
1324 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001325 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001326 while (*endBuf != ')') endBuf--;
1327 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001328 buf = ");\n";
1329 // declare a new scope with two variables, _stack and _rethrow.
1330 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1331 buf += "int buf[18/*32-bit i386*/];\n";
1332 buf += "char *pointers[4];} _stack;\n";
1333 buf += "id volatile _rethrow = 0;\n";
1334 buf += "objc_exception_try_enter(&_stack);\n";
1335 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001336 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001337 startLoc = S->getSynchBody()->getLocEnd();
1338 startBuf = SM->getCharacterData(startLoc);
1339
Steve Naroffc7089f12008-08-19 13:04:19 +00001340 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001341 SourceLocation lastCurlyLoc = startLoc;
1342 buf = "}\nelse {\n";
1343 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1344 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001345 buf += " objc_sync_exit(";
Steve Naroff3498cc92008-08-21 13:03:03 +00001346 Expr *syncExpr = new ExplicitCastExpr(Context->getObjCIdType(),
1347 S->getSynchExpr(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001348 std::string syncExprBufS;
1349 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001350 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001351 buf += syncExprBuf.str();
1352 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001353 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1354 buf += "}\n";
1355 buf += "}";
1356
Chris Lattneraadaf782008-01-31 19:51:04 +00001357 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001358 return 0;
1359}
1360
Steve Naroffb29b4272008-04-14 22:03:09 +00001361Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001362 // Get the start location and compute the semi location.
1363 SourceLocation startLoc = S->getLocStart();
1364 const char *startBuf = SM->getCharacterData(startLoc);
1365
1366 assert((*startBuf == '@') && "bogus @try location");
1367
1368 std::string buf;
1369 // declare a new scope with two variables, _stack and _rethrow.
1370 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1371 buf += "int buf[18/*32-bit i386*/];\n";
1372 buf += "char *pointers[4];} _stack;\n";
1373 buf += "id volatile _rethrow = 0;\n";
1374 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001375 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001376
Chris Lattneraadaf782008-01-31 19:51:04 +00001377 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001378
1379 startLoc = S->getTryBody()->getLocEnd();
1380 startBuf = SM->getCharacterData(startLoc);
1381
1382 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001383
Steve Naroff75730982007-11-07 04:08:17 +00001384 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001385 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1386 if (catchList) {
1387 startLoc = startLoc.getFileLocWithOffset(1);
1388 buf = " /* @catch begin */ else {\n";
1389 buf += " id _caught = objc_exception_extract(&_stack);\n";
1390 buf += " objc_exception_try_enter (&_stack);\n";
1391 buf += " if (_setjmp(_stack.buf))\n";
1392 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1393 buf += " else { /* @catch continue */";
1394
1395 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001396 } else { /* no catch list */
1397 buf = "}\nelse {\n";
1398 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1399 buf += "}";
1400 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001401 }
Steve Naroff75730982007-11-07 04:08:17 +00001402 bool sawIdTypedCatch = false;
1403 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001404 while (catchList) {
1405 Stmt *catchStmt = catchList->getCatchParamStmt();
1406
1407 if (catchList == S->getCatchStmts())
1408 buf = "if ("; // we are generating code for the first catch clause
1409 else
1410 buf = "else if (";
1411 startLoc = catchList->getLocStart();
1412 startBuf = SM->getCharacterData(startLoc);
1413
1414 assert((*startBuf == '@') && "bogus @catch location");
1415
1416 const char *lParenLoc = strchr(startBuf, '(');
1417
Steve Naroffbe4b3332008-02-01 22:08:12 +00001418 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001419 // Now rewrite the body...
1420 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001421 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1422 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001423 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1424 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001425 assert((*bodyBuf == '{') && "bogus @catch body location");
1426
1427 buf += "1) { id _tmp = _caught;";
1428 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1429 buf.c_str(), buf.size());
1430 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001431 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001432 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001433 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001434 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001435 sawIdTypedCatch = true;
1436 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001437 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001438
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001439 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001440 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001441 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001442 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001443 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001444 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001445 }
1446 }
1447 // Now rewrite the body...
1448 lastCatchBody = catchList->getCatchBody();
1449 SourceLocation rParenLoc = catchList->getRParenLoc();
1450 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1451 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1452 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1453 assert((*rParenBuf == ')') && "bogus @catch paren location");
1454 assert((*bodyBuf == '{') && "bogus @catch body location");
1455
1456 buf = " = _caught;";
1457 // Here we replace ") {" with "= _caught;" (which initializes and
1458 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001459 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001460 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001461 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001462 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001463 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001464 catchList = catchList->getNextCatchStmt();
1465 }
1466 // Complete the catch list...
1467 if (lastCatchBody) {
1468 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001469 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1470 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001471
Steve Naroff378f47a2008-09-11 15:29:03 +00001472 // Insert the last (implicit) else clause *before* the right curly brace.
1473 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1474 buf = "} /* last catch end */\n";
1475 buf += "else {\n";
1476 buf += " _rethrow = _caught;\n";
1477 buf += " objc_exception_try_exit(&_stack);\n";
1478 buf += "} } /* @catch end */\n";
1479 if (!S->getFinallyStmt())
1480 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001481 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001482
1483 // Set lastCurlyLoc
1484 lastCurlyLoc = lastCatchBody->getLocEnd();
1485 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001486 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001487 startLoc = finalStmt->getLocStart();
1488 startBuf = SM->getCharacterData(startLoc);
1489 assert((*startBuf == '@') && "bogus @finally start");
1490
1491 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001492 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001493
1494 Stmt *body = finalStmt->getFinallyBody();
1495 SourceLocation startLoc = body->getLocStart();
1496 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001497 assert(*SM->getCharacterData(startLoc) == '{' &&
1498 "bogus @finally body location");
1499 assert(*SM->getCharacterData(endLoc) == '}' &&
1500 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001501
1502 startLoc = startLoc.getFileLocWithOffset(1);
1503 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001504 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001505 endLoc = endLoc.getFileLocWithOffset(-1);
1506 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001507 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001508
1509 // Set lastCurlyLoc
1510 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001511 } else { /* no finally clause - make sure we synthesize an implicit one */
1512 buf = "{ /* implicit finally clause */\n";
1513 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1514 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1515 buf += "}";
1516 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001517 }
1518 // Now emit the final closing curly brace...
1519 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1520 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001521 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001522 return 0;
1523}
1524
Steve Naroffb29b4272008-04-14 22:03:09 +00001525Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001526 return 0;
1527}
1528
Steve Naroffb29b4272008-04-14 22:03:09 +00001529Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001530 return 0;
1531}
1532
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001533// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001534// the throw expression is typically a message expression that's already
1535// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001536Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001537 // Get the start location and compute the semi location.
1538 SourceLocation startLoc = S->getLocStart();
1539 const char *startBuf = SM->getCharacterData(startLoc);
1540
1541 assert((*startBuf == '@') && "bogus @throw location");
1542
1543 std::string buf;
1544 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001545 if (S->getThrowExpr())
1546 buf = "objc_exception_throw(";
1547 else // add an implicit argument
1548 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001549
1550 // handle "@ throw" correctly.
1551 const char *wBuf = strchr(startBuf, 'w');
1552 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1553 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1554
Steve Naroff2bd03922007-11-07 15:32:26 +00001555 const char *semiBuf = strchr(startBuf, ';');
1556 assert((*semiBuf == ';') && "@throw: can't find ';'");
1557 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1558 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001559 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001560 return 0;
1561}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001562
Steve Naroffb29b4272008-04-14 22:03:09 +00001563Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001564 // Create a new string expression.
1565 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001566 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001567 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001568 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1569 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001570 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001571 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001572
Chris Lattner07506182007-11-30 22:53:43 +00001573 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001574 delete Exp;
1575 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001576}
1577
Steve Naroffb29b4272008-04-14 22:03:09 +00001578Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001579 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1580 // Create a call to sel_registerName("selName").
1581 llvm::SmallVector<Expr*, 8> SelExprs;
1582 QualType argType = Context->getPointerType(Context->CharTy);
1583 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1584 Exp->getSelector().getName().size(),
1585 false, argType, SourceLocation(),
1586 SourceLocation()));
1587 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1588 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001589 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001590 delete Exp;
1591 return SelExp;
1592}
1593
Steve Naroffb29b4272008-04-14 22:03:09 +00001594CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001595 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001596 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001597 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001598
1599 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001600 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001601
1602 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001603 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001604 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1605
1606 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001607
Steve Naroff934f2762007-10-24 22:48:43 +00001608 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1609}
1610
Steve Naroffd5255f52007-11-01 13:24:47 +00001611static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1612 const char *&startRef, const char *&endRef) {
1613 while (startBuf < endBuf) {
1614 if (*startBuf == '<')
1615 startRef = startBuf; // mark the start.
1616 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001617 if (startRef && *startRef == '<') {
1618 endRef = startBuf; // mark the end.
1619 return true;
1620 }
1621 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001622 }
1623 startBuf++;
1624 }
1625 return false;
1626}
1627
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001628static void scanToNextArgument(const char *&argRef) {
1629 int angle = 0;
1630 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1631 if (*argRef == '<')
1632 angle++;
1633 else if (*argRef == '>')
1634 angle--;
1635 argRef++;
1636 }
1637 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1638}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001639
Steve Naroffb29b4272008-04-14 22:03:09 +00001640bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001641
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001642 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001643 return true;
1644
Steve Naroffd5255f52007-11-01 13:24:47 +00001645 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001646 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001647 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001648 return true; // we have "Class <Protocol> *".
1649 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001650 return false;
1651}
1652
Steve Naroff4f95b752008-07-29 18:15:38 +00001653void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1654 QualType Type = E->getType();
1655 if (needToScanForQualifiers(Type)) {
1656 SourceLocation Loc = E->getLocStart();
1657 const char *startBuf = SM->getCharacterData(Loc);
1658 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1659 const char *startRef = 0, *endRef = 0;
1660 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1661 // Get the locations of the startRef, endRef.
1662 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1663 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1664 // Comment out the protocol references.
1665 InsertText(LessLoc, "/*", 2);
1666 InsertText(GreaterLoc, "*/", 2);
1667 }
1668 }
1669}
1670
Steve Naroffb29b4272008-04-14 22:03:09 +00001671void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001672 SourceLocation Loc;
1673 QualType Type;
1674 const FunctionTypeProto *proto = 0;
1675 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1676 Loc = VD->getLocation();
1677 Type = VD->getType();
1678 }
1679 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1680 Loc = FD->getLocation();
1681 // Check for ObjC 'id' and class types that have been adorned with protocol
1682 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1683 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1684 assert(funcType && "missing function type");
1685 proto = dyn_cast<FunctionTypeProto>(funcType);
1686 if (!proto)
1687 return;
1688 Type = proto->getResultType();
1689 }
1690 else
1691 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001692
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001693 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001694 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001695
1696 const char *endBuf = SM->getCharacterData(Loc);
1697 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001698 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001699 startBuf--; // scan backward (from the decl location) for return type.
1700 const char *startRef = 0, *endRef = 0;
1701 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1702 // Get the locations of the startRef, endRef.
1703 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1704 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1705 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001706 InsertText(LessLoc, "/*", 2);
1707 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001708 }
1709 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001710 if (!proto)
1711 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001712 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001713 const char *startBuf = SM->getCharacterData(Loc);
1714 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001715 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1716 if (needToScanForQualifiers(proto->getArgType(i))) {
1717 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001718
Steve Naroffd5255f52007-11-01 13:24:47 +00001719 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001720 // scan forward (from the decl location) for argument types.
1721 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001722 const char *startRef = 0, *endRef = 0;
1723 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1724 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001725 SourceLocation LessLoc =
1726 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1727 SourceLocation GreaterLoc =
1728 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001729 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001730 InsertText(LessLoc, "/*", 2);
1731 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001732 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001733 startBuf = ++endBuf;
1734 }
1735 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001736 // If the function name is derived from a macro expansion, then the
1737 // argument buffer will not follow the name. Need to speak with Chris.
1738 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001739 startBuf++; // scan forward (from the decl location) for argument types.
1740 startBuf++;
1741 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001742 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001743}
1744
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001745// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001746void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001747 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1748 llvm::SmallVector<QualType, 16> ArgTys;
1749 ArgTys.push_back(Context->getPointerType(
1750 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001751 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001752 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001753 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001754 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001755 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001756 SelGetUidIdent, getFuncType,
1757 FunctionDecl::Extern, false, 0);
1758}
1759
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001760// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001761void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001762 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1763 llvm::SmallVector<QualType, 16> ArgTys;
1764 ArgTys.push_back(Context->getPointerType(
1765 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001766 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001767 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001768 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001769 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001770 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001771 SelGetProtoIdent, getFuncType,
1772 FunctionDecl::Extern, false, 0);
1773}
1774
Steve Naroffb29b4272008-04-14 22:03:09 +00001775void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001776 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001777 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001778 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001779 return;
1780 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001781 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001782}
1783
Steve Naroffc0a123c2008-03-11 17:37:02 +00001784// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001785void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001786 if (SuperContructorFunctionDecl)
1787 return;
1788 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1789 llvm::SmallVector<QualType, 16> ArgTys;
1790 QualType argT = Context->getObjCIdType();
1791 assert(!argT.isNull() && "Can't find 'id' type");
1792 ArgTys.push_back(argT);
1793 ArgTys.push_back(argT);
1794 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1795 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001796 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001797 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001798 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001799 msgSendIdent, msgSendType,
1800 FunctionDecl::Extern, false, 0);
1801}
1802
Steve Naroff09b266e2007-10-30 23:14:51 +00001803// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001804void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001805 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1806 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001807 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001808 assert(!argT.isNull() && "Can't find 'id' type");
1809 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001810 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001811 assert(!argT.isNull() && "Can't find 'SEL' type");
1812 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001813 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001814 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001815 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001816 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001817 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001818 msgSendIdent, msgSendType,
1819 FunctionDecl::Extern, false, 0);
1820}
1821
Steve Naroff874e2322007-11-15 10:28:18 +00001822// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001823void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001824 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1825 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001826 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001827 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001828 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001829 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1830 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1831 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001832 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001833 assert(!argT.isNull() && "Can't find 'SEL' type");
1834 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001835 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001836 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001837 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001838 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001839 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001840 msgSendIdent, msgSendType,
1841 FunctionDecl::Extern, false, 0);
1842}
1843
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001844// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001845void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001846 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1847 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001848 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001849 assert(!argT.isNull() && "Can't find 'id' type");
1850 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001851 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001852 assert(!argT.isNull() && "Can't find 'SEL' type");
1853 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001854 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001855 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001856 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001857 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001858 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001859 msgSendIdent, msgSendType,
1860 FunctionDecl::Extern, false, 0);
1861}
1862
1863// SynthMsgSendSuperStretFunctionDecl -
1864// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001865void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001866 IdentifierInfo *msgSendIdent =
1867 &Context->Idents.get("objc_msgSendSuper_stret");
1868 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001869 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001870 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001871 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001872 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1873 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1874 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001875 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001876 assert(!argT.isNull() && "Can't find 'SEL' type");
1877 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001878 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001879 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001880 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001881 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001882 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001883 msgSendIdent, msgSendType,
1884 FunctionDecl::Extern, false, 0);
1885}
1886
Steve Naroff1284db82008-05-08 22:02:18 +00001887// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001888void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001889 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1890 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001891 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001892 assert(!argT.isNull() && "Can't find 'id' type");
1893 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001894 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001895 assert(!argT.isNull() && "Can't find 'SEL' type");
1896 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001897 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001898 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001899 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001900 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001901 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001902 msgSendIdent, msgSendType,
1903 FunctionDecl::Extern, false, 0);
1904}
1905
Steve Naroff09b266e2007-10-30 23:14:51 +00001906// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001907void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001908 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1909 llvm::SmallVector<QualType, 16> ArgTys;
1910 ArgTys.push_back(Context->getPointerType(
1911 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001912 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001913 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001914 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001915 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001916 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001917 getClassIdent, getClassType,
1918 FunctionDecl::Extern, false, 0);
1919}
1920
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001921// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001922void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001923 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1924 llvm::SmallVector<QualType, 16> ArgTys;
1925 ArgTys.push_back(Context->getPointerType(
1926 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001927 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001928 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001929 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001930 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001931 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001932 getClassIdent, getClassType,
1933 FunctionDecl::Extern, false, 0);
1934}
1935
Steve Naroffb29b4272008-04-14 22:03:09 +00001936Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001937 QualType strType = getConstantStringStructType();
1938
1939 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001940
1941 std::string tmpName = InFileName;
1942 unsigned i;
1943 for (i=0; i < tmpName.length(); i++) {
1944 char c = tmpName.at(i);
1945 // replace any non alphanumeric characters with '_'.
1946 if (!isalpha(c) && (c < '0' || c > '9'))
1947 tmpName[i] = '_';
1948 }
1949 S += tmpName;
1950 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001951 S += utostr(NumObjCStringLiterals++);
1952
Steve Naroffba92b2e2008-03-27 22:29:16 +00001953 Preamble += "static __NSConstantStringImpl " + S;
1954 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1955 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001956 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001957 std::string prettyBufS;
1958 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001959 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001960 Preamble += prettyBuf.str();
1961 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001962 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001963 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001964
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001965 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001966 &Context->Idents.get(S.c_str()), strType,
1967 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001968 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1969 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1970 Context->getPointerType(DRE->getType()),
1971 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001972 // cast to NSConstantString *
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001973 CastExpr *cast = new ExplicitCastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001974 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001975 delete Exp;
1976 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001977}
1978
Steve Naroffb29b4272008-04-14 22:03:09 +00001979ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001980 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001981 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1982
Chris Lattnerd9f69102008-08-10 01:53:14 +00001983 if (PredefinedExpr *PDE = dyn_cast<PredefinedExpr>(recExpr))
1984 if (PDE->getIdentType() == PredefinedExpr::ObjCSuper) {
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001985 const PointerType *PT = PDE->getType()->getAsPointerType();
1986 assert(PT);
1987 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1988 return IT->getDecl();
1989 }
1990 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001991}
1992
1993// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001994QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001995 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001996 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001997 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001998 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001999 QualType FieldTypes[2];
2000
2001 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002002 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002003 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002004 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002005 // Create fields
2006 FieldDecl *FieldDecls[2];
2007
2008 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002009 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002010 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002011
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002012 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002013 }
2014 return Context->getTagDeclType(SuperStructDecl);
2015}
2016
Steve Naroffb29b4272008-04-14 22:03:09 +00002017QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002018 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002019 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002020 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002021 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002022 QualType FieldTypes[4];
2023
2024 // struct objc_object *receiver;
2025 FieldTypes[0] = Context->getObjCIdType();
2026 // int flags;
2027 FieldTypes[1] = Context->IntTy;
2028 // char *str;
2029 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2030 // long length;
2031 FieldTypes[3] = Context->LongTy;
2032 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002033 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002034
2035 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002036 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002037 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002038
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002039 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002040 }
2041 return Context->getTagDeclType(ConstantStringDecl);
2042}
2043
Steve Naroffb29b4272008-04-14 22:03:09 +00002044Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002045 if (!SelGetUidFunctionDecl)
2046 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002047 if (!MsgSendFunctionDecl)
2048 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002049 if (!MsgSendSuperFunctionDecl)
2050 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002051 if (!MsgSendStretFunctionDecl)
2052 SynthMsgSendStretFunctionDecl();
2053 if (!MsgSendSuperStretFunctionDecl)
2054 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002055 if (!MsgSendFpretFunctionDecl)
2056 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002057 if (!GetClassFunctionDecl)
2058 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002059 if (!GetMetaClassFunctionDecl)
2060 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002061
Steve Naroff874e2322007-11-15 10:28:18 +00002062 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002063 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2064 // May need to use objc_msgSend_stret() as well.
2065 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002066 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002067 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002068 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002069 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002070 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002071 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002072 }
Steve Naroff874e2322007-11-15 10:28:18 +00002073
Steve Naroff934f2762007-10-24 22:48:43 +00002074 // Synthesize a call to objc_msgSend().
2075 llvm::SmallVector<Expr*, 8> MsgExprs;
2076 IdentifierInfo *clsName = Exp->getClassName();
2077
2078 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2079 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002080 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2081 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002082 if (!strcmp(clsName->getName(), "super")) {
2083 MsgSendFlavor = MsgSendSuperFunctionDecl;
2084 if (MsgSendStretFlavor)
2085 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2086 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2087
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002088 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002089 CurMethodDecl->getClassInterface()->getSuperClass();
2090
2091 llvm::SmallVector<Expr*, 4> InitExprs;
2092
2093 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002094 InitExprs.push_back(new DeclRefExpr(
2095 CurMethodDecl->getSelfDecl(),
2096 Context->getObjCIdType(),
2097 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002098 llvm::SmallVector<Expr*, 8> ClsExprs;
2099 QualType argType = Context->getPointerType(Context->CharTy);
2100 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2101 SuperDecl->getIdentifier()->getLength(),
2102 false, argType, SourceLocation(),
2103 SourceLocation()));
2104 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2105 &ClsExprs[0],
2106 ClsExprs.size());
2107 // To turn off a warning, type-cast to 'id'
2108 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002109 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002110 Cls, SourceLocation())); // set 'super class', using objc_getClass().
2111 // struct objc_super
2112 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002113 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002114
Steve Naroff23f41272008-03-11 18:14:26 +00002115 if (LangOpts.Microsoft) {
2116 SynthSuperContructorFunctionDecl();
2117 // Simulate a contructor call...
2118 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2119 superType, SourceLocation());
2120 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2121 superType, SourceLocation());
2122 } else {
2123 // (struct objc_super) { <exprs from above> }
2124 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2125 &InitExprs[0], InitExprs.size(),
2126 SourceLocation());
2127 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2128 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002129 // struct objc_super *
2130 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2131 Context->getPointerType(SuperRep->getType()),
2132 SourceLocation());
2133 MsgExprs.push_back(Unop);
2134 } else {
2135 llvm::SmallVector<Expr*, 8> ClsExprs;
2136 QualType argType = Context->getPointerType(Context->CharTy);
2137 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2138 clsName->getLength(),
2139 false, argType, SourceLocation(),
2140 SourceLocation()));
2141 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2142 &ClsExprs[0],
2143 ClsExprs.size());
2144 MsgExprs.push_back(Cls);
2145 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002146 } else { // instance message.
2147 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002148
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002149 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002150 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002151 if (MsgSendStretFlavor)
2152 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002153 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2154
2155 llvm::SmallVector<Expr*, 4> InitExprs;
2156
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002157 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002158 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002159 new DeclRefExpr(CurMethodDecl->getSelfDecl(),
2160 Context->getObjCIdType(),
2161 SourceLocation()),
2162 SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002163
2164 llvm::SmallVector<Expr*, 8> ClsExprs;
2165 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002166 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2167 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002168 false, argType, SourceLocation(),
2169 SourceLocation()));
2170 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002171 &ClsExprs[0],
2172 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002173 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002174 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002175 new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002176 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002177 // struct objc_super
2178 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002179 Expr *SuperRep;
2180
2181 if (LangOpts.Microsoft) {
2182 SynthSuperContructorFunctionDecl();
2183 // Simulate a contructor call...
2184 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2185 superType, SourceLocation());
2186 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2187 superType, SourceLocation());
2188 } else {
2189 // (struct objc_super) { <exprs from above> }
2190 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2191 &InitExprs[0], InitExprs.size(),
2192 SourceLocation());
2193 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2194 }
Steve Naroff874e2322007-11-15 10:28:18 +00002195 // struct objc_super *
2196 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2197 Context->getPointerType(SuperRep->getType()),
2198 SourceLocation());
2199 MsgExprs.push_back(Unop);
2200 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002201 // Remove all type-casts because it may contain objc-style types; e.g.
2202 // Foo<Proto> *.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002203 while (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002204 recExpr = CE->getSubExpr();
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002205 recExpr = new ExplicitCastExpr(Context->getObjCIdType(), recExpr,
2206 SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002207 MsgExprs.push_back(recExpr);
2208 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002209 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002210 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002211 llvm::SmallVector<Expr*, 8> SelExprs;
2212 QualType argType = Context->getPointerType(Context->CharTy);
2213 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2214 Exp->getSelector().getName().size(),
2215 false, argType, SourceLocation(),
2216 SourceLocation()));
2217 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2218 &SelExprs[0], SelExprs.size());
2219 MsgExprs.push_back(SelExp);
2220
2221 // Now push any user supplied arguments.
2222 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002223 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002224 // Make all implicit casts explicit...ICE comes in handy:-)
2225 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2226 // Reuse the ICE type, it is exactly what the doctor ordered.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002227 userExpr = new ExplicitCastExpr(ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002228 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002229 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002230 }
2231 // Make id<P...> cast into an 'id' cast.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002232 else if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002233 if (CE->getType()->isObjCQualifiedIdType()) {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002234 while ((CE = dyn_cast<ExplicitCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002235 userExpr = CE->getSubExpr();
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002236 userExpr = new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002237 userExpr, SourceLocation());
2238 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002239 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002240 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002241 // We've transferred the ownership to MsgExprs. Null out the argument in
2242 // the original expression, since we will delete it below.
2243 Exp->setArg(i, 0);
2244 }
Steve Naroffab972d32007-11-04 22:37:50 +00002245 // Generate the funky cast.
2246 CastExpr *cast;
2247 llvm::SmallVector<QualType, 8> ArgTypes;
2248 QualType returnType;
2249
2250 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002251 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2252 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2253 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002254 ArgTypes.push_back(Context->getObjCIdType());
2255 ArgTypes.push_back(Context->getObjCSelType());
2256 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002257 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002258 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002259 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2260 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002261 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002262 ArgTypes.push_back(t);
2263 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002264 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2265 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002266 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002267 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002268 }
2269 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002270 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002271
2272 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002273 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2274 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002275
2276 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2277 // If we don't do this cast, we get the following bizarre warning/note:
2278 // xx.m:13: warning: function called through a non-compatible type
2279 // xx.m:13: note: if this code is reached, the program will abort
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002280 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Steve Naroffab972d32007-11-04 22:37:50 +00002281 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002282
Steve Naroffab972d32007-11-04 22:37:50 +00002283 // Now do the "normal" pointer to function cast.
2284 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002285 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002286 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002287 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002288 castType = Context->getPointerType(castType);
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002289 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002290
2291 // Don't forget the parens to enforce the proper binding.
2292 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2293
2294 const FunctionType *FT = msgSendType->getAsFunctionType();
2295 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2296 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002297 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002298 if (MsgSendStretFlavor) {
2299 // We have the method which returns a struct/union. Must also generate
2300 // call to objc_msgSend_stret and hang both varieties on a conditional
2301 // expression which dictate which one to envoke depending on size of
2302 // method's return type.
2303
2304 // Create a reference to the objc_msgSend_stret() declaration.
2305 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2306 SourceLocation());
2307 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002308 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002309 SourceLocation());
2310 // Now do the "normal" pointer to function cast.
2311 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002312 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002313 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002314 castType = Context->getPointerType(castType);
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002315 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002316
2317 // Don't forget the parens to enforce the proper binding.
2318 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2319
2320 FT = msgSendType->getAsFunctionType();
2321 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2322 FT->getResultType(), SourceLocation());
2323
2324 // Build sizeof(returnType)
2325 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2326 returnType, Context->getSizeType(),
2327 SourceLocation(), SourceLocation());
2328 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2329 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2330 // For X86 it is more complicated and some kind of target specific routine
2331 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002332 unsigned IntSize =
2333 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002334 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2335 Context->IntTy,
2336 SourceLocation());
2337 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2338 BinaryOperator::LE,
2339 Context->IntTy,
2340 SourceLocation());
2341 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2342 ConditionalOperator *CondExpr =
2343 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002344 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002345 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002346 return ReplacingStmt;
2347}
2348
Steve Naroffb29b4272008-04-14 22:03:09 +00002349Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002350 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002351 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002352 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002353
Chris Lattnere64b7772007-10-24 16:57:36 +00002354 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002355 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002356}
2357
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002358/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2359/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002360Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002361 if (!GetProtocolFunctionDecl)
2362 SynthGetProtocolFunctionDecl();
2363 // Create a call to objc_getProtocol("ProtocolName").
2364 llvm::SmallVector<Expr*, 8> ProtoExprs;
2365 QualType argType = Context->getPointerType(Context->CharTy);
2366 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2367 strlen(Exp->getProtocol()->getName()),
2368 false, argType, SourceLocation(),
2369 SourceLocation()));
2370 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2371 &ProtoExprs[0],
2372 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002373 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002374 delete Exp;
2375 return ProtoExp;
2376
2377}
2378
Steve Naroffbaf58c32008-05-31 14:15:04 +00002379bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2380 const char *endBuf) {
2381 while (startBuf < endBuf) {
2382 if (*startBuf == '#') {
2383 // Skip whitespace.
2384 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2385 ;
2386 if (!strncmp(startBuf, "if", strlen("if")) ||
2387 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2388 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2389 !strncmp(startBuf, "define", strlen("define")) ||
2390 !strncmp(startBuf, "undef", strlen("undef")) ||
2391 !strncmp(startBuf, "else", strlen("else")) ||
2392 !strncmp(startBuf, "elif", strlen("elif")) ||
2393 !strncmp(startBuf, "endif", strlen("endif")) ||
2394 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2395 !strncmp(startBuf, "include", strlen("include")) ||
2396 !strncmp(startBuf, "import", strlen("import")) ||
2397 !strncmp(startBuf, "include_next", strlen("include_next")))
2398 return true;
2399 }
2400 startBuf++;
2401 }
2402 return false;
2403}
2404
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002405/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002406/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002407void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002408 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002409 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2410 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002411 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002412 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002413 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002414 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002415 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002416 SourceLocation LocStart = CDecl->getLocStart();
2417 SourceLocation LocEnd = CDecl->getLocEnd();
2418
2419 const char *startBuf = SM->getCharacterData(LocStart);
2420 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002421
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002422 // If no ivars and no root or if its root, directly or indirectly,
2423 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002424 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2425 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002426 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002427 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002428 return;
2429 }
2430
2431 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002432 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002433 Result += "\nstruct ";
2434 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002435 if (LangOpts.Microsoft)
2436 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002437
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002438 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002439 const char *cursor = strchr(startBuf, '{');
2440 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002441 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002442 // If the buffer contains preprocessor directives, we do more fine-grained
2443 // rewrites. This is intended to fix code that looks like (which occurs in
2444 // NSURL.h, for example):
2445 //
2446 // #ifdef XYZ
2447 // @interface Foo : NSObject
2448 // #else
2449 // @interface FooBar : NSObject
2450 // #endif
2451 // {
2452 // int i;
2453 // }
2454 // @end
2455 //
2456 // This clause is segregated to avoid breaking the common case.
2457 if (BufferContainsPPDirectives(startBuf, cursor)) {
2458 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2459 CDecl->getClassLoc();
2460 const char *endHeader = SM->getCharacterData(L);
2461 endHeader += Lexer::MeasureTokenLength(L, *SM);
2462
Chris Lattner3db6cae2008-07-21 18:19:38 +00002463 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002464 // advance to the end of the referenced protocols.
2465 while (endHeader < cursor && *endHeader != '>') endHeader++;
2466 endHeader++;
2467 }
2468 // rewrite the original header
2469 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2470 } else {
2471 // rewrite the original header *without* disturbing the '{'
2472 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2473 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002474 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002475 Result = "\n struct ";
2476 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002477 Result += "_IMPL ";
2478 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002479 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002480
2481 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002482 SourceLocation OnePastCurly =
2483 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2484 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002485 }
2486 cursor++; // past '{'
2487
2488 // Now comment out any visibility specifiers.
2489 while (cursor < endBuf) {
2490 if (*cursor == '@') {
2491 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002492 // Skip whitespace.
2493 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2494 /*scan*/;
2495
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002496 // FIXME: presence of @public, etc. inside comment results in
2497 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002498 if (!strncmp(cursor, "public", strlen("public")) ||
2499 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002500 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002501 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002502 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002503 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002504 // FIXME: If there are cases where '<' is used in ivar declaration part
2505 // of user code, then scan the ivar list and use needToScanForQualifiers
2506 // for type checking.
2507 else if (*cursor == '<') {
2508 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002509 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002510 cursor = strchr(cursor, '>');
2511 cursor++;
2512 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002513 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002514 }
Steve Narofffea763e82007-11-14 19:25:57 +00002515 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002516 }
Steve Narofffea763e82007-11-14 19:25:57 +00002517 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002518 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002519 } else { // we don't have any instance variables - insert super struct.
2520 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2521 Result += " {\n struct ";
2522 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002523 Result += "_IMPL ";
2524 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002525 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002526 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002527 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002528 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002529 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002530 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002531}
2532
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002533// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002534/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002535void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002536 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002537 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002538 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002539 const char *ClassName,
2540 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002541 if (MethodBegin == MethodEnd) return;
2542
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002543 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002544 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002545 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002546 SEL _cmd;
2547 char *method_types;
2548 void *_imp;
2549 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002550 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002551 Result += "\nstruct _objc_method {\n";
2552 Result += "\tSEL _cmd;\n";
2553 Result += "\tchar *method_types;\n";
2554 Result += "\tvoid *_imp;\n";
2555 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002556
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002557 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002558 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002559
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002560 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002561
2562 /* struct {
2563 struct _objc_method_list *next_method;
2564 int method_count;
2565 struct _objc_method method_list[];
2566 }
2567 */
2568 Result += "\nstatic struct {\n";
2569 Result += "\tstruct _objc_method_list *next_method;\n";
2570 Result += "\tint method_count;\n";
2571 Result += "\tstruct _objc_method method_list[";
2572 Result += utostr(MethodEnd-MethodBegin);
2573 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002574 Result += prefix;
2575 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2576 Result += "_METHODS_";
2577 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002578 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002579 Result += IsInstanceMethod ? "inst" : "cls";
2580 Result += "_meth\")))= ";
2581 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002582
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002583 Result += "\t,{{(SEL)\"";
2584 Result += (*MethodBegin)->getSelector().getName().c_str();
2585 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002586 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002587 Result += "\", \"";
2588 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002589 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002590 Result += MethodInternalNames[*MethodBegin];
2591 Result += "}\n";
2592 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2593 Result += "\t ,{(SEL)\"";
2594 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002595 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002596 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002597 Result += "\", \"";
2598 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002599 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002600 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002601 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002602 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002603 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002604}
2605
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002606/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002607void RewriteObjC::
2608RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2609 const char *prefix,
2610 const char *ClassName,
2611 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002612 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002613 if (Protocols.empty()) return;
2614
2615 for (unsigned i = 0; i != Protocols.size(); i++) {
2616 ObjCProtocolDecl *PDecl = Protocols[i];
2617 // Output struct protocol_methods holder of method selector and type.
2618 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2619 /* struct protocol_methods {
2620 SEL _cmd;
2621 char *method_types;
2622 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002623 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002624 Result += "\nstruct protocol_methods {\n";
2625 Result += "\tSEL _cmd;\n";
2626 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002627 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002628
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002629 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002630 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002631 // Do not synthesize the protocol more than once.
2632 if (ObjCSynthesizedProtocols.count(PDecl))
2633 continue;
2634
2635 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2636 unsigned NumMethods = PDecl->getNumInstanceMethods();
2637 /* struct _objc_protocol_method_list {
2638 int protocol_method_count;
2639 struct protocol_methods protocols[];
2640 }
2641 */
2642 Result += "\nstatic struct {\n";
2643 Result += "\tint protocol_method_count;\n";
2644 Result += "\tstruct protocol_methods protocols[";
2645 Result += utostr(NumMethods);
2646 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2647 Result += PDecl->getName();
2648 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2649 "{\n\t" + utostr(NumMethods) + "\n";
2650
2651 // Output instance methods declared in this protocol.
2652 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2653 E = PDecl->instmeth_end(); I != E; ++I) {
2654 if (I == PDecl->instmeth_begin())
2655 Result += "\t ,{{(SEL)\"";
2656 else
2657 Result += "\t ,{(SEL)\"";
2658 Result += (*I)->getSelector().getName().c_str();
2659 std::string MethodTypeString;
2660 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2661 Result += "\", \"";
2662 Result += MethodTypeString;
2663 Result += "\"}\n";
2664 }
2665 Result += "\t }\n};\n";
2666 }
2667
2668 // Output class methods declared in this protocol.
2669 int NumMethods = PDecl->getNumClassMethods();
2670 if (NumMethods > 0) {
2671 /* struct _objc_protocol_method_list {
2672 int protocol_method_count;
2673 struct protocol_methods protocols[];
2674 }
2675 */
2676 Result += "\nstatic struct {\n";
2677 Result += "\tint protocol_method_count;\n";
2678 Result += "\tstruct protocol_methods protocols[";
2679 Result += utostr(NumMethods);
2680 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2681 Result += PDecl->getName();
2682 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2683 "{\n\t";
2684 Result += utostr(NumMethods);
2685 Result += "\n";
2686
2687 // Output instance methods declared in this protocol.
2688 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2689 E = PDecl->classmeth_end(); I != E; ++I) {
2690 if (I == PDecl->classmeth_begin())
2691 Result += "\t ,{{(SEL)\"";
2692 else
2693 Result += "\t ,{(SEL)\"";
2694 Result += (*I)->getSelector().getName().c_str();
2695 std::string MethodTypeString;
2696 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2697 Result += "\", \"";
2698 Result += MethodTypeString;
2699 Result += "\"}\n";
2700 }
2701 Result += "\t }\n};\n";
2702 }
2703
2704 // Output:
2705 /* struct _objc_protocol {
2706 // Objective-C 1.0 extensions
2707 struct _objc_protocol_extension *isa;
2708 char *protocol_name;
2709 struct _objc_protocol **protocol_list;
2710 struct _objc_protocol_method_list *instance_methods;
2711 struct _objc_protocol_method_list *class_methods;
2712 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002713 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002714 static bool objc_protocol = false;
2715 if (!objc_protocol) {
2716 Result += "\nstruct _objc_protocol {\n";
2717 Result += "\tstruct _objc_protocol_extension *isa;\n";
2718 Result += "\tchar *protocol_name;\n";
2719 Result += "\tstruct _objc_protocol **protocol_list;\n";
2720 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2721 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2722 Result += "};\n";
2723
2724 objc_protocol = true;
2725 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002726
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002727 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2728 Result += PDecl->getName();
2729 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2730 "{\n\t0, \"";
2731 Result += PDecl->getName();
2732 Result += "\", 0, ";
2733 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2734 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2735 Result += PDecl->getName();
2736 Result += ", ";
2737 }
2738 else
2739 Result += "0, ";
2740 if (PDecl->getNumClassMethods() > 0) {
2741 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2742 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002743 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002744 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002745 else
2746 Result += "0\n";
2747 Result += "};\n";
2748
2749 // Mark this protocol as having been generated.
2750 if (!ObjCSynthesizedProtocols.insert(PDecl))
2751 assert(false && "protocol already synthesized");
2752 }
2753 // Output the top lovel protocol meta-data for the class.
2754 /* struct _objc_protocol_list {
2755 struct _objc_protocol_list *next;
2756 int protocol_count;
2757 struct _objc_protocol *class_protocols[];
2758 }
2759 */
2760 Result += "\nstatic struct {\n";
2761 Result += "\tstruct _objc_protocol_list *next;\n";
2762 Result += "\tint protocol_count;\n";
2763 Result += "\tstruct _objc_protocol *class_protocols[";
2764 Result += utostr(Protocols.size());
2765 Result += "];\n} _OBJC_";
2766 Result += prefix;
2767 Result += "_PROTOCOLS_";
2768 Result += ClassName;
2769 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2770 "{\n\t0, ";
2771 Result += utostr(Protocols.size());
2772 Result += "\n";
2773
2774 Result += "\t,{&_OBJC_PROTOCOL_";
2775 Result += Protocols[0]->getName();
2776 Result += " \n";
2777
2778 for (unsigned i = 1; i != Protocols.size(); i++) {
2779 Result += "\t ,&_OBJC_PROTOCOL_";
2780 Result += Protocols[i]->getName();
2781 Result += "\n";
2782 }
2783 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002784}
2785
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002786/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002787/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002788void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002789 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002790 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002791 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002792 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002793 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2794 CDecl = CDecl->getNextClassCategory())
2795 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2796 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002797
Chris Lattnereb44eee2007-12-23 01:40:15 +00002798 std::string FullCategoryName = ClassDecl->getName();
2799 FullCategoryName += '_';
2800 FullCategoryName += IDecl->getName();
2801
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002802 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002803 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002804 true, "CATEGORY_", FullCategoryName.c_str(),
2805 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002806
2807 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002808 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002809 false, "CATEGORY_", FullCategoryName.c_str(),
2810 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002811
2812 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002813 // Null CDecl is case of a category implementation with no category interface
2814 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002815 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002816 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002817
2818 /* struct _objc_category {
2819 char *category_name;
2820 char *class_name;
2821 struct _objc_method_list *instance_methods;
2822 struct _objc_method_list *class_methods;
2823 struct _objc_protocol_list *protocols;
2824 // Objective-C 1.0 extensions
2825 uint32_t size; // sizeof (struct _objc_category)
2826 struct _objc_property_list *instance_properties; // category's own
2827 // @property decl.
2828 };
2829 */
2830
2831 static bool objc_category = false;
2832 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002833 Result += "\nstruct _objc_category {\n";
2834 Result += "\tchar *category_name;\n";
2835 Result += "\tchar *class_name;\n";
2836 Result += "\tstruct _objc_method_list *instance_methods;\n";
2837 Result += "\tstruct _objc_method_list *class_methods;\n";
2838 Result += "\tstruct _objc_protocol_list *protocols;\n";
2839 Result += "\tunsigned int size;\n";
2840 Result += "\tstruct _objc_property_list *instance_properties;\n";
2841 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002842 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002843 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002844 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2845 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002846 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002847 Result += IDecl->getName();
2848 Result += "\"\n\t, \"";
2849 Result += ClassDecl->getName();
2850 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002851
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002852 if (IDecl->getNumInstanceMethods() > 0) {
2853 Result += "\t, (struct _objc_method_list *)"
2854 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2855 Result += FullCategoryName;
2856 Result += "\n";
2857 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002858 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002859 Result += "\t, 0\n";
2860 if (IDecl->getNumClassMethods() > 0) {
2861 Result += "\t, (struct _objc_method_list *)"
2862 "&_OBJC_CATEGORY_CLASS_METHODS_";
2863 Result += FullCategoryName;
2864 Result += "\n";
2865 }
2866 else
2867 Result += "\t, 0\n";
2868
Chris Lattner780f3292008-07-21 21:32:27 +00002869 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002870 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2871 Result += FullCategoryName;
2872 Result += "\n";
2873 }
2874 else
2875 Result += "\t, 0\n";
2876 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002877}
2878
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002879/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2880/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002881void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002882 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002883 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002884 if (ivar->isBitField()) {
2885 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2886 // place all bitfields at offset 0.
2887 Result += "0";
2888 } else {
2889 Result += "__OFFSETOFIVAR__(struct ";
2890 Result += IDecl->getName();
2891 if (LangOpts.Microsoft)
2892 Result += "_IMPL";
2893 Result += ", ";
2894 Result += ivar->getName();
2895 Result += ")";
2896 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002897}
2898
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002899//===----------------------------------------------------------------------===//
2900// Meta Data Emission
2901//===----------------------------------------------------------------------===//
2902
Steve Naroffb29b4272008-04-14 22:03:09 +00002903void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002904 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002905 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002906
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002907 // Explictly declared @interface's are already synthesized.
2908 if (CDecl->ImplicitInterfaceDecl()) {
2909 // FIXME: Implementation of a class with no @interface (legacy) doese not
2910 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002911 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002912 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002913
Chris Lattnerbe6df082007-12-12 07:56:42 +00002914 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002915 unsigned NumIvars = !IDecl->ivar_empty()
2916 ? IDecl->ivar_size()
2917 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002918 if (NumIvars > 0) {
2919 static bool objc_ivar = false;
2920 if (!objc_ivar) {
2921 /* struct _objc_ivar {
2922 char *ivar_name;
2923 char *ivar_type;
2924 int ivar_offset;
2925 };
2926 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002927 Result += "\nstruct _objc_ivar {\n";
2928 Result += "\tchar *ivar_name;\n";
2929 Result += "\tchar *ivar_type;\n";
2930 Result += "\tint ivar_offset;\n";
2931 Result += "};\n";
2932
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002933 objc_ivar = true;
2934 }
2935
Steve Naroff946a6932008-03-11 00:12:29 +00002936 /* struct {
2937 int ivar_count;
2938 struct _objc_ivar ivar_list[nIvars];
2939 };
2940 */
2941 Result += "\nstatic struct {\n";
2942 Result += "\tint ivar_count;\n";
2943 Result += "\tstruct _objc_ivar ivar_list[";
2944 Result += utostr(NumIvars);
2945 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002946 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002947 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002948 "{\n\t";
2949 Result += utostr(NumIvars);
2950 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002951
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002952 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002953 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002954 IVI = IDecl->ivar_begin();
2955 IVE = IDecl->ivar_end();
2956 } else {
2957 IVI = CDecl->ivar_begin();
2958 IVE = CDecl->ivar_end();
2959 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002960 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002961 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002962 Result += "\", \"";
2963 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002964 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002965 Result += StrEncoding;
2966 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002967 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002968 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002969 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002970 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002971 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002972 Result += "\", \"";
2973 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002974 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002975 Result += StrEncoding;
2976 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002977 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002978 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002979 }
2980
2981 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002982 }
2983
2984 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002985 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002986 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002987
2988 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002989 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002990 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002991
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002992 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00002993 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002994 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002995
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002996
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002997 // Declaration of class/meta-class metadata
2998 /* struct _objc_class {
2999 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003000 const char *super_class_name;
3001 char *name;
3002 long version;
3003 long info;
3004 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003005 struct _objc_ivar_list *ivars;
3006 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003007 struct objc_cache *cache;
3008 struct objc_protocol_list *protocols;
3009 const char *ivar_layout;
3010 struct _objc_class_ext *ext;
3011 };
3012 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003013 static bool objc_class = false;
3014 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003015 Result += "\nstruct _objc_class {\n";
3016 Result += "\tstruct _objc_class *isa;\n";
3017 Result += "\tconst char *super_class_name;\n";
3018 Result += "\tchar *name;\n";
3019 Result += "\tlong version;\n";
3020 Result += "\tlong info;\n";
3021 Result += "\tlong instance_size;\n";
3022 Result += "\tstruct _objc_ivar_list *ivars;\n";
3023 Result += "\tstruct _objc_method_list *methods;\n";
3024 Result += "\tstruct objc_cache *cache;\n";
3025 Result += "\tstruct _objc_protocol_list *protocols;\n";
3026 Result += "\tconst char *ivar_layout;\n";
3027 Result += "\tstruct _objc_class_ext *ext;\n";
3028 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003029 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003030 }
3031
3032 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003033 ObjCInterfaceDecl *RootClass = 0;
3034 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003035 while (SuperClass) {
3036 RootClass = SuperClass;
3037 SuperClass = SuperClass->getSuperClass();
3038 }
3039 SuperClass = CDecl->getSuperClass();
3040
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003041 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3042 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003043 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003044 "{\n\t(struct _objc_class *)\"";
3045 Result += (RootClass ? RootClass->getName() : CDecl->getName());
3046 Result += "\"";
3047
3048 if (SuperClass) {
3049 Result += ", \"";
3050 Result += SuperClass->getName();
3051 Result += "\", \"";
3052 Result += CDecl->getName();
3053 Result += "\"";
3054 }
3055 else {
3056 Result += ", 0, \"";
3057 Result += CDecl->getName();
3058 Result += "\"";
3059 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003060 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003061 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003062 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003063 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003064 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00003065 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003066 Result += "\n";
3067 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003068 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003069 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003070 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003071 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003072 Result += CDecl->getName();
3073 Result += ",0,0\n";
3074 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003075 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003076 Result += "\t,0,0,0,0\n";
3077 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003078
3079 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003080 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3081 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003082 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003083 "{\n\t&_OBJC_METACLASS_";
3084 Result += CDecl->getName();
3085 if (SuperClass) {
3086 Result += ", \"";
3087 Result += SuperClass->getName();
3088 Result += "\", \"";
3089 Result += CDecl->getName();
3090 Result += "\"";
3091 }
3092 else {
3093 Result += ", 0, \"";
3094 Result += CDecl->getName();
3095 Result += "\"";
3096 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003097 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003098 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003099 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003100 Result += ",0";
3101 else {
3102 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003103 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003104 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003105 if (LangOpts.Microsoft)
3106 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003107 Result += ")";
3108 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003109 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003110 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003111 Result += CDecl->getName();
3112 Result += "\n\t";
3113 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003114 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003115 Result += ",0";
3116 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003117 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003118 Result += CDecl->getName();
3119 Result += ", 0\n\t";
3120 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003121 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003122 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003123 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003124 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003125 Result += CDecl->getName();
3126 Result += ", 0,0\n";
3127 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003128 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003129 Result += ",0,0,0\n";
3130 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003131}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003132
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003133/// RewriteImplementations - This routine rewrites all method implementations
3134/// and emits meta-data.
3135
Steve Naroffb29b4272008-04-14 22:03:09 +00003136void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003137 int ClsDefCount = ClassImplementation.size();
3138 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003139
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003140 if (ClsDefCount == 0 && CatDefCount == 0)
3141 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003142 // Rewrite implemented methods
3143 for (int i = 0; i < ClsDefCount; i++)
3144 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003145
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003146 for (int i = 0; i < CatDefCount; i++)
3147 RewriteImplementationDecl(CategoryImplementation[i]);
3148
Steve Naroff5df5b762008-05-07 21:23:49 +00003149 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003150 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003151 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003152 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003153 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003154
3155 // For each implemented category, write out all its meta data.
3156 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003157 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003158
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003159 // Write objc_symtab metadata
3160 /*
3161 struct _objc_symtab
3162 {
3163 long sel_ref_cnt;
3164 SEL *refs;
3165 short cls_def_cnt;
3166 short cat_def_cnt;
3167 void *defs[cls_def_cnt + cat_def_cnt];
3168 };
3169 */
3170
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003171 Result += "\nstruct _objc_symtab {\n";
3172 Result += "\tlong sel_ref_cnt;\n";
3173 Result += "\tSEL *refs;\n";
3174 Result += "\tshort cls_def_cnt;\n";
3175 Result += "\tshort cat_def_cnt;\n";
3176 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3177 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003178
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003179 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003180 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003181 Result += "\t0, 0, " + utostr(ClsDefCount)
3182 + ", " + utostr(CatDefCount) + "\n";
3183 for (int i = 0; i < ClsDefCount; i++) {
3184 Result += "\t,&_OBJC_CLASS_";
3185 Result += ClassImplementation[i]->getName();
3186 Result += "\n";
3187 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003188
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003189 for (int i = 0; i < CatDefCount; i++) {
3190 Result += "\t,&_OBJC_CATEGORY_";
3191 Result += CategoryImplementation[i]->getClassInterface()->getName();
3192 Result += "_";
3193 Result += CategoryImplementation[i]->getName();
3194 Result += "\n";
3195 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003196
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003197 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003198
3199 // Write objc_module metadata
3200
3201 /*
3202 struct _objc_module {
3203 long version;
3204 long size;
3205 const char *name;
3206 struct _objc_symtab *symtab;
3207 }
3208 */
3209
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003210 Result += "\nstruct _objc_module {\n";
3211 Result += "\tlong version;\n";
3212 Result += "\tlong size;\n";
3213 Result += "\tconst char *name;\n";
3214 Result += "\tstruct _objc_symtab *symtab;\n";
3215 Result += "};\n\n";
3216 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003217 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003218 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3219 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003220 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003221
3222 if (LangOpts.Microsoft) {
3223 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003224 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003225 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3226 Result += "&_OBJC_MODULES;\n";
3227 Result += "#pragma data_seg(pop)\n\n";
3228 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003229}
Chris Lattner311ff022007-10-16 22:36:42 +00003230
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003231
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003232
3233