blob: 56f3b3d0f44ee4e4cadad7184d94e783cabc9ebd [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"
Chris Lattner26de4652007-12-02 01:13:47 +000025#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000026#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000027#include "llvm/Support/Streams.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000028#include "llvm/System/Path.h"
Steve Naroff0d4e9632008-04-14 22:53:48 +000029#include <sstream>
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include <fstream>
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;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000060 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000061
Steve Naroffd82a9ab2008-03-15 00:55:56 +000062 unsigned NumObjCStringLiterals;
63
Steve Naroffebf2b562007-10-23 23:50:29 +000064 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000065 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000066 FunctionDecl *MsgSendStretFunctionDecl;
67 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000068 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000069 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000070 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000071 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000072 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000073 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000074 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000075
Steve Naroffbeaf2992007-11-03 11:27:19 +000076 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000077 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000078 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000079
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000080 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000081 int BcLabelCount;
82
Steve Naroff874e2322007-11-15 10:28:18 +000083 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000084 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000085 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000086 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000087
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000088 // Needed for header files being rewritten
89 bool IsHeader;
90
Steve Naroffa7b402d2008-03-28 22:26:09 +000091 std::string InFileName;
92 std::string OutFileName;
93
Steve Naroffba92b2e2008-03-27 22:29:16 +000094 std::string Preamble;
95
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000096 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000097 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +000098 virtual void Initialize(ASTContext &context);
99
100 virtual void InitializeTU(TranslationUnit &TU) {
101 TU.SetOwnsDecls(false);
102 Initialize(TU.getContext());
103 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000104
Chris Lattner8a12c272007-10-11 18:38:32 +0000105
Chris Lattnerf04da132007-10-24 17:06:59 +0000106 // Top Level Driver code.
107 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000108 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000109 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000110 Diagnostic &D, const LangOptions &LOpts);
Steve Naroffb29b4272008-04-14 22:03:09 +0000111 ~RewriteObjC();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000112
113 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000114 // If replacement succeeded or warning disabled return with no warning.
115 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000116 return;
117
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000118 SourceRange Range = Old->getSourceRange();
119 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
120 0, 0, &Range, 1);
121 }
122
Steve Naroffba92b2e2008-03-27 22:29:16 +0000123 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
124 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000125 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000126 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000127 SilenceRewriteMacroWarning)
128 return;
129
130 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
131 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000132
Chris Lattneraadaf782008-01-31 19:51:04 +0000133 void RemoveText(SourceLocation Loc, unsigned StrLen) {
134 // If removal succeeded or warning disabled return with no warning.
135 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
136 return;
137
138 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
139 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000140
Chris Lattneraadaf782008-01-31 19:51:04 +0000141 void ReplaceText(SourceLocation Start, unsigned OrigLength,
142 const char *NewStr, unsigned NewLength) {
143 // If removal succeeded or warning disabled return with no warning.
144 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
145 SilenceRewriteMacroWarning)
146 return;
147
148 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
149 }
150
Chris Lattnerf04da132007-10-24 17:06:59 +0000151 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000152 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000153 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000154 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000155 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
156 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000157 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000158 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
159 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
160 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
161 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
162 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000163 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000164 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000165 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000166 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000167 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000168 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000169 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000170 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000171
Chris Lattnerf04da132007-10-24 17:06:59 +0000172 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000173 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000174 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000175 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000176 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000177 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000178 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000179 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000180 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000181 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000182 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
183 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
184 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000185 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
186 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000187 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
188 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000189 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000190 Stmt *RewriteBreakStmt(BreakStmt *S);
191 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000192 void SynthCountByEnumWithState(std::string &buf);
193
Steve Naroff09b266e2007-10-30 23:14:51 +0000194 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000195 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000196 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000197 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000198 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000199 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000200 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000201 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000202 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000203 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000204
Chris Lattnerf04da132007-10-24 17:06:59 +0000205 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000206 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000207 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000208
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000209 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
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 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
213 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000214 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000215 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000216 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000217 const char *ClassName,
218 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000219
Chris Lattner780f3292008-07-21 21:32:27 +0000220 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
221 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000222 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000223 const char *ClassName,
224 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000225 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000226 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000227 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
228 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000229 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000230 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000231 };
232}
233
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000234static bool IsHeaderFile(const std::string &Filename) {
235 std::string::size_type DotPos = Filename.rfind('.');
236
237 if (DotPos == std::string::npos) {
238 // no file extension
239 return false;
240 }
241
242 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
243 // C header: .h
244 // C++ header: .hh or .H;
245 return Ext == "h" || Ext == "hh" || Ext == "H";
246}
247
Steve Naroffb29b4272008-04-14 22:03:09 +0000248RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000249 Diagnostic &D, const LangOptions &LOpts)
250 : Diags(D), LangOpts(LOpts) {
251 IsHeader = IsHeaderFile(inFile);
252 InFileName = inFile;
253 OutFileName = outFile;
254 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
255 "rewriting sub-expression within a macro (may not be correct)");
256}
257
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000258ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000259 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000260 Diagnostic &Diags,
261 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000262 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000263}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000264
Steve Naroffb29b4272008-04-14 22:03:09 +0000265void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000266 Context = &context;
267 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000268 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000269 MsgSendFunctionDecl = 0;
270 MsgSendSuperFunctionDecl = 0;
271 MsgSendStretFunctionDecl = 0;
272 MsgSendSuperStretFunctionDecl = 0;
273 MsgSendFpretFunctionDecl = 0;
274 GetClassFunctionDecl = 0;
275 GetMetaClassFunctionDecl = 0;
276 SelGetUidFunctionDecl = 0;
277 CFStringFunctionDecl = 0;
278 GetProtocolFunctionDecl = 0;
279 ConstantStringClassReference = 0;
280 NSStringRecord = 0;
281 CurMethodDecl = 0;
282 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000283 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000284 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000285 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000286 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000287
288 // Get the ID and start/end of the main file.
289 MainFileID = SM->getMainFileID();
290 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
291 MainFileStart = MainBuf->getBufferStart();
292 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000293
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000294 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000295
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000296 // declaring objc_selector outside the parameter list removes a silly
297 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000298 if (IsHeader)
299 Preamble = "#pragma once\n";
300 Preamble += "struct objc_selector; struct objc_class;\n";
301 Preamble += "#ifndef OBJC_SUPER\n";
302 Preamble += "struct objc_super { struct objc_object *object; ";
303 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000304 if (LangOpts.Microsoft) {
305 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000306 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
307 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000308 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000309 Preamble += "};\n";
310 Preamble += "#define OBJC_SUPER\n";
311 Preamble += "#endif\n";
312 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
313 Preamble += "typedef struct objc_object Protocol;\n";
314 Preamble += "#define _REWRITER_typedef_Protocol\n";
315 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000316 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000317 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
318 else
319 Preamble += "#define __OBJC_RW_EXTERN extern\n";
320 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000321 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000322 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000323 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000324 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000325 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000326 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000327 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000328 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000329 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000330 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000331 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000332 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000333 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000334 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
335 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
336 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
337 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
338 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000339 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000340 // @synchronized hooks.
341 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
342 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000343 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000344 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
345 Preamble += "struct __objcFastEnumerationState {\n\t";
346 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000347 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000348 Preamble += "unsigned long *mutationsPtr;\n\t";
349 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000350 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000351 Preamble += "#define __FASTENUMERATIONSTATE\n";
352 Preamble += "#endif\n";
353 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
354 Preamble += "struct __NSConstantStringImpl {\n";
355 Preamble += " int *isa;\n";
356 Preamble += " int flags;\n";
357 Preamble += " char *str;\n";
358 Preamble += " long length;\n";
359 Preamble += "};\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000360 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000361 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
362 Preamble += "#endif\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000363 if (LangOpts.Microsoft) {
364 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000365 Preamble += "#define __attribute__(X)\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000366 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000367}
368
369
Chris Lattnerf04da132007-10-24 17:06:59 +0000370//===----------------------------------------------------------------------===//
371// Top Level Driver Code
372//===----------------------------------------------------------------------===//
373
Steve Naroffb29b4272008-04-14 22:03:09 +0000374void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000375 // Two cases: either the decl could be in the main file, or it could be in a
376 // #included file. If the former, rewrite it now. If the later, check to see
377 // if we rewrote the #include/#import.
378 SourceLocation Loc = D->getLocation();
379 Loc = SM->getLogicalLoc(Loc);
380
381 // If this is for a builtin, ignore it.
382 if (Loc.isInvalid()) return;
383
Steve Naroffebf2b562007-10-23 23:50:29 +0000384 // Look for built-in declarations that we need to refer during the rewrite.
385 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000386 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000387 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000388 // declared in <Foundation/NSString.h>
389 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
390 ConstantStringClassReference = FVD;
391 return;
392 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000393 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000394 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000395 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000396 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000397 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000398 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000399 } else if (ObjCForwardProtocolDecl *FP =
400 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000401 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000402 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000403 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000404 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000405 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000406}
407
Chris Lattnerf04da132007-10-24 17:06:59 +0000408/// HandleDeclInMainFile - This is called for each top-level decl defined in the
409/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000410void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000411 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
412 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000413 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000414
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000415 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000416 if (Stmt *Body = MD->getBody()) {
417 //Body->dump();
418 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000419 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000420 CurMethodDecl = 0;
421 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000422 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000423 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000424 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000425 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000426 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000427 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000428 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000429 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000430 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000431 if (VD->getInit())
432 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
433 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000434 // Nothing yet.
435}
436
Steve Naroffb29b4272008-04-14 22:03:09 +0000437RewriteObjC::~RewriteObjC() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000438 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000439
440 // Rewrite tabs if we care.
441 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000442
Steve Naroffa7b402d2008-03-28 22:26:09 +0000443 if (Diags.hasErrorOccurred())
444 return;
445
446 // Create the output file.
447
448 std::ostream *OutFile;
449 if (OutFileName == "-") {
450 OutFile = llvm::cout.stream();
451 } else if (!OutFileName.empty()) {
452 OutFile = new std::ofstream(OutFileName.c_str(),
453 std::ios_base::binary|std::ios_base::out);
454 } else if (InFileName == "-") {
455 OutFile = llvm::cout.stream();
456 } else {
457 llvm::sys::Path Path(InFileName);
458 Path.eraseSuffix();
459 Path.appendSuffix("cpp");
460 OutFile = new std::ofstream(Path.toString().c_str(),
461 std::ios_base::binary|std::ios_base::out);
462 }
463
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000464 RewriteInclude();
465
Steve Naroffba92b2e2008-03-27 22:29:16 +0000466 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
467 Preamble.c_str(), Preamble.size(), false);
468
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000469 // Rewrite Objective-c meta data*
470 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000471 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000472
Chris Lattnerf04da132007-10-24 17:06:59 +0000473 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
474 // we are done.
475 if (const RewriteBuffer *RewriteBuf =
476 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000477 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000478 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000479 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000480 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000481 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000482 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000483 *OutFile << ResultStr;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000484}
485
Chris Lattnerf04da132007-10-24 17:06:59 +0000486//===----------------------------------------------------------------------===//
487// Syntactic (non-AST) Rewriting Code
488//===----------------------------------------------------------------------===//
489
Steve Naroffb29b4272008-04-14 22:03:09 +0000490void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000491 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
492 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
493 const char *MainBufStart = MainBuf.first;
494 const char *MainBufEnd = MainBuf.second;
495 size_t ImportLen = strlen("import");
496 size_t IncludeLen = strlen("include");
497
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000498 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000499 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
500 if (*BufPtr == '#') {
501 if (++BufPtr == MainBufEnd)
502 return;
503 while (*BufPtr == ' ' || *BufPtr == '\t')
504 if (++BufPtr == MainBufEnd)
505 return;
506 if (!strncmp(BufPtr, "import", ImportLen)) {
507 // replace import with include
508 SourceLocation ImportLoc =
509 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000510 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000511 BufPtr += ImportLen;
512 }
513 }
514 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000515}
516
Steve Naroffb29b4272008-04-14 22:03:09 +0000517void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000518 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
519 const char *MainBufStart = MainBuf.first;
520 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000521
Chris Lattnerf04da132007-10-24 17:06:59 +0000522 // Loop over the whole file, looking for tabs.
523 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
524 if (*BufPtr != '\t')
525 continue;
526
527 // Okay, we found a tab. This tab will turn into at least one character,
528 // but it depends on which 'virtual column' it is in. Compute that now.
529 unsigned VCol = 0;
530 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
531 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
532 ++VCol;
533
534 // Okay, now that we know the virtual column, we know how many spaces to
535 // insert. We assume 8-character tab-stops.
536 unsigned Spaces = 8-(VCol & 7);
537
538 // Get the location of the tab.
539 SourceLocation TabLoc =
540 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
541
542 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000543 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000544 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000545}
546
547
Steve Naroffb29b4272008-04-14 22:03:09 +0000548void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000549 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000550 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000551
552 // Get the start location and compute the semi location.
553 SourceLocation startLoc = ClassDecl->getLocation();
554 const char *startBuf = SM->getCharacterData(startLoc);
555 const char *semiPtr = strchr(startBuf, ';');
556
557 // Translate to typedef's that forward reference structs with the same name
558 // as the class. As a convenience, we include the original declaration
559 // as a comment.
560 std::string typedefString;
561 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000562 typedefString.append(startBuf, semiPtr-startBuf+1);
563 typedefString += "\n";
564 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000565 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000566 typedefString += "#ifndef _REWRITER_typedef_";
567 typedefString += ForwardDecl->getName();
568 typedefString += "\n";
569 typedefString += "#define _REWRITER_typedef_";
570 typedefString += ForwardDecl->getName();
571 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000572 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000573 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000574 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000575 }
576
577 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000578 ReplaceText(startLoc, semiPtr-startBuf+1,
579 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000580}
581
Steve Naroffb29b4272008-04-14 22:03:09 +0000582void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000583 SourceLocation LocStart = Method->getLocStart();
584 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000585
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000586 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000587 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000588 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000589 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000590 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000591 }
592}
593
Steve Naroffb29b4272008-04-14 22:03:09 +0000594void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000595{
Chris Lattner55d13b42008-03-16 21:23:50 +0000596 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000597 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000598 SourceLocation Loc = Property->getLocation();
599
Chris Lattneraadaf782008-01-31 19:51:04 +0000600 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000601
602 // FIXME: handle properties that are declared across multiple lines.
603 }
604}
605
Steve Naroffb29b4272008-04-14 22:03:09 +0000606void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000607 SourceLocation LocStart = CatDecl->getLocStart();
608
609 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000610 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000611
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000612 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000613 E = CatDecl->instmeth_end(); I != E; ++I)
614 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000615 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000616 E = CatDecl->classmeth_end(); I != E; ++I)
617 RewriteMethodDeclaration(*I);
618
Steve Naroff423cb562007-10-30 13:30:57 +0000619 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000620 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000621}
622
Steve Naroffb29b4272008-04-14 22:03:09 +0000623void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000624 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000625
Steve Naroff752d6ef2007-10-30 16:42:30 +0000626 SourceLocation LocStart = PDecl->getLocStart();
627
628 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000629 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000630
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000631 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000632 E = PDecl->instmeth_end(); I != E; ++I)
633 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000634 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000635 E = PDecl->classmeth_end(); I != E; ++I)
636 RewriteMethodDeclaration(*I);
637
Steve Naroff752d6ef2007-10-30 16:42:30 +0000638 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000639 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000640 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000641
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000642 // Must comment out @optional/@required
643 const char *startBuf = SM->getCharacterData(LocStart);
644 const char *endBuf = SM->getCharacterData(LocEnd);
645 for (const char *p = startBuf; p < endBuf; p++) {
646 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
647 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000648 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000649 ReplaceText(OptionalLoc, strlen("@optional"),
650 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000651
652 }
653 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
654 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000655 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000656 ReplaceText(OptionalLoc, strlen("@required"),
657 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000658
659 }
660 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000661}
662
Steve Naroffb29b4272008-04-14 22:03:09 +0000663void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000664 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000665 if (LocStart.isInvalid())
666 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000667 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000668 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000669}
670
Steve Naroffb29b4272008-04-14 22:03:09 +0000671void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000672 std::string &ResultStr) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000673 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000674 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000675 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000676 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000677 else if (OMD->getResultType()->isFunctionPointerType()) {
678 // needs special handling, since pointer-to-functions have special
679 // syntax (where a decaration models use).
680 QualType retType = OMD->getResultType();
681 if (const PointerType* PT = retType->getAsPointerType()) {
682 QualType PointeeTy = PT->getPointeeType();
683 if ((FPRetType = PointeeTy->getAsFunctionType())) {
684 ResultStr += FPRetType->getResultType().getAsString();
685 ResultStr += "(*";
686 }
687 }
688 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000689 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000690 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000691
692 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000693 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000694
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000695 if (OMD->isInstance())
696 NameStr += "_I_";
697 else
698 NameStr += "_C_";
699
700 NameStr += OMD->getClassInterface()->getName();
701 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000702
703 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000704 if (ObjCCategoryImplDecl *CID =
705 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000706 NameStr += CID->getName();
707 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000708 }
Steve Naroff563b8282008-04-04 22:23:44 +0000709 // Append selector names, replacing ':' with '_'
710 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000711 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000712 else {
713 std::string selString = OMD->getSelector().getName();
714 int len = selString.size();
715 for (int i = 0; i < len; i++)
716 if (selString[i] == ':')
717 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000718 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000719 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000720 // Remember this name for metadata emission
721 MethodInternalNames[OMD] = NameStr;
722 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000723
724 // Rewrite arguments
725 ResultStr += "(";
726
727 // invisible arguments
728 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000729 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000730 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000731 if (!LangOpts.Microsoft) {
732 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
733 ResultStr += "struct ";
734 }
735 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000736 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000737 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000738 }
739 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000740 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000741
742 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000743 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000744 ResultStr += " _cmd";
745
746 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000747 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000748 ParmVarDecl *PDecl = OMD->getParamDecl(i);
749 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000750 if (PDecl->getType()->isObjCQualifiedIdType()) {
751 ResultStr += "id ";
752 ResultStr += PDecl->getName();
753 } else {
754 std::string Name = PDecl->getName();
755 PDecl->getType().getAsStringInternal(Name);
756 ResultStr += Name;
757 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000758 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000759 if (OMD->isVariadic())
760 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000761 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000762
Steve Naroff76e429d2008-07-16 14:40:40 +0000763 if (FPRetType) {
764 ResultStr += ")"; // close the precedence "scope" for "*".
765
766 // Now, emit the argument types (if any).
767 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
768 ResultStr += "(";
769 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
770 if (i) ResultStr += ", ";
771 std::string ParamStr = FT->getArgType(i).getAsString();
772 ResultStr += ParamStr;
773 }
774 if (FT->isVariadic()) {
775 if (FT->getNumArgs()) ResultStr += ", ";
776 ResultStr += "...";
777 }
778 ResultStr += ")";
779 } else {
780 ResultStr += "()";
781 }
782 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000783}
Steve Naroffb29b4272008-04-14 22:03:09 +0000784void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000785 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
786 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000787
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000788 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000789 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000790 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000791 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000792
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000793 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000794 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
795 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000796 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000797 ObjCMethodDecl *OMD = *I;
798 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000799 SourceLocation LocStart = OMD->getLocStart();
800 SourceLocation LocEnd = OMD->getBody()->getLocStart();
801
802 const char *startBuf = SM->getCharacterData(LocStart);
803 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000804 ReplaceText(LocStart, endBuf-startBuf,
805 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000806 }
807
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000808 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000809 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
810 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000811 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000812 ObjCMethodDecl *OMD = *I;
813 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000814 SourceLocation LocStart = OMD->getLocStart();
815 SourceLocation LocEnd = OMD->getBody()->getLocStart();
816
817 const char *startBuf = SM->getCharacterData(LocStart);
818 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000819 ReplaceText(LocStart, endBuf-startBuf,
820 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000821 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000822 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000823 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000824 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000825 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000826}
827
Steve Naroffb29b4272008-04-14 22:03:09 +0000828void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000829 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000830 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000831 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000832 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000833 ResultStr += ClassDecl->getName();
834 ResultStr += "\n";
835 ResultStr += "#define _REWRITER_typedef_";
836 ResultStr += ClassDecl->getName();
837 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000838 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000839 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000840 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000841 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000842 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000843 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000844 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000845
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000846 RewriteProperties(ClassDecl->getNumPropertyDecl(),
847 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000848 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000849 E = ClassDecl->instmeth_end(); I != E; ++I)
850 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000851 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000852 E = ClassDecl->classmeth_end(); I != E; ++I)
853 RewriteMethodDeclaration(*I);
854
Steve Naroff2feac5e2007-10-30 03:43:13 +0000855 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000856 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000857}
858
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000859Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
860 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000861 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000862 if (CurMethodDecl) {
863 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000864 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
865 // lookup which class implements the instance variable.
866 ObjCInterfaceDecl *clsDeclared = 0;
867 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
868 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
869
870 // Synthesize an explicit cast to gain access to the ivar.
871 std::string RecName = clsDeclared->getIdentifier()->getName();
872 RecName += "_IMPL";
873 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000874 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Steve Narofff0757612008-05-08 17:52:16 +0000875 SourceLocation(), II, 0);
876 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
877 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
878 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
879 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000880 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
881 IV->getBase()->getLocEnd(),
882 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000883 if (IV->isFreeIvar() &&
884 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000885 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
886 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000887 ReplaceStmt(IV, ME);
888 delete IV;
889 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000890 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000891
892 ReplaceStmt(IV->getBase(), PE);
893 // Cannot delete IV->getBase(), since PE points to it.
894 // Replace the old base with the cast. This is important when doing
895 // embedded rewrites. For example, [newInv->_container addObject:0].
896 IV->setBase(PE);
897 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000898 }
Steve Naroff84472a82008-04-18 21:55:08 +0000899 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000900 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
901
902 // Explicit ivar refs need to have a cast inserted.
903 // FIXME: consider sharing some of this code with the code above.
904 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000905 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000906 // lookup which class implements the instance variable.
907 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000908 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000909 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
910
911 // Synthesize an explicit cast to gain access to the ivar.
912 std::string RecName = clsDeclared->getIdentifier()->getName();
913 RecName += "_IMPL";
914 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000915 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Steve Naroff9f525972008-05-06 23:20:07 +0000916 SourceLocation(), II, 0);
917 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
918 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
919 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
920 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +0000921 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
922 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +0000923 ReplaceStmt(IV->getBase(), PE);
924 // Cannot delete IV->getBase(), since PE points to it.
925 // Replace the old base with the cast. This is important when doing
926 // embedded rewrites. For example, [newInv->_container addObject:0].
927 IV->setBase(PE);
928 return IV;
929 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000930 }
Steve Naroff84472a82008-04-18 21:55:08 +0000931 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000932}
933
Chris Lattnerf04da132007-10-24 17:06:59 +0000934//===----------------------------------------------------------------------===//
935// Function Body / Expression rewriting
936//===----------------------------------------------------------------------===//
937
Steve Naroffb29b4272008-04-14 22:03:09 +0000938Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000939 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
940 isa<DoStmt>(S) || isa<ForStmt>(S))
941 Stmts.push_back(S);
942 else if (isa<ObjCForCollectionStmt>(S)) {
943 Stmts.push_back(S);
944 ObjCBcLabelNo.push_back(++BcLabelCount);
945 }
946
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000947 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner338d1e22008-01-31 05:10:40 +0000948
949 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000950 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
951 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000952 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000953 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000954 if (newStmt)
955 *CI = newStmt;
956 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000957
958 // Handle specific things.
959 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
960 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000961
962 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000963 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroffb42f8412007-11-05 14:50:49 +0000964
965 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
966 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000967
Steve Naroffbeaf2992007-11-03 11:27:19 +0000968 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
969 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000970
Steve Naroff934f2762007-10-24 22:48:43 +0000971 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
972 // Before we rewrite it, put the original message expression in a comment.
973 SourceLocation startLoc = MessExpr->getLocStart();
974 SourceLocation endLoc = MessExpr->getLocEnd();
975
976 const char *startBuf = SM->getCharacterData(startLoc);
977 const char *endBuf = SM->getCharacterData(endLoc);
978
979 std::string messString;
980 messString += "// ";
981 messString.append(startBuf, endBuf-startBuf+1);
982 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000983
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000984 // FIXME: Missing definition of
985 // InsertText(clang::SourceLocation, char const*, unsigned int).
986 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000987 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000988 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000989 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000990 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000991
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000992 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
993 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000994
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000995 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
996 return RewriteObjCSynchronizedStmt(StmtTry);
997
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000998 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
999 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001000
1001 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
1002 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001003
1004 if (ObjCForCollectionStmt *StmtForCollection =
1005 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001006 return RewriteObjCForCollectionStmt(StmtForCollection,
1007 OrigStmtRange.getEnd());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001008 if (BreakStmt *StmtBreakStmt =
1009 dyn_cast<BreakStmt>(S))
1010 return RewriteBreakStmt(StmtBreakStmt);
1011 if (ContinueStmt *StmtContinueStmt =
1012 dyn_cast<ContinueStmt>(S))
1013 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001014
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001015 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1016 isa<DoStmt>(S) || isa<ForStmt>(S)) {
1017 assert(!Stmts.empty() && "Statement stack is empty");
1018 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
1019 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
1020 && "Statement stack mismatch");
1021 Stmts.pop_back();
1022 }
Steve Naroff874e2322007-11-15 10:28:18 +00001023#if 0
1024 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
1025 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
1026 // Get the new text.
1027 std::ostringstream Buf;
1028 Replacement->printPretty(Buf);
1029 const std::string &Str = Buf.str();
1030
1031 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001032 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +00001033 delete S;
1034 return Replacement;
1035 }
1036#endif
Chris Lattnere64b7772007-10-24 16:57:36 +00001037 // Return this stmt unmodified.
1038 return S;
Chris Lattner311ff022007-10-16 22:36:42 +00001039}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001040
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001041/// SynthCountByEnumWithState - To print:
1042/// ((unsigned int (*)
1043/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1044/// (void *)objc_msgSend)((id)l_collection,
1045/// sel_registerName(
1046/// "countByEnumeratingWithState:objects:count:"),
1047/// &enumState,
1048/// (id *)items, (unsigned int)16)
1049///
Steve Naroffb29b4272008-04-14 22:03:09 +00001050void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001051 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1052 "id *, unsigned int))(void *)objc_msgSend)";
1053 buf += "\n\t\t";
1054 buf += "((id)l_collection,\n\t\t";
1055 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1056 buf += "\n\t\t";
1057 buf += "&enumState, "
1058 "(id *)items, (unsigned int)16)";
1059}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001060
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001061/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1062/// statement to exit to its outer synthesized loop.
1063///
Steve Naroffb29b4272008-04-14 22:03:09 +00001064Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001065 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1066 return S;
1067 // replace break with goto __break_label
1068 std::string buf;
1069
1070 SourceLocation startLoc = S->getLocStart();
1071 buf = "goto __break_label_";
1072 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001073 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001074
1075 return 0;
1076}
1077
1078/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1079/// statement to continue with its inner synthesized loop.
1080///
Steve Naroffb29b4272008-04-14 22:03:09 +00001081Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001082 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1083 return S;
1084 // replace continue with goto __continue_label
1085 std::string buf;
1086
1087 SourceLocation startLoc = S->getLocStart();
1088 buf = "goto __continue_label_";
1089 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001090 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001091
1092 return 0;
1093}
1094
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001095/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001096/// It rewrites:
1097/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001098
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001099/// Into:
1100/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001101/// type elem;
1102/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001103/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001104/// id l_collection = (id)collection;
1105/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1106/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001107/// if (limit) {
1108/// unsigned long startMutations = *enumState.mutationsPtr;
1109/// do {
1110/// unsigned long counter = 0;
1111/// do {
1112/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001113/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001114/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001115/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001116/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001117/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001118/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1119/// objects:items count:16]);
1120/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001121/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001122/// }
1123/// else
1124/// elem = nil;
1125/// }
1126///
Steve Naroffb29b4272008-04-14 22:03:09 +00001127Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001128 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001129 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1130 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1131 "ObjCForCollectionStmt Statement stack mismatch");
1132 assert(!ObjCBcLabelNo.empty() &&
1133 "ObjCForCollectionStmt - Label No stack empty");
1134
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001135 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001136 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001137 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001138 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001139 std::string buf;
1140 buf = "\n{\n\t";
1141 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1142 // type elem;
1143 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001144 elementTypeAsString = ElementType.getAsString();
1145 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001146 buf += " ";
1147 elementName = DS->getDecl()->getName();
1148 buf += elementName;
1149 buf += ";\n\t";
1150 }
Chris Lattner06767512008-04-08 05:52:18 +00001151 else {
1152 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001153 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001154 elementTypeAsString = DR->getDecl()->getType().getAsString();
1155 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001156
1157 // struct __objcFastEnumerationState enumState = { 0 };
1158 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1159 // id items[16];
1160 buf += "id items[16];\n\t";
1161 // id l_collection = (id)
1162 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001163 // Find start location of 'collection' the hard way!
1164 const char *startCollectionBuf = startBuf;
1165 startCollectionBuf += 3; // skip 'for'
1166 startCollectionBuf = strchr(startCollectionBuf, '(');
1167 startCollectionBuf++; // skip '('
1168 // find 'in' and skip it.
1169 while (*startCollectionBuf != ' ' ||
1170 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1171 (*(startCollectionBuf+3) != ' ' &&
1172 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1173 startCollectionBuf++;
1174 startCollectionBuf += 3;
1175
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001176 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001177 ReplaceText(startLoc, startCollectionBuf - startBuf,
1178 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001179 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001180 SourceLocation rightParenLoc = S->getRParenLoc();
1181 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1182 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001183 buf = ";\n\t";
1184
1185 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1186 // objects:items count:16];
1187 // which is synthesized into:
1188 // unsigned int limit =
1189 // ((unsigned int (*)
1190 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1191 // (void *)objc_msgSend)((id)l_collection,
1192 // sel_registerName(
1193 // "countByEnumeratingWithState:objects:count:"),
1194 // (struct __objcFastEnumerationState *)&state,
1195 // (id *)items, (unsigned int)16);
1196 buf += "unsigned long limit =\n\t\t";
1197 SynthCountByEnumWithState(buf);
1198 buf += ";\n\t";
1199 /// if (limit) {
1200 /// unsigned long startMutations = *enumState.mutationsPtr;
1201 /// do {
1202 /// unsigned long counter = 0;
1203 /// do {
1204 /// if (startMutations != *enumState.mutationsPtr)
1205 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001206 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001207 buf += "if (limit) {\n\t";
1208 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1209 buf += "do {\n\t\t";
1210 buf += "unsigned long counter = 0;\n\t\t";
1211 buf += "do {\n\t\t\t";
1212 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1213 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1214 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001215 buf += " = (";
1216 buf += elementTypeAsString;
1217 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001218 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001219 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001220
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001221 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001222 /// } while (counter < limit);
1223 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1224 /// objects:items count:16]);
1225 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001226 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001227 /// }
1228 /// else
1229 /// elem = nil;
1230 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001231 ///
1232 buf = ";\n\t";
1233 buf += "__continue_label_";
1234 buf += utostr(ObjCBcLabelNo.back());
1235 buf += ": ;";
1236 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001237 buf += "} while (counter < limit);\n\t";
1238 buf += "} while (limit = ";
1239 SynthCountByEnumWithState(buf);
1240 buf += ");\n\t";
1241 buf += elementName;
1242 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001243 buf += "__break_label_";
1244 buf += utostr(ObjCBcLabelNo.back());
1245 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001246 buf += "}\n\t";
1247 buf += "else\n\t\t";
1248 buf += elementName;
1249 buf += " = nil;\n";
1250 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001251
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001252 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001253 if (isa<CompoundStmt>(S->getBody())) {
1254 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1255 InsertText(endBodyLoc, buf.c_str(), buf.size());
1256 } else {
1257 /* Need to treat single statements specially. For example:
1258 *
1259 * for (A *a in b) if (stuff()) break;
1260 * for (A *a in b) xxxyy;
1261 *
1262 * The following code simply scans ahead to the semi to find the actual end.
1263 */
1264 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1265 const char *semiBuf = strchr(stmtBuf, ';');
1266 assert(semiBuf && "Can't find ';'");
1267 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1268 InsertText(endBodyLoc, buf.c_str(), buf.size());
1269 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001270 Stmts.pop_back();
1271 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001272 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001273}
1274
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001275/// RewriteObjCSynchronizedStmt -
1276/// This routine rewrites @synchronized(expr) stmt;
1277/// into:
1278/// objc_sync_enter(expr);
1279/// @try stmt @finally { objc_sync_exit(expr); }
1280///
Steve Naroffb29b4272008-04-14 22:03:09 +00001281Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001282 // Get the start location and compute the semi location.
1283 SourceLocation startLoc = S->getLocStart();
1284 const char *startBuf = SM->getCharacterData(startLoc);
1285
1286 assert((*startBuf == '@') && "bogus @synchronized location");
1287
1288 std::string buf;
1289 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001290 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001291 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1292 const char *endBuf = SM->getCharacterData(endLoc);
1293 endBuf++;
1294 const char *rparenBuf = strchr(endBuf, ')');
1295 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1296 buf = ");\n";
1297 // declare a new scope with two variables, _stack and _rethrow.
1298 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1299 buf += "int buf[18/*32-bit i386*/];\n";
1300 buf += "char *pointers[4];} _stack;\n";
1301 buf += "id volatile _rethrow = 0;\n";
1302 buf += "objc_exception_try_enter(&_stack);\n";
1303 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001304 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001305 startLoc = S->getSynchBody()->getLocEnd();
1306 startBuf = SM->getCharacterData(startLoc);
1307
1308 assert((*startBuf == '}') && "bogus @try block");
1309 SourceLocation lastCurlyLoc = startLoc;
1310 buf = "}\nelse {\n";
1311 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1312 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001313 buf += " objc_sync_exit(";
1314 std::ostringstream syncExprBuf;
1315 S->getSynchExpr()->printPretty(syncExprBuf);
1316 buf += syncExprBuf.str();
1317 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001318 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1319 buf += "}\n";
1320 buf += "}";
1321
Chris Lattneraadaf782008-01-31 19:51:04 +00001322 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001323 return 0;
1324}
1325
Steve Naroffb29b4272008-04-14 22:03:09 +00001326Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001327 // Get the start location and compute the semi location.
1328 SourceLocation startLoc = S->getLocStart();
1329 const char *startBuf = SM->getCharacterData(startLoc);
1330
1331 assert((*startBuf == '@') && "bogus @try location");
1332
1333 std::string buf;
1334 // declare a new scope with two variables, _stack and _rethrow.
1335 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1336 buf += "int buf[18/*32-bit i386*/];\n";
1337 buf += "char *pointers[4];} _stack;\n";
1338 buf += "id volatile _rethrow = 0;\n";
1339 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001340 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001341
Chris Lattneraadaf782008-01-31 19:51:04 +00001342 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001343
1344 startLoc = S->getTryBody()->getLocEnd();
1345 startBuf = SM->getCharacterData(startLoc);
1346
1347 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001348
Steve Naroff75730982007-11-07 04:08:17 +00001349 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001350 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1351 if (catchList) {
1352 startLoc = startLoc.getFileLocWithOffset(1);
1353 buf = " /* @catch begin */ else {\n";
1354 buf += " id _caught = objc_exception_extract(&_stack);\n";
1355 buf += " objc_exception_try_enter (&_stack);\n";
1356 buf += " if (_setjmp(_stack.buf))\n";
1357 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1358 buf += " else { /* @catch continue */";
1359
1360 InsertText(startLoc, buf.c_str(), buf.size());
1361 }
Steve Naroff75730982007-11-07 04:08:17 +00001362 bool sawIdTypedCatch = false;
1363 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001364 while (catchList) {
1365 Stmt *catchStmt = catchList->getCatchParamStmt();
1366
1367 if (catchList == S->getCatchStmts())
1368 buf = "if ("; // we are generating code for the first catch clause
1369 else
1370 buf = "else if (";
1371 startLoc = catchList->getLocStart();
1372 startBuf = SM->getCharacterData(startLoc);
1373
1374 assert((*startBuf == '@') && "bogus @catch location");
1375
1376 const char *lParenLoc = strchr(startBuf, '(');
1377
Steve Naroffbe4b3332008-02-01 22:08:12 +00001378 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001379 // Now rewrite the body...
1380 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001381 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1382 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001383 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1384 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001385 assert((*bodyBuf == '{') && "bogus @catch body location");
1386
1387 buf += "1) { id _tmp = _caught;";
1388 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1389 buf.c_str(), buf.size());
1390 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001391 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001392 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001393 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001394 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001395 sawIdTypedCatch = true;
1396 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001397 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001398
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001399 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001400 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001401 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001402 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001403 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001404 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001405 }
1406 }
1407 // Now rewrite the body...
1408 lastCatchBody = catchList->getCatchBody();
1409 SourceLocation rParenLoc = catchList->getRParenLoc();
1410 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1411 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1412 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1413 assert((*rParenBuf == ')') && "bogus @catch paren location");
1414 assert((*bodyBuf == '{') && "bogus @catch body location");
1415
1416 buf = " = _caught;";
1417 // Here we replace ") {" with "= _caught;" (which initializes and
1418 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001419 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001420 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001421 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001422 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001423 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001424 catchList = catchList->getNextCatchStmt();
1425 }
1426 // Complete the catch list...
1427 if (lastCatchBody) {
1428 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001429 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1430 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001431 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1432 buf = " } } /* @catch end */\n";
1433
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001434 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001435
1436 // Set lastCurlyLoc
1437 lastCurlyLoc = lastCatchBody->getLocEnd();
1438 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001439 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001440 startLoc = finalStmt->getLocStart();
1441 startBuf = SM->getCharacterData(startLoc);
1442 assert((*startBuf == '@') && "bogus @finally start");
1443
1444 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001445 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001446
1447 Stmt *body = finalStmt->getFinallyBody();
1448 SourceLocation startLoc = body->getLocStart();
1449 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001450 assert(*SM->getCharacterData(startLoc) == '{' &&
1451 "bogus @finally body location");
1452 assert(*SM->getCharacterData(endLoc) == '}' &&
1453 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001454
1455 startLoc = startLoc.getFileLocWithOffset(1);
1456 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001457 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001458 endLoc = endLoc.getFileLocWithOffset(-1);
1459 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001460 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001461
1462 // Set lastCurlyLoc
1463 lastCurlyLoc = body->getLocEnd();
1464 }
1465 // Now emit the final closing curly brace...
1466 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1467 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001468 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001469 return 0;
1470}
1471
Steve Naroffb29b4272008-04-14 22:03:09 +00001472Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001473 return 0;
1474}
1475
Steve Naroffb29b4272008-04-14 22:03:09 +00001476Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001477 return 0;
1478}
1479
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001480// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001481// the throw expression is typically a message expression that's already
1482// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001483Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001484 // Get the start location and compute the semi location.
1485 SourceLocation startLoc = S->getLocStart();
1486 const char *startBuf = SM->getCharacterData(startLoc);
1487
1488 assert((*startBuf == '@') && "bogus @throw location");
1489
1490 std::string buf;
1491 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001492 if (S->getThrowExpr())
1493 buf = "objc_exception_throw(";
1494 else // add an implicit argument
1495 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001496
1497 // handle "@ throw" correctly.
1498 const char *wBuf = strchr(startBuf, 'w');
1499 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1500 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1501
Steve Naroff2bd03922007-11-07 15:32:26 +00001502 const char *semiBuf = strchr(startBuf, ';');
1503 assert((*semiBuf == ';') && "@throw: can't find ';'");
1504 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1505 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001506 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001507 return 0;
1508}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001509
Steve Naroffb29b4272008-04-14 22:03:09 +00001510Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001511 // Create a new string expression.
1512 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001513 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001514 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1515 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001516 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1517 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001518 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001519 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001520
Chris Lattner07506182007-11-30 22:53:43 +00001521 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001522 delete Exp;
1523 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001524}
1525
Steve Naroffb29b4272008-04-14 22:03:09 +00001526Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001527 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1528 // Create a call to sel_registerName("selName").
1529 llvm::SmallVector<Expr*, 8> SelExprs;
1530 QualType argType = Context->getPointerType(Context->CharTy);
1531 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1532 Exp->getSelector().getName().size(),
1533 false, argType, SourceLocation(),
1534 SourceLocation()));
1535 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1536 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001537 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001538 delete Exp;
1539 return SelExp;
1540}
1541
Steve Naroffb29b4272008-04-14 22:03:09 +00001542CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001543 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001544 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001545 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001546
1547 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001548 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001549
1550 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001551 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001552 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1553
1554 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001555
Steve Naroff934f2762007-10-24 22:48:43 +00001556 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1557}
1558
Steve Naroffd5255f52007-11-01 13:24:47 +00001559static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1560 const char *&startRef, const char *&endRef) {
1561 while (startBuf < endBuf) {
1562 if (*startBuf == '<')
1563 startRef = startBuf; // mark the start.
1564 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001565 if (startRef && *startRef == '<') {
1566 endRef = startBuf; // mark the end.
1567 return true;
1568 }
1569 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001570 }
1571 startBuf++;
1572 }
1573 return false;
1574}
1575
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001576static void scanToNextArgument(const char *&argRef) {
1577 int angle = 0;
1578 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1579 if (*argRef == '<')
1580 angle++;
1581 else if (*argRef == '>')
1582 angle--;
1583 argRef++;
1584 }
1585 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1586}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001587
Steve Naroffb29b4272008-04-14 22:03:09 +00001588bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001589
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001590 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001591 return true;
1592
Steve Naroffd5255f52007-11-01 13:24:47 +00001593 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001594 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001595 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001596 return true; // we have "Class <Protocol> *".
1597 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001598 return false;
1599}
1600
Steve Naroffb29b4272008-04-14 22:03:09 +00001601void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001602 SourceLocation Loc;
1603 QualType Type;
1604 const FunctionTypeProto *proto = 0;
1605 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1606 Loc = VD->getLocation();
1607 Type = VD->getType();
1608 }
1609 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1610 Loc = FD->getLocation();
1611 // Check for ObjC 'id' and class types that have been adorned with protocol
1612 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1613 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1614 assert(funcType && "missing function type");
1615 proto = dyn_cast<FunctionTypeProto>(funcType);
1616 if (!proto)
1617 return;
1618 Type = proto->getResultType();
1619 }
1620 else
1621 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001622
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001623 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001624 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001625
1626 const char *endBuf = SM->getCharacterData(Loc);
1627 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001628 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001629 startBuf--; // scan backward (from the decl location) for return type.
1630 const char *startRef = 0, *endRef = 0;
1631 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1632 // Get the locations of the startRef, endRef.
1633 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1634 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1635 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001636 InsertText(LessLoc, "/*", 2);
1637 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001638 }
1639 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001640 if (!proto)
1641 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001642 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001643 const char *startBuf = SM->getCharacterData(Loc);
1644 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001645 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1646 if (needToScanForQualifiers(proto->getArgType(i))) {
1647 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001648
Steve Naroffd5255f52007-11-01 13:24:47 +00001649 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001650 // scan forward (from the decl location) for argument types.
1651 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001652 const char *startRef = 0, *endRef = 0;
1653 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1654 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001655 SourceLocation LessLoc =
1656 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1657 SourceLocation GreaterLoc =
1658 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001659 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001660 InsertText(LessLoc, "/*", 2);
1661 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001662 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001663 startBuf = ++endBuf;
1664 }
1665 else {
1666 while (*startBuf != ')' && *startBuf != ',')
1667 startBuf++; // scan forward (from the decl location) for argument types.
1668 startBuf++;
1669 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001670 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001671}
1672
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001673// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001674void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001675 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1676 llvm::SmallVector<QualType, 16> ArgTys;
1677 ArgTys.push_back(Context->getPointerType(
1678 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001679 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001680 &ArgTys[0], ArgTys.size(),
1681 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001682 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001683 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001684 SelGetUidIdent, getFuncType,
1685 FunctionDecl::Extern, false, 0);
1686}
1687
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001688// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001689void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001690 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1691 llvm::SmallVector<QualType, 16> ArgTys;
1692 ArgTys.push_back(Context->getPointerType(
1693 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001694 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001695 &ArgTys[0], ArgTys.size(),
1696 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001697 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001698 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001699 SelGetProtoIdent, getFuncType,
1700 FunctionDecl::Extern, false, 0);
1701}
1702
Steve Naroffb29b4272008-04-14 22:03:09 +00001703void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001704 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001705 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001706 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001707 return;
1708 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001709 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001710}
1711
Steve Naroffc0a123c2008-03-11 17:37:02 +00001712// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001713void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001714 if (SuperContructorFunctionDecl)
1715 return;
1716 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1717 llvm::SmallVector<QualType, 16> ArgTys;
1718 QualType argT = Context->getObjCIdType();
1719 assert(!argT.isNull() && "Can't find 'id' type");
1720 ArgTys.push_back(argT);
1721 ArgTys.push_back(argT);
1722 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1723 &ArgTys[0], ArgTys.size(),
1724 false);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001725 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001726 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001727 msgSendIdent, msgSendType,
1728 FunctionDecl::Extern, false, 0);
1729}
1730
Steve Naroff09b266e2007-10-30 23:14:51 +00001731// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001732void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001733 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1734 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001735 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001736 assert(!argT.isNull() && "Can't find 'id' type");
1737 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001738 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001739 assert(!argT.isNull() && "Can't find 'SEL' type");
1740 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001741 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001742 &ArgTys[0], ArgTys.size(),
1743 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001744 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001745 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001746 msgSendIdent, msgSendType,
1747 FunctionDecl::Extern, false, 0);
1748}
1749
Steve Naroff874e2322007-11-15 10:28:18 +00001750// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001751void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001752 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1753 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001754 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001755 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001756 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001757 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1758 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1759 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001760 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001761 assert(!argT.isNull() && "Can't find 'SEL' type");
1762 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001763 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001764 &ArgTys[0], ArgTys.size(),
1765 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001766 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001767 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001768 msgSendIdent, msgSendType,
1769 FunctionDecl::Extern, false, 0);
1770}
1771
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001772// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001773void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001774 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1775 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001776 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001777 assert(!argT.isNull() && "Can't find 'id' type");
1778 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001779 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001780 assert(!argT.isNull() && "Can't find 'SEL' type");
1781 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001782 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001783 &ArgTys[0], ArgTys.size(),
1784 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001785 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001786 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001787 msgSendIdent, msgSendType,
1788 FunctionDecl::Extern, false, 0);
1789}
1790
1791// SynthMsgSendSuperStretFunctionDecl -
1792// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001793void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001794 IdentifierInfo *msgSendIdent =
1795 &Context->Idents.get("objc_msgSendSuper_stret");
1796 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001797 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001798 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001799 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001800 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1801 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1802 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001803 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001804 assert(!argT.isNull() && "Can't find 'SEL' type");
1805 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001806 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001807 &ArgTys[0], ArgTys.size(),
1808 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001809 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001810 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001811 msgSendIdent, msgSendType,
1812 FunctionDecl::Extern, false, 0);
1813}
1814
Steve Naroff1284db82008-05-08 22:02:18 +00001815// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001816void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001817 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1818 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001819 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001820 assert(!argT.isNull() && "Can't find 'id' type");
1821 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001822 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001823 assert(!argT.isNull() && "Can't find 'SEL' type");
1824 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001825 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001826 &ArgTys[0], ArgTys.size(),
1827 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001828 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001829 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001830 msgSendIdent, msgSendType,
1831 FunctionDecl::Extern, false, 0);
1832}
1833
Steve Naroff09b266e2007-10-30 23:14:51 +00001834// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001835void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001836 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1837 llvm::SmallVector<QualType, 16> ArgTys;
1838 ArgTys.push_back(Context->getPointerType(
1839 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001840 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001841 &ArgTys[0], ArgTys.size(),
1842 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001843 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001844 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001845 getClassIdent, getClassType,
1846 FunctionDecl::Extern, false, 0);
1847}
1848
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001849// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001850void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001851 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1852 llvm::SmallVector<QualType, 16> ArgTys;
1853 ArgTys.push_back(Context->getPointerType(
1854 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001855 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001856 &ArgTys[0], ArgTys.size(),
1857 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001858 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001859 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001860 getClassIdent, getClassType,
1861 FunctionDecl::Extern, false, 0);
1862}
1863
Steve Naroffb29b4272008-04-14 22:03:09 +00001864Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001865 QualType strType = getConstantStringStructType();
1866
1867 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001868
1869 std::string tmpName = InFileName;
1870 unsigned i;
1871 for (i=0; i < tmpName.length(); i++) {
1872 char c = tmpName.at(i);
1873 // replace any non alphanumeric characters with '_'.
1874 if (!isalpha(c) && (c < '0' || c > '9'))
1875 tmpName[i] = '_';
1876 }
1877 S += tmpName;
1878 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001879 S += utostr(NumObjCStringLiterals++);
1880
Steve Naroffba92b2e2008-03-27 22:29:16 +00001881 Preamble += "static __NSConstantStringImpl " + S;
1882 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1883 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001884 // The pretty printer for StringLiteral handles escape characters properly.
1885 std::ostringstream prettyBuf;
1886 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001887 Preamble += prettyBuf.str();
1888 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001889 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001890 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001891
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001892 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001893 &Context->Idents.get(S.c_str()), strType,
1894 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001895 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1896 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1897 Context->getPointerType(DRE->getType()),
1898 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001899 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001900 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001901 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001902 delete Exp;
1903 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001904}
1905
Steve Naroffb29b4272008-04-14 22:03:09 +00001906ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001907 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001908 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1909
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001910 if (PreDefinedExpr *PDE = dyn_cast<PreDefinedExpr>(recExpr))
1911 if (PDE->getIdentType() == PreDefinedExpr::ObjCSuper) {
1912 const PointerType *PT = PDE->getType()->getAsPointerType();
1913 assert(PT);
1914 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1915 return IT->getDecl();
1916 }
1917 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001918}
1919
1920// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001921QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001922 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001923 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001924 SourceLocation(),
1925 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001926 QualType FieldTypes[2];
1927
1928 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001929 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001930 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001931 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001932 // Create fields
1933 FieldDecl *FieldDecls[2];
1934
1935 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001936 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001937 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001938
1939 SuperStructDecl->defineBody(FieldDecls, 4);
1940 }
1941 return Context->getTagDeclType(SuperStructDecl);
1942}
1943
Steve Naroffb29b4272008-04-14 22:03:09 +00001944QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001945 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001946 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001947 SourceLocation(),
1948 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001949 QualType FieldTypes[4];
1950
1951 // struct objc_object *receiver;
1952 FieldTypes[0] = Context->getObjCIdType();
1953 // int flags;
1954 FieldTypes[1] = Context->IntTy;
1955 // char *str;
1956 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1957 // long length;
1958 FieldTypes[3] = Context->LongTy;
1959 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001960 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001961
1962 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001963 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001964 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001965
1966 ConstantStringDecl->defineBody(FieldDecls, 4);
1967 }
1968 return Context->getTagDeclType(ConstantStringDecl);
1969}
1970
Steve Naroffb29b4272008-04-14 22:03:09 +00001971Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001972 if (!SelGetUidFunctionDecl)
1973 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001974 if (!MsgSendFunctionDecl)
1975 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001976 if (!MsgSendSuperFunctionDecl)
1977 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001978 if (!MsgSendStretFunctionDecl)
1979 SynthMsgSendStretFunctionDecl();
1980 if (!MsgSendSuperStretFunctionDecl)
1981 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001982 if (!MsgSendFpretFunctionDecl)
1983 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001984 if (!GetClassFunctionDecl)
1985 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001986 if (!GetMetaClassFunctionDecl)
1987 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001988
Steve Naroff874e2322007-11-15 10:28:18 +00001989 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001990 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1991 // May need to use objc_msgSend_stret() as well.
1992 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001993 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001994 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00001995 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001996 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00001997 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001998 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001999 }
Steve Naroff874e2322007-11-15 10:28:18 +00002000
Steve Naroff934f2762007-10-24 22:48:43 +00002001 // Synthesize a call to objc_msgSend().
2002 llvm::SmallVector<Expr*, 8> MsgExprs;
2003 IdentifierInfo *clsName = Exp->getClassName();
2004
2005 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2006 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002007 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2008 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002009 if (!strcmp(clsName->getName(), "super")) {
2010 MsgSendFlavor = MsgSendSuperFunctionDecl;
2011 if (MsgSendStretFlavor)
2012 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2013 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2014
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002015 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002016 CurMethodDecl->getClassInterface()->getSuperClass();
2017
2018 llvm::SmallVector<Expr*, 4> InitExprs;
2019
2020 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002021 InitExprs.push_back(new DeclRefExpr(
2022 CurMethodDecl->getSelfDecl(),
2023 Context->getObjCIdType(),
2024 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002025 llvm::SmallVector<Expr*, 8> ClsExprs;
2026 QualType argType = Context->getPointerType(Context->CharTy);
2027 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2028 SuperDecl->getIdentifier()->getLength(),
2029 false, argType, SourceLocation(),
2030 SourceLocation()));
2031 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2032 &ClsExprs[0],
2033 ClsExprs.size());
2034 // To turn off a warning, type-cast to 'id'
2035 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002036 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002037 Cls, SourceLocation())); // set 'super class', using objc_getClass().
2038 // struct objc_super
2039 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002040 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002041
Steve Naroff23f41272008-03-11 18:14:26 +00002042 if (LangOpts.Microsoft) {
2043 SynthSuperContructorFunctionDecl();
2044 // Simulate a contructor call...
2045 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2046 superType, SourceLocation());
2047 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2048 superType, SourceLocation());
2049 } else {
2050 // (struct objc_super) { <exprs from above> }
2051 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2052 &InitExprs[0], InitExprs.size(),
2053 SourceLocation());
2054 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2055 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002056 // struct objc_super *
2057 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2058 Context->getPointerType(SuperRep->getType()),
2059 SourceLocation());
2060 MsgExprs.push_back(Unop);
2061 } else {
2062 llvm::SmallVector<Expr*, 8> ClsExprs;
2063 QualType argType = Context->getPointerType(Context->CharTy);
2064 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2065 clsName->getLength(),
2066 false, argType, SourceLocation(),
2067 SourceLocation()));
2068 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2069 &ClsExprs[0],
2070 ClsExprs.size());
2071 MsgExprs.push_back(Cls);
2072 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002073 } else { // instance message.
2074 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002075
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002076 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002077 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002078 if (MsgSendStretFlavor)
2079 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002080 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2081
2082 llvm::SmallVector<Expr*, 4> InitExprs;
2083
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002084 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002085 new CastExpr(Context->getObjCIdType(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002086 new DeclRefExpr(CurMethodDecl->getSelfDecl(),
2087 Context->getObjCIdType(),
2088 SourceLocation()),
2089 SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002090
2091 llvm::SmallVector<Expr*, 8> ClsExprs;
2092 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002093 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2094 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002095 false, argType, SourceLocation(),
2096 SourceLocation()));
2097 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002098 &ClsExprs[0],
2099 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002100 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002101 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002102 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002103 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002104 // struct objc_super
2105 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002106 Expr *SuperRep;
2107
2108 if (LangOpts.Microsoft) {
2109 SynthSuperContructorFunctionDecl();
2110 // Simulate a contructor call...
2111 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2112 superType, SourceLocation());
2113 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2114 superType, SourceLocation());
2115 } else {
2116 // (struct objc_super) { <exprs from above> }
2117 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2118 &InitExprs[0], InitExprs.size(),
2119 SourceLocation());
2120 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2121 }
Steve Naroff874e2322007-11-15 10:28:18 +00002122 // struct objc_super *
2123 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2124 Context->getPointerType(SuperRep->getType()),
2125 SourceLocation());
2126 MsgExprs.push_back(Unop);
2127 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002128 // Remove all type-casts because it may contain objc-style types; e.g.
2129 // Foo<Proto> *.
2130 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2131 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002132 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002133 MsgExprs.push_back(recExpr);
2134 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002135 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002136 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002137 llvm::SmallVector<Expr*, 8> SelExprs;
2138 QualType argType = Context->getPointerType(Context->CharTy);
2139 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2140 Exp->getSelector().getName().size(),
2141 false, argType, SourceLocation(),
2142 SourceLocation()));
2143 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2144 &SelExprs[0], SelExprs.size());
2145 MsgExprs.push_back(SelExp);
2146
2147 // Now push any user supplied arguments.
2148 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002149 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002150 // Make all implicit casts explicit...ICE comes in handy:-)
2151 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2152 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002153 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2154 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002155 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002156 }
2157 // Make id<P...> cast into an 'id' cast.
2158 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002159 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002160 while ((CE = dyn_cast<CastExpr>(userExpr)))
2161 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002162 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002163 userExpr, SourceLocation());
2164 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002165 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002166 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002167 // We've transferred the ownership to MsgExprs. Null out the argument in
2168 // the original expression, since we will delete it below.
2169 Exp->setArg(i, 0);
2170 }
Steve Naroffab972d32007-11-04 22:37:50 +00002171 // Generate the funky cast.
2172 CastExpr *cast;
2173 llvm::SmallVector<QualType, 8> ArgTypes;
2174 QualType returnType;
2175
2176 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002177 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2178 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2179 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002180 ArgTypes.push_back(Context->getObjCIdType());
2181 ArgTypes.push_back(Context->getObjCSelType());
2182 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002183 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002184 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002185 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2186 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002187 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002188 ArgTypes.push_back(t);
2189 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002190 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2191 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002192 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002193 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002194 }
2195 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002196 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002197
2198 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002199 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2200 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002201
2202 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2203 // If we don't do this cast, we get the following bizarre warning/note:
2204 // xx.m:13: warning: function called through a non-compatible type
2205 // xx.m:13: note: if this code is reached, the program will abort
2206 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2207 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002208
Steve Naroffab972d32007-11-04 22:37:50 +00002209 // Now do the "normal" pointer to function cast.
2210 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002211 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002212 // If we don't have a method decl, force a variadic cast.
2213 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002214 castType = Context->getPointerType(castType);
2215 cast = new CastExpr(castType, cast, SourceLocation());
2216
2217 // Don't forget the parens to enforce the proper binding.
2218 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2219
2220 const FunctionType *FT = msgSendType->getAsFunctionType();
2221 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2222 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002223 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002224 if (MsgSendStretFlavor) {
2225 // We have the method which returns a struct/union. Must also generate
2226 // call to objc_msgSend_stret and hang both varieties on a conditional
2227 // expression which dictate which one to envoke depending on size of
2228 // method's return type.
2229
2230 // Create a reference to the objc_msgSend_stret() declaration.
2231 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2232 SourceLocation());
2233 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2234 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2235 SourceLocation());
2236 // Now do the "normal" pointer to function cast.
2237 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002238 &ArgTypes[0], ArgTypes.size(),
2239 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002240 castType = Context->getPointerType(castType);
2241 cast = new CastExpr(castType, cast, SourceLocation());
2242
2243 // Don't forget the parens to enforce the proper binding.
2244 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2245
2246 FT = msgSendType->getAsFunctionType();
2247 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2248 FT->getResultType(), SourceLocation());
2249
2250 // Build sizeof(returnType)
2251 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2252 returnType, Context->getSizeType(),
2253 SourceLocation(), SourceLocation());
2254 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2255 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2256 // For X86 it is more complicated and some kind of target specific routine
2257 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002258 unsigned IntSize =
2259 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002260 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2261 Context->IntTy,
2262 SourceLocation());
2263 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2264 BinaryOperator::LE,
2265 Context->IntTy,
2266 SourceLocation());
2267 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2268 ConditionalOperator *CondExpr =
2269 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002270 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002271 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002272 return ReplacingStmt;
2273}
2274
Steve Naroffb29b4272008-04-14 22:03:09 +00002275Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002276 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002277 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002278 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002279
Chris Lattnere64b7772007-10-24 16:57:36 +00002280 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002281 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002282}
2283
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002284/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2285/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002286Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002287 if (!GetProtocolFunctionDecl)
2288 SynthGetProtocolFunctionDecl();
2289 // Create a call to objc_getProtocol("ProtocolName").
2290 llvm::SmallVector<Expr*, 8> ProtoExprs;
2291 QualType argType = Context->getPointerType(Context->CharTy);
2292 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2293 strlen(Exp->getProtocol()->getName()),
2294 false, argType, SourceLocation(),
2295 SourceLocation()));
2296 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2297 &ProtoExprs[0],
2298 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002299 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002300 delete Exp;
2301 return ProtoExp;
2302
2303}
2304
Steve Naroffbaf58c32008-05-31 14:15:04 +00002305bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2306 const char *endBuf) {
2307 while (startBuf < endBuf) {
2308 if (*startBuf == '#') {
2309 // Skip whitespace.
2310 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2311 ;
2312 if (!strncmp(startBuf, "if", strlen("if")) ||
2313 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2314 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2315 !strncmp(startBuf, "define", strlen("define")) ||
2316 !strncmp(startBuf, "undef", strlen("undef")) ||
2317 !strncmp(startBuf, "else", strlen("else")) ||
2318 !strncmp(startBuf, "elif", strlen("elif")) ||
2319 !strncmp(startBuf, "endif", strlen("endif")) ||
2320 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2321 !strncmp(startBuf, "include", strlen("include")) ||
2322 !strncmp(startBuf, "import", strlen("import")) ||
2323 !strncmp(startBuf, "include_next", strlen("include_next")))
2324 return true;
2325 }
2326 startBuf++;
2327 }
2328 return false;
2329}
2330
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002331/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002332/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002333void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002334 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002335 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2336 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002337 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002338 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002339 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002340 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002341 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002342 SourceLocation LocStart = CDecl->getLocStart();
2343 SourceLocation LocEnd = CDecl->getLocEnd();
2344
2345 const char *startBuf = SM->getCharacterData(LocStart);
2346 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002347
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002348 // If no ivars and no root or if its root, directly or indirectly,
2349 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002350 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2351 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002352 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002353 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002354 return;
2355 }
2356
2357 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002358 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002359 Result += "\nstruct ";
2360 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002361 if (LangOpts.Microsoft)
2362 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002363
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002364 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002365 const char *cursor = strchr(startBuf, '{');
2366 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002367 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002368 // If the buffer contains preprocessor directives, we do more fine-grained
2369 // rewrites. This is intended to fix code that looks like (which occurs in
2370 // NSURL.h, for example):
2371 //
2372 // #ifdef XYZ
2373 // @interface Foo : NSObject
2374 // #else
2375 // @interface FooBar : NSObject
2376 // #endif
2377 // {
2378 // int i;
2379 // }
2380 // @end
2381 //
2382 // This clause is segregated to avoid breaking the common case.
2383 if (BufferContainsPPDirectives(startBuf, cursor)) {
2384 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2385 CDecl->getClassLoc();
2386 const char *endHeader = SM->getCharacterData(L);
2387 endHeader += Lexer::MeasureTokenLength(L, *SM);
2388
Chris Lattner3db6cae2008-07-21 18:19:38 +00002389 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002390 // advance to the end of the referenced protocols.
2391 while (endHeader < cursor && *endHeader != '>') endHeader++;
2392 endHeader++;
2393 }
2394 // rewrite the original header
2395 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2396 } else {
2397 // rewrite the original header *without* disturbing the '{'
2398 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2399 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002400 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002401 Result = "\n struct ";
2402 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002403 Result += "_IMPL ";
2404 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002405 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002406
2407 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002408 SourceLocation OnePastCurly =
2409 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2410 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002411 }
2412 cursor++; // past '{'
2413
2414 // Now comment out any visibility specifiers.
2415 while (cursor < endBuf) {
2416 if (*cursor == '@') {
2417 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002418 // Skip whitespace.
2419 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2420 /*scan*/;
2421
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002422 // FIXME: presence of @public, etc. inside comment results in
2423 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002424 if (!strncmp(cursor, "public", strlen("public")) ||
2425 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002426 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002427 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002428 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002429 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002430 // FIXME: If there are cases where '<' is used in ivar declaration part
2431 // of user code, then scan the ivar list and use needToScanForQualifiers
2432 // for type checking.
2433 else if (*cursor == '<') {
2434 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002435 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002436 cursor = strchr(cursor, '>');
2437 cursor++;
2438 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002439 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002440 }
Steve Narofffea763e82007-11-14 19:25:57 +00002441 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002442 }
Steve Narofffea763e82007-11-14 19:25:57 +00002443 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002444 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002445 } else { // we don't have any instance variables - insert super struct.
2446 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2447 Result += " {\n struct ";
2448 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002449 Result += "_IMPL ";
2450 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002451 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002452 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002453 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002454 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002455 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002456 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002457}
2458
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002459// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002460/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002461void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002462 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002463 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002464 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002465 const char *ClassName,
2466 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002467 if (MethodBegin == MethodEnd) return;
2468
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002469 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002470 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002471 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002472 SEL _cmd;
2473 char *method_types;
2474 void *_imp;
2475 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002476 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002477 Result += "\nstruct _objc_method {\n";
2478 Result += "\tSEL _cmd;\n";
2479 Result += "\tchar *method_types;\n";
2480 Result += "\tvoid *_imp;\n";
2481 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002482
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002483 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002484 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002485
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002486 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002487
2488 /* struct {
2489 struct _objc_method_list *next_method;
2490 int method_count;
2491 struct _objc_method method_list[];
2492 }
2493 */
2494 Result += "\nstatic struct {\n";
2495 Result += "\tstruct _objc_method_list *next_method;\n";
2496 Result += "\tint method_count;\n";
2497 Result += "\tstruct _objc_method method_list[";
2498 Result += utostr(MethodEnd-MethodBegin);
2499 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002500 Result += prefix;
2501 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2502 Result += "_METHODS_";
2503 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002504 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002505 Result += IsInstanceMethod ? "inst" : "cls";
2506 Result += "_meth\")))= ";
2507 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002508
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002509 Result += "\t,{{(SEL)\"";
2510 Result += (*MethodBegin)->getSelector().getName().c_str();
2511 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002512 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002513 Result += "\", \"";
2514 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002515 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002516 Result += MethodInternalNames[*MethodBegin];
2517 Result += "}\n";
2518 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2519 Result += "\t ,{(SEL)\"";
2520 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002521 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002522 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002523 Result += "\", \"";
2524 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002525 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002526 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002527 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002528 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002529 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002530}
2531
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002532/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002533void RewriteObjC::
2534RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2535 const char *prefix,
2536 const char *ClassName,
2537 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002538 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002539 if (Protocols.empty()) return;
2540
2541 for (unsigned i = 0; i != Protocols.size(); i++) {
2542 ObjCProtocolDecl *PDecl = Protocols[i];
2543 // Output struct protocol_methods holder of method selector and type.
2544 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2545 /* struct protocol_methods {
2546 SEL _cmd;
2547 char *method_types;
2548 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002549 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002550 Result += "\nstruct protocol_methods {\n";
2551 Result += "\tSEL _cmd;\n";
2552 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002553 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002554
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002555 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002556 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002557 // Do not synthesize the protocol more than once.
2558 if (ObjCSynthesizedProtocols.count(PDecl))
2559 continue;
2560
2561 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2562 unsigned NumMethods = PDecl->getNumInstanceMethods();
2563 /* struct _objc_protocol_method_list {
2564 int protocol_method_count;
2565 struct protocol_methods protocols[];
2566 }
2567 */
2568 Result += "\nstatic struct {\n";
2569 Result += "\tint protocol_method_count;\n";
2570 Result += "\tstruct protocol_methods protocols[";
2571 Result += utostr(NumMethods);
2572 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2573 Result += PDecl->getName();
2574 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2575 "{\n\t" + utostr(NumMethods) + "\n";
2576
2577 // Output instance methods declared in this protocol.
2578 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2579 E = PDecl->instmeth_end(); I != E; ++I) {
2580 if (I == PDecl->instmeth_begin())
2581 Result += "\t ,{{(SEL)\"";
2582 else
2583 Result += "\t ,{(SEL)\"";
2584 Result += (*I)->getSelector().getName().c_str();
2585 std::string MethodTypeString;
2586 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2587 Result += "\", \"";
2588 Result += MethodTypeString;
2589 Result += "\"}\n";
2590 }
2591 Result += "\t }\n};\n";
2592 }
2593
2594 // Output class methods declared in this protocol.
2595 int NumMethods = PDecl->getNumClassMethods();
2596 if (NumMethods > 0) {
2597 /* struct _objc_protocol_method_list {
2598 int protocol_method_count;
2599 struct protocol_methods protocols[];
2600 }
2601 */
2602 Result += "\nstatic struct {\n";
2603 Result += "\tint protocol_method_count;\n";
2604 Result += "\tstruct protocol_methods protocols[";
2605 Result += utostr(NumMethods);
2606 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2607 Result += PDecl->getName();
2608 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2609 "{\n\t";
2610 Result += utostr(NumMethods);
2611 Result += "\n";
2612
2613 // Output instance methods declared in this protocol.
2614 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2615 E = PDecl->classmeth_end(); I != E; ++I) {
2616 if (I == PDecl->classmeth_begin())
2617 Result += "\t ,{{(SEL)\"";
2618 else
2619 Result += "\t ,{(SEL)\"";
2620 Result += (*I)->getSelector().getName().c_str();
2621 std::string MethodTypeString;
2622 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2623 Result += "\", \"";
2624 Result += MethodTypeString;
2625 Result += "\"}\n";
2626 }
2627 Result += "\t }\n};\n";
2628 }
2629
2630 // Output:
2631 /* struct _objc_protocol {
2632 // Objective-C 1.0 extensions
2633 struct _objc_protocol_extension *isa;
2634 char *protocol_name;
2635 struct _objc_protocol **protocol_list;
2636 struct _objc_protocol_method_list *instance_methods;
2637 struct _objc_protocol_method_list *class_methods;
2638 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002639 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002640 static bool objc_protocol = false;
2641 if (!objc_protocol) {
2642 Result += "\nstruct _objc_protocol {\n";
2643 Result += "\tstruct _objc_protocol_extension *isa;\n";
2644 Result += "\tchar *protocol_name;\n";
2645 Result += "\tstruct _objc_protocol **protocol_list;\n";
2646 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2647 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2648 Result += "};\n";
2649
2650 objc_protocol = true;
2651 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002652
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002653 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2654 Result += PDecl->getName();
2655 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2656 "{\n\t0, \"";
2657 Result += PDecl->getName();
2658 Result += "\", 0, ";
2659 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2660 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2661 Result += PDecl->getName();
2662 Result += ", ";
2663 }
2664 else
2665 Result += "0, ";
2666 if (PDecl->getNumClassMethods() > 0) {
2667 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2668 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002669 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002670 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002671 else
2672 Result += "0\n";
2673 Result += "};\n";
2674
2675 // Mark this protocol as having been generated.
2676 if (!ObjCSynthesizedProtocols.insert(PDecl))
2677 assert(false && "protocol already synthesized");
2678 }
2679 // Output the top lovel protocol meta-data for the class.
2680 /* struct _objc_protocol_list {
2681 struct _objc_protocol_list *next;
2682 int protocol_count;
2683 struct _objc_protocol *class_protocols[];
2684 }
2685 */
2686 Result += "\nstatic struct {\n";
2687 Result += "\tstruct _objc_protocol_list *next;\n";
2688 Result += "\tint protocol_count;\n";
2689 Result += "\tstruct _objc_protocol *class_protocols[";
2690 Result += utostr(Protocols.size());
2691 Result += "];\n} _OBJC_";
2692 Result += prefix;
2693 Result += "_PROTOCOLS_";
2694 Result += ClassName;
2695 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2696 "{\n\t0, ";
2697 Result += utostr(Protocols.size());
2698 Result += "\n";
2699
2700 Result += "\t,{&_OBJC_PROTOCOL_";
2701 Result += Protocols[0]->getName();
2702 Result += " \n";
2703
2704 for (unsigned i = 1; i != Protocols.size(); i++) {
2705 Result += "\t ,&_OBJC_PROTOCOL_";
2706 Result += Protocols[i]->getName();
2707 Result += "\n";
2708 }
2709 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002710}
2711
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002712/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002713/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002714void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002715 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002716 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002717 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002718 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002719 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2720 CDecl = CDecl->getNextClassCategory())
2721 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2722 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002723
Chris Lattnereb44eee2007-12-23 01:40:15 +00002724 std::string FullCategoryName = ClassDecl->getName();
2725 FullCategoryName += '_';
2726 FullCategoryName += IDecl->getName();
2727
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002728 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002729 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002730 true, "CATEGORY_", FullCategoryName.c_str(),
2731 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002732
2733 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002734 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002735 false, "CATEGORY_", FullCategoryName.c_str(),
2736 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002737
2738 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002739 // Null CDecl is case of a category implementation with no category interface
2740 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002741 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002742 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002743
2744 /* struct _objc_category {
2745 char *category_name;
2746 char *class_name;
2747 struct _objc_method_list *instance_methods;
2748 struct _objc_method_list *class_methods;
2749 struct _objc_protocol_list *protocols;
2750 // Objective-C 1.0 extensions
2751 uint32_t size; // sizeof (struct _objc_category)
2752 struct _objc_property_list *instance_properties; // category's own
2753 // @property decl.
2754 };
2755 */
2756
2757 static bool objc_category = false;
2758 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002759 Result += "\nstruct _objc_category {\n";
2760 Result += "\tchar *category_name;\n";
2761 Result += "\tchar *class_name;\n";
2762 Result += "\tstruct _objc_method_list *instance_methods;\n";
2763 Result += "\tstruct _objc_method_list *class_methods;\n";
2764 Result += "\tstruct _objc_protocol_list *protocols;\n";
2765 Result += "\tunsigned int size;\n";
2766 Result += "\tstruct _objc_property_list *instance_properties;\n";
2767 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002768 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002769 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002770 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2771 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002772 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002773 Result += IDecl->getName();
2774 Result += "\"\n\t, \"";
2775 Result += ClassDecl->getName();
2776 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002777
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002778 if (IDecl->getNumInstanceMethods() > 0) {
2779 Result += "\t, (struct _objc_method_list *)"
2780 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2781 Result += FullCategoryName;
2782 Result += "\n";
2783 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002784 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002785 Result += "\t, 0\n";
2786 if (IDecl->getNumClassMethods() > 0) {
2787 Result += "\t, (struct _objc_method_list *)"
2788 "&_OBJC_CATEGORY_CLASS_METHODS_";
2789 Result += FullCategoryName;
2790 Result += "\n";
2791 }
2792 else
2793 Result += "\t, 0\n";
2794
Chris Lattner780f3292008-07-21 21:32:27 +00002795 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002796 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2797 Result += FullCategoryName;
2798 Result += "\n";
2799 }
2800 else
2801 Result += "\t, 0\n";
2802 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002803}
2804
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002805/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2806/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002807void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002808 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002809 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002810 if (ivar->isBitField()) {
2811 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2812 // place all bitfields at offset 0.
2813 Result += "0";
2814 } else {
2815 Result += "__OFFSETOFIVAR__(struct ";
2816 Result += IDecl->getName();
2817 if (LangOpts.Microsoft)
2818 Result += "_IMPL";
2819 Result += ", ";
2820 Result += ivar->getName();
2821 Result += ")";
2822 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002823}
2824
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002825//===----------------------------------------------------------------------===//
2826// Meta Data Emission
2827//===----------------------------------------------------------------------===//
2828
Steve Naroffb29b4272008-04-14 22:03:09 +00002829void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002830 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002831 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002832
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002833 // Explictly declared @interface's are already synthesized.
2834 if (CDecl->ImplicitInterfaceDecl()) {
2835 // FIXME: Implementation of a class with no @interface (legacy) doese not
2836 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002837 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002838 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002839
Chris Lattnerbe6df082007-12-12 07:56:42 +00002840 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002841 unsigned NumIvars = !IDecl->ivar_empty()
2842 ? IDecl->ivar_size()
2843 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002844 if (NumIvars > 0) {
2845 static bool objc_ivar = false;
2846 if (!objc_ivar) {
2847 /* struct _objc_ivar {
2848 char *ivar_name;
2849 char *ivar_type;
2850 int ivar_offset;
2851 };
2852 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002853 Result += "\nstruct _objc_ivar {\n";
2854 Result += "\tchar *ivar_name;\n";
2855 Result += "\tchar *ivar_type;\n";
2856 Result += "\tint ivar_offset;\n";
2857 Result += "};\n";
2858
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002859 objc_ivar = true;
2860 }
2861
Steve Naroff946a6932008-03-11 00:12:29 +00002862 /* struct {
2863 int ivar_count;
2864 struct _objc_ivar ivar_list[nIvars];
2865 };
2866 */
2867 Result += "\nstatic struct {\n";
2868 Result += "\tint ivar_count;\n";
2869 Result += "\tstruct _objc_ivar ivar_list[";
2870 Result += utostr(NumIvars);
2871 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002872 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002873 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002874 "{\n\t";
2875 Result += utostr(NumIvars);
2876 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002877
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002878 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002879 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002880 IVI = IDecl->ivar_begin();
2881 IVE = IDecl->ivar_end();
2882 } else {
2883 IVI = CDecl->ivar_begin();
2884 IVE = CDecl->ivar_end();
2885 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002886 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002887 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002888 Result += "\", \"";
2889 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002890 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2891 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002892 Result += StrEncoding;
2893 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002894 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002895 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002896 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002897 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002898 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002899 Result += "\", \"";
2900 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002901 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2902 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002903 Result += StrEncoding;
2904 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002905 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002906 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002907 }
2908
2909 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002910 }
2911
2912 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002913 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002914 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002915
2916 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002917 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002918 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002919
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002920 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00002921 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002922 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002923
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002924
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002925 // Declaration of class/meta-class metadata
2926 /* struct _objc_class {
2927 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002928 const char *super_class_name;
2929 char *name;
2930 long version;
2931 long info;
2932 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002933 struct _objc_ivar_list *ivars;
2934 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002935 struct objc_cache *cache;
2936 struct objc_protocol_list *protocols;
2937 const char *ivar_layout;
2938 struct _objc_class_ext *ext;
2939 };
2940 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002941 static bool objc_class = false;
2942 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002943 Result += "\nstruct _objc_class {\n";
2944 Result += "\tstruct _objc_class *isa;\n";
2945 Result += "\tconst char *super_class_name;\n";
2946 Result += "\tchar *name;\n";
2947 Result += "\tlong version;\n";
2948 Result += "\tlong info;\n";
2949 Result += "\tlong instance_size;\n";
2950 Result += "\tstruct _objc_ivar_list *ivars;\n";
2951 Result += "\tstruct _objc_method_list *methods;\n";
2952 Result += "\tstruct objc_cache *cache;\n";
2953 Result += "\tstruct _objc_protocol_list *protocols;\n";
2954 Result += "\tconst char *ivar_layout;\n";
2955 Result += "\tstruct _objc_class_ext *ext;\n";
2956 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002957 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002958 }
2959
2960 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002961 ObjCInterfaceDecl *RootClass = 0;
2962 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002963 while (SuperClass) {
2964 RootClass = SuperClass;
2965 SuperClass = SuperClass->getSuperClass();
2966 }
2967 SuperClass = CDecl->getSuperClass();
2968
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002969 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2970 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002971 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002972 "{\n\t(struct _objc_class *)\"";
2973 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2974 Result += "\"";
2975
2976 if (SuperClass) {
2977 Result += ", \"";
2978 Result += SuperClass->getName();
2979 Result += "\", \"";
2980 Result += CDecl->getName();
2981 Result += "\"";
2982 }
2983 else {
2984 Result += ", 0, \"";
2985 Result += CDecl->getName();
2986 Result += "\"";
2987 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002988 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002989 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002990 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002991 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002992 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002993 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002994 Result += "\n";
2995 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002996 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002997 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00002998 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002999 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003000 Result += CDecl->getName();
3001 Result += ",0,0\n";
3002 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003003 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003004 Result += "\t,0,0,0,0\n";
3005 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003006
3007 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003008 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3009 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003010 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003011 "{\n\t&_OBJC_METACLASS_";
3012 Result += CDecl->getName();
3013 if (SuperClass) {
3014 Result += ", \"";
3015 Result += SuperClass->getName();
3016 Result += "\", \"";
3017 Result += CDecl->getName();
3018 Result += "\"";
3019 }
3020 else {
3021 Result += ", 0, \"";
3022 Result += CDecl->getName();
3023 Result += "\"";
3024 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003025 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003026 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003027 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003028 Result += ",0";
3029 else {
3030 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003031 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003032 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003033 if (LangOpts.Microsoft)
3034 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003035 Result += ")";
3036 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003037 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003038 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003039 Result += CDecl->getName();
3040 Result += "\n\t";
3041 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003042 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003043 Result += ",0";
3044 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003045 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003046 Result += CDecl->getName();
3047 Result += ", 0\n\t";
3048 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003049 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003050 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003051 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003052 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003053 Result += CDecl->getName();
3054 Result += ", 0,0\n";
3055 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003056 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003057 Result += ",0,0,0\n";
3058 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003059}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003060
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003061/// RewriteImplementations - This routine rewrites all method implementations
3062/// and emits meta-data.
3063
Steve Naroffb29b4272008-04-14 22:03:09 +00003064void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003065 int ClsDefCount = ClassImplementation.size();
3066 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003067
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003068 if (ClsDefCount == 0 && CatDefCount == 0)
3069 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003070 // Rewrite implemented methods
3071 for (int i = 0; i < ClsDefCount; i++)
3072 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003073
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003074 for (int i = 0; i < CatDefCount; i++)
3075 RewriteImplementationDecl(CategoryImplementation[i]);
3076
Steve Naroff5df5b762008-05-07 21:23:49 +00003077 // This is needed for determining instance variable offsets.
3078 Result += "#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003079 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003080 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003081 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003082
3083 // For each implemented category, write out all its meta data.
3084 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003085 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003086
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003087 // Write objc_symtab metadata
3088 /*
3089 struct _objc_symtab
3090 {
3091 long sel_ref_cnt;
3092 SEL *refs;
3093 short cls_def_cnt;
3094 short cat_def_cnt;
3095 void *defs[cls_def_cnt + cat_def_cnt];
3096 };
3097 */
3098
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003099 Result += "\nstruct _objc_symtab {\n";
3100 Result += "\tlong sel_ref_cnt;\n";
3101 Result += "\tSEL *refs;\n";
3102 Result += "\tshort cls_def_cnt;\n";
3103 Result += "\tshort cat_def_cnt;\n";
3104 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3105 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003106
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003107 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003108 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003109 Result += "\t0, 0, " + utostr(ClsDefCount)
3110 + ", " + utostr(CatDefCount) + "\n";
3111 for (int i = 0; i < ClsDefCount; i++) {
3112 Result += "\t,&_OBJC_CLASS_";
3113 Result += ClassImplementation[i]->getName();
3114 Result += "\n";
3115 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003116
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003117 for (int i = 0; i < CatDefCount; i++) {
3118 Result += "\t,&_OBJC_CATEGORY_";
3119 Result += CategoryImplementation[i]->getClassInterface()->getName();
3120 Result += "_";
3121 Result += CategoryImplementation[i]->getName();
3122 Result += "\n";
3123 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003124
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003125 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003126
3127 // Write objc_module metadata
3128
3129 /*
3130 struct _objc_module {
3131 long version;
3132 long size;
3133 const char *name;
3134 struct _objc_symtab *symtab;
3135 }
3136 */
3137
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003138 Result += "\nstruct _objc_module {\n";
3139 Result += "\tlong version;\n";
3140 Result += "\tlong size;\n";
3141 Result += "\tconst char *name;\n";
3142 Result += "\tstruct _objc_symtab *symtab;\n";
3143 Result += "};\n\n";
3144 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003145 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003146 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3147 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003148 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003149
3150 if (LangOpts.Microsoft) {
3151 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003152 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003153 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3154 Result += "&_OBJC_MODULES;\n";
3155 Result += "#pragma data_seg(pop)\n\n";
3156 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003157}
Chris Lattner311ff022007-10-16 22:36:42 +00003158
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003159
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003160
3161