blob: eb9d01256497bd92efcb2a188d0667c801c6f1d5 [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"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner26de4652007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000025#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000026#include "llvm/Support/Streams.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000027#include "llvm/System/Path.h"
Steve Naroff0d4e9632008-04-14 22:53:48 +000028#include <sstream>
Chris Lattnerc68ab772008-03-22 00:08:40 +000029#include <fstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Steve Naroff0113c9d2008-01-28 21:34:52 +000033static llvm::cl::opt<bool>
34SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
35 llvm::cl::desc("Silence ObjC rewriting warnings"));
36
Chris Lattner77cd2a02007-10-11 00:43:27 +000037namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000038 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000039 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000040 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000041 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000042 unsigned RewriteFailedDiag;
43
Chris Lattner01c57482007-10-17 22:35:30 +000044 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000045 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000046 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000047 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000048 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000049 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000050
Ted Kremeneka526c5c2008-01-07 19:49:32 +000051 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
52 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
53 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000054 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000055 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
56 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000057 llvm::SmallVector<Stmt *, 32> Stmts;
58 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000059 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000083 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
94
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000095 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000096 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000097 void Initialize(ASTContext &context);
98
Chris Lattner8a12c272007-10-11 18:38:32 +000099
Chris Lattnerf04da132007-10-24 17:06:59 +0000100 // Top Level Driver code.
101 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000102 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000103 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000104 Diagnostic &D, const LangOptions &LOpts);
Steve Naroffb29b4272008-04-14 22:03:09 +0000105 ~RewriteObjC();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000106
107 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000108 // If replacement succeeded or warning disabled return with no warning.
109 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000110 return;
111
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000112 SourceRange Range = Old->getSourceRange();
113 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
114 0, 0, &Range, 1);
115 }
116
Steve Naroffba92b2e2008-03-27 22:29:16 +0000117 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
118 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000119 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000120 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000121 SilenceRewriteMacroWarning)
122 return;
123
124 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
125 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000126
Chris Lattneraadaf782008-01-31 19:51:04 +0000127 void RemoveText(SourceLocation Loc, unsigned StrLen) {
128 // If removal succeeded or warning disabled return with no warning.
129 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
130 return;
131
132 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
133 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000134
Chris Lattneraadaf782008-01-31 19:51:04 +0000135 void ReplaceText(SourceLocation Start, unsigned OrigLength,
136 const char *NewStr, unsigned NewLength) {
137 // If removal succeeded or warning disabled return with no warning.
138 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
139 SilenceRewriteMacroWarning)
140 return;
141
142 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
143 }
144
Chris Lattnerf04da132007-10-24 17:06:59 +0000145 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000146 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000147 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000148 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000149 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
150 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000151 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000152 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
153 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
154 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
155 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
156 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000157 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000158 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000159 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000160 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000161 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000162 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000163 QualType getConstantStringStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000164
Chris Lattnerf04da132007-10-24 17:06:59 +0000165 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000166 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000167 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000168 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000169 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000170 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000171 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000172 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000173 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000174 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000175 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
176 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
177 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000178 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
179 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000180 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
181 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000182 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000183 Stmt *RewriteBreakStmt(BreakStmt *S);
184 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000185 void SynthCountByEnumWithState(std::string &buf);
186
Steve Naroff09b266e2007-10-30 23:14:51 +0000187 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000188 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000189 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000190 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000191 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000192 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000193 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000194 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000195 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000196 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000197
Chris Lattnerf04da132007-10-24 17:06:59 +0000198 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000199 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000200 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000201
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000202 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000203 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000204
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000205 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
206 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000207 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000208 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000209 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000210 const char *ClassName,
211 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000212
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000213 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000214 int NumProtocols,
215 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000216 const char *ClassName,
217 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000218 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000219 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000220 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
221 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000222 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000223 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000224 };
225}
226
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000227static bool IsHeaderFile(const std::string &Filename) {
228 std::string::size_type DotPos = Filename.rfind('.');
229
230 if (DotPos == std::string::npos) {
231 // no file extension
232 return false;
233 }
234
235 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
236 // C header: .h
237 // C++ header: .hh or .H;
238 return Ext == "h" || Ext == "hh" || Ext == "H";
239}
240
Steve Naroffb29b4272008-04-14 22:03:09 +0000241RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000242 Diagnostic &D, const LangOptions &LOpts)
243 : Diags(D), LangOpts(LOpts) {
244 IsHeader = IsHeaderFile(inFile);
245 InFileName = inFile;
246 OutFileName = outFile;
247 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
248 "rewriting sub-expression within a macro (may not be correct)");
249}
250
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000251ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000252 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000253 Diagnostic &Diags,
254 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000255 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000256}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000257
Steve Naroffb29b4272008-04-14 22:03:09 +0000258void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000259 Context = &context;
260 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000261 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000262 MsgSendFunctionDecl = 0;
263 MsgSendSuperFunctionDecl = 0;
264 MsgSendStretFunctionDecl = 0;
265 MsgSendSuperStretFunctionDecl = 0;
266 MsgSendFpretFunctionDecl = 0;
267 GetClassFunctionDecl = 0;
268 GetMetaClassFunctionDecl = 0;
269 SelGetUidFunctionDecl = 0;
270 CFStringFunctionDecl = 0;
271 GetProtocolFunctionDecl = 0;
272 ConstantStringClassReference = 0;
273 NSStringRecord = 0;
274 CurMethodDecl = 0;
275 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000276 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000277 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000278 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000279 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000280
281 // Get the ID and start/end of the main file.
282 MainFileID = SM->getMainFileID();
283 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
284 MainFileStart = MainBuf->getBufferStart();
285 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000286
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000287 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000288
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000289 // declaring objc_selector outside the parameter list removes a silly
290 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000291 if (IsHeader)
292 Preamble = "#pragma once\n";
293 Preamble += "struct objc_selector; struct objc_class;\n";
294 Preamble += "#ifndef OBJC_SUPER\n";
295 Preamble += "struct objc_super { struct objc_object *object; ";
296 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000297 if (LangOpts.Microsoft) {
298 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000299 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
300 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000301 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000302 Preamble += "};\n";
303 Preamble += "#define OBJC_SUPER\n";
304 Preamble += "#endif\n";
305 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
306 Preamble += "typedef struct objc_object Protocol;\n";
307 Preamble += "#define _REWRITER_typedef_Protocol\n";
308 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000309 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000310 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
311 else
312 Preamble += "#define __OBJC_RW_EXTERN extern\n";
313 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000314 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000315 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000316 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000317 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000318 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000319 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000320 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000321 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000322 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000323 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000324 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000325 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000326 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000327 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
328 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
329 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
330 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
331 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000332 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000333 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000334 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
335 Preamble += "struct __objcFastEnumerationState {\n\t";
336 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000337 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000338 Preamble += "unsigned long *mutationsPtr;\n\t";
339 Preamble += "unsigned long extra[5];\n};\n";
340 Preamble += "#define __FASTENUMERATIONSTATE\n";
341 Preamble += "#endif\n";
342 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
343 Preamble += "struct __NSConstantStringImpl {\n";
344 Preamble += " int *isa;\n";
345 Preamble += " int flags;\n";
346 Preamble += " char *str;\n";
347 Preamble += " long length;\n";
348 Preamble += "};\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000349 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000350 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
351 Preamble += "#endif\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000352 if (LangOpts.Microsoft) {
353 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000354 Preamble += "#define __attribute__(X)\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000355 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000356}
357
358
Chris Lattnerf04da132007-10-24 17:06:59 +0000359//===----------------------------------------------------------------------===//
360// Top Level Driver Code
361//===----------------------------------------------------------------------===//
362
Steve Naroffb29b4272008-04-14 22:03:09 +0000363void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000364 // Two cases: either the decl could be in the main file, or it could be in a
365 // #included file. If the former, rewrite it now. If the later, check to see
366 // if we rewrote the #include/#import.
367 SourceLocation Loc = D->getLocation();
368 Loc = SM->getLogicalLoc(Loc);
369
370 // If this is for a builtin, ignore it.
371 if (Loc.isInvalid()) return;
372
Steve Naroffebf2b562007-10-23 23:50:29 +0000373 // Look for built-in declarations that we need to refer during the rewrite.
374 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000375 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000376 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000377 // declared in <Foundation/NSString.h>
378 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
379 ConstantStringClassReference = FVD;
380 return;
381 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000382 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000383 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000384 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000385 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000386 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000387 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000388 } else if (ObjCForwardProtocolDecl *FP =
389 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000390 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000391 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000392 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000393 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000394 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000395}
396
Chris Lattnerf04da132007-10-24 17:06:59 +0000397/// HandleDeclInMainFile - This is called for each top-level decl defined in the
398/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000399void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000400 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
401 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000402 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000403
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000404 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000405 if (Stmt *Body = MD->getBody()) {
406 //Body->dump();
407 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000408 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000409 CurMethodDecl = 0;
410 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000411 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000412 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000413 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000414 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000415 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000416 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000417 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000418 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000419 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000420 if (VD->getInit())
421 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
422 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000423 // Nothing yet.
424}
425
Steve Naroffb29b4272008-04-14 22:03:09 +0000426RewriteObjC::~RewriteObjC() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000427 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000428
429 // Rewrite tabs if we care.
430 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000431
Steve Naroffa7b402d2008-03-28 22:26:09 +0000432 if (Diags.hasErrorOccurred())
433 return;
434
435 // Create the output file.
436
437 std::ostream *OutFile;
438 if (OutFileName == "-") {
439 OutFile = llvm::cout.stream();
440 } else if (!OutFileName.empty()) {
441 OutFile = new std::ofstream(OutFileName.c_str(),
442 std::ios_base::binary|std::ios_base::out);
443 } else if (InFileName == "-") {
444 OutFile = llvm::cout.stream();
445 } else {
446 llvm::sys::Path Path(InFileName);
447 Path.eraseSuffix();
448 Path.appendSuffix("cpp");
449 OutFile = new std::ofstream(Path.toString().c_str(),
450 std::ios_base::binary|std::ios_base::out);
451 }
452
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000453 RewriteInclude();
454
Steve Naroffba92b2e2008-03-27 22:29:16 +0000455 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
456 Preamble.c_str(), Preamble.size(), false);
457
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000458 // Rewrite Objective-c meta data*
459 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000460 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000461
Chris Lattnerf04da132007-10-24 17:06:59 +0000462 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
463 // we are done.
464 if (const RewriteBuffer *RewriteBuf =
465 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000466 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000467 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000468 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000469 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000470 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000471 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000472 *OutFile << ResultStr;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000473}
474
Chris Lattnerf04da132007-10-24 17:06:59 +0000475//===----------------------------------------------------------------------===//
476// Syntactic (non-AST) Rewriting Code
477//===----------------------------------------------------------------------===//
478
Steve Naroffb29b4272008-04-14 22:03:09 +0000479void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000480 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
481 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
482 const char *MainBufStart = MainBuf.first;
483 const char *MainBufEnd = MainBuf.second;
484 size_t ImportLen = strlen("import");
485 size_t IncludeLen = strlen("include");
486
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000487 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000488 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
489 if (*BufPtr == '#') {
490 if (++BufPtr == MainBufEnd)
491 return;
492 while (*BufPtr == ' ' || *BufPtr == '\t')
493 if (++BufPtr == MainBufEnd)
494 return;
495 if (!strncmp(BufPtr, "import", ImportLen)) {
496 // replace import with include
497 SourceLocation ImportLoc =
498 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000499 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000500 BufPtr += ImportLen;
501 }
502 }
503 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000504}
505
Steve Naroffb29b4272008-04-14 22:03:09 +0000506void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000507 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
508 const char *MainBufStart = MainBuf.first;
509 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000510
Chris Lattnerf04da132007-10-24 17:06:59 +0000511 // Loop over the whole file, looking for tabs.
512 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
513 if (*BufPtr != '\t')
514 continue;
515
516 // Okay, we found a tab. This tab will turn into at least one character,
517 // but it depends on which 'virtual column' it is in. Compute that now.
518 unsigned VCol = 0;
519 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
520 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
521 ++VCol;
522
523 // Okay, now that we know the virtual column, we know how many spaces to
524 // insert. We assume 8-character tab-stops.
525 unsigned Spaces = 8-(VCol & 7);
526
527 // Get the location of the tab.
528 SourceLocation TabLoc =
529 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
530
531 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000532 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000533 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000534}
535
536
Steve Naroffb29b4272008-04-14 22:03:09 +0000537void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000538 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000539 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000540
541 // Get the start location and compute the semi location.
542 SourceLocation startLoc = ClassDecl->getLocation();
543 const char *startBuf = SM->getCharacterData(startLoc);
544 const char *semiPtr = strchr(startBuf, ';');
545
546 // Translate to typedef's that forward reference structs with the same name
547 // as the class. As a convenience, we include the original declaration
548 // as a comment.
549 std::string typedefString;
550 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000551 typedefString.append(startBuf, semiPtr-startBuf+1);
552 typedefString += "\n";
553 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000554 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000555 typedefString += "#ifndef _REWRITER_typedef_";
556 typedefString += ForwardDecl->getName();
557 typedefString += "\n";
558 typedefString += "#define _REWRITER_typedef_";
559 typedefString += ForwardDecl->getName();
560 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000561 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000562 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000563 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000564 }
565
566 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000567 ReplaceText(startLoc, semiPtr-startBuf+1,
568 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000569}
570
Steve Naroffb29b4272008-04-14 22:03:09 +0000571void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000572 SourceLocation LocStart = Method->getLocStart();
573 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000574
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000575 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000576 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000577 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000578 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000579 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000580 }
581}
582
Steve Naroffb29b4272008-04-14 22:03:09 +0000583void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000584{
Chris Lattner55d13b42008-03-16 21:23:50 +0000585 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000586 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000587 SourceLocation Loc = Property->getLocation();
588
Chris Lattneraadaf782008-01-31 19:51:04 +0000589 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000590
591 // FIXME: handle properties that are declared across multiple lines.
592 }
593}
594
Steve Naroffb29b4272008-04-14 22:03:09 +0000595void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000596 SourceLocation LocStart = CatDecl->getLocStart();
597
598 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000599 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000600
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000601 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000602 E = CatDecl->instmeth_end(); I != E; ++I)
603 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000604 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000605 E = CatDecl->classmeth_end(); I != E; ++I)
606 RewriteMethodDeclaration(*I);
607
Steve Naroff423cb562007-10-30 13:30:57 +0000608 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000609 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000610}
611
Steve Naroffb29b4272008-04-14 22:03:09 +0000612void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000613 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000614
Steve Naroff752d6ef2007-10-30 16:42:30 +0000615 SourceLocation LocStart = PDecl->getLocStart();
616
617 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000618 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000619
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000620 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000621 E = PDecl->instmeth_end(); I != E; ++I)
622 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000623 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000624 E = PDecl->classmeth_end(); I != E; ++I)
625 RewriteMethodDeclaration(*I);
626
Steve Naroff752d6ef2007-10-30 16:42:30 +0000627 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000628 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000629 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000630
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000631 // Must comment out @optional/@required
632 const char *startBuf = SM->getCharacterData(LocStart);
633 const char *endBuf = SM->getCharacterData(LocEnd);
634 for (const char *p = startBuf; p < endBuf; p++) {
635 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
636 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000637 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000638 ReplaceText(OptionalLoc, strlen("@optional"),
639 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000640
641 }
642 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
643 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000644 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000645 ReplaceText(OptionalLoc, strlen("@required"),
646 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000647
648 }
649 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000650}
651
Steve Naroffb29b4272008-04-14 22:03:09 +0000652void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000653 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000654 if (LocStart.isInvalid())
655 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000656 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000657 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000658}
659
Steve Naroffb29b4272008-04-14 22:03:09 +0000660void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000661 std::string &ResultStr) {
662 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000663 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000664 ResultStr += "id";
665 else
666 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000667 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000668
669 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000670 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000671
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000672 if (OMD->isInstance())
673 NameStr += "_I_";
674 else
675 NameStr += "_C_";
676
677 NameStr += OMD->getClassInterface()->getName();
678 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000679
680 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000681 if (ObjCCategoryImplDecl *CID =
682 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000683 NameStr += CID->getName();
684 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000685 }
Steve Naroff563b8282008-04-04 22:23:44 +0000686 // Append selector names, replacing ':' with '_'
687 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000688 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000689 else {
690 std::string selString = OMD->getSelector().getName();
691 int len = selString.size();
692 for (int i = 0; i < len; i++)
693 if (selString[i] == ':')
694 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000695 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000696 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000697 // Remember this name for metadata emission
698 MethodInternalNames[OMD] = NameStr;
699 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000700
701 // Rewrite arguments
702 ResultStr += "(";
703
704 // invisible arguments
705 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000706 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000707 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000708 if (!LangOpts.Microsoft) {
709 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
710 ResultStr += "struct ";
711 }
712 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000713 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000714 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000715 }
716 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000717 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000718
719 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000720 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000721 ResultStr += " _cmd";
722
723 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000724 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000725 ParmVarDecl *PDecl = OMD->getParamDecl(i);
726 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000727 if (PDecl->getType()->isObjCQualifiedIdType()) {
728 ResultStr += "id ";
729 ResultStr += PDecl->getName();
730 } else {
731 std::string Name = PDecl->getName();
732 PDecl->getType().getAsStringInternal(Name);
733 ResultStr += Name;
734 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000735 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000736 if (OMD->isVariadic())
737 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000738 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000739
740}
Steve Naroffb29b4272008-04-14 22:03:09 +0000741void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000742 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
743 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000744
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000745 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000746 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000747 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000748 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000749
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000750 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000751 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
752 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000753 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000754 ObjCMethodDecl *OMD = *I;
755 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000756 SourceLocation LocStart = OMD->getLocStart();
757 SourceLocation LocEnd = OMD->getBody()->getLocStart();
758
759 const char *startBuf = SM->getCharacterData(LocStart);
760 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000761 ReplaceText(LocStart, endBuf-startBuf,
762 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000763 }
764
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000765 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000766 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
767 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000768 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000769 ObjCMethodDecl *OMD = *I;
770 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000771 SourceLocation LocStart = OMD->getLocStart();
772 SourceLocation LocEnd = OMD->getBody()->getLocStart();
773
774 const char *startBuf = SM->getCharacterData(LocStart);
775 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000776 ReplaceText(LocStart, endBuf-startBuf,
777 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000778 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000779 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000780 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000781 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000782 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000783}
784
Steve Naroffb29b4272008-04-14 22:03:09 +0000785void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000786 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000787 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000788 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000789 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000790 ResultStr += ClassDecl->getName();
791 ResultStr += "\n";
792 ResultStr += "#define _REWRITER_typedef_";
793 ResultStr += ClassDecl->getName();
794 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000795 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000796 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000797 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000798 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000799 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000800 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000801 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000802
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000803 RewriteProperties(ClassDecl->getNumPropertyDecl(),
804 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000805 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000806 E = ClassDecl->instmeth_end(); I != E; ++I)
807 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000808 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000809 E = ClassDecl->classmeth_end(); I != E; ++I)
810 RewriteMethodDeclaration(*I);
811
Steve Naroff2feac5e2007-10-30 03:43:13 +0000812 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000813 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000814}
815
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000816Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
817 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000818 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000819 if (CurMethodDecl) {
820 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000821 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
822 // lookup which class implements the instance variable.
823 ObjCInterfaceDecl *clsDeclared = 0;
824 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
825 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
826
827 // Synthesize an explicit cast to gain access to the ivar.
828 std::string RecName = clsDeclared->getIdentifier()->getName();
829 RecName += "_IMPL";
830 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
831 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
832 SourceLocation(), II, 0);
833 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
834 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
835 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
836 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000837 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
838 IV->getBase()->getLocEnd(),
839 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000840 if (IV->isFreeIvar() &&
841 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000842 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
843 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000844 ReplaceStmt(IV, ME);
845 delete IV;
846 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000847 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000848
849 ReplaceStmt(IV->getBase(), PE);
850 // Cannot delete IV->getBase(), since PE points to it.
851 // Replace the old base with the cast. This is important when doing
852 // embedded rewrites. For example, [newInv->_container addObject:0].
853 IV->setBase(PE);
854 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000855 }
Steve Naroff84472a82008-04-18 21:55:08 +0000856 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000857 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
858
859 // Explicit ivar refs need to have a cast inserted.
860 // FIXME: consider sharing some of this code with the code above.
861 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000862 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000863 // lookup which class implements the instance variable.
864 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000865 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000866 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
867
868 // Synthesize an explicit cast to gain access to the ivar.
869 std::string RecName = clsDeclared->getIdentifier()->getName();
870 RecName += "_IMPL";
871 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
872 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
873 SourceLocation(), II, 0);
874 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
875 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
876 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
877 // Don't forget the parens to enforce the proper binding.
878 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
879 ReplaceStmt(IV->getBase(), PE);
880 // Cannot delete IV->getBase(), since PE points to it.
881 // Replace the old base with the cast. This is important when doing
882 // embedded rewrites. For example, [newInv->_container addObject:0].
883 IV->setBase(PE);
884 return IV;
885 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000886 }
Steve Naroff84472a82008-04-18 21:55:08 +0000887 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000888}
889
Chris Lattnerf04da132007-10-24 17:06:59 +0000890//===----------------------------------------------------------------------===//
891// Function Body / Expression rewriting
892//===----------------------------------------------------------------------===//
893
Steve Naroffb29b4272008-04-14 22:03:09 +0000894Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000895 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
896 isa<DoStmt>(S) || isa<ForStmt>(S))
897 Stmts.push_back(S);
898 else if (isa<ObjCForCollectionStmt>(S)) {
899 Stmts.push_back(S);
900 ObjCBcLabelNo.push_back(++BcLabelCount);
901 }
902
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000903 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner338d1e22008-01-31 05:10:40 +0000904
905 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000906 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
907 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000908 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000909 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000910 if (newStmt)
911 *CI = newStmt;
912 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000913
914 // Handle specific things.
915 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
916 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000917
918 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000919 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroffb42f8412007-11-05 14:50:49 +0000920
921 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
922 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000923
Steve Naroffbeaf2992007-11-03 11:27:19 +0000924 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
925 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000926
Steve Naroff934f2762007-10-24 22:48:43 +0000927 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
928 // Before we rewrite it, put the original message expression in a comment.
929 SourceLocation startLoc = MessExpr->getLocStart();
930 SourceLocation endLoc = MessExpr->getLocEnd();
931
932 const char *startBuf = SM->getCharacterData(startLoc);
933 const char *endBuf = SM->getCharacterData(endLoc);
934
935 std::string messString;
936 messString += "// ";
937 messString.append(startBuf, endBuf-startBuf+1);
938 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000939
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000940 // FIXME: Missing definition of
941 // InsertText(clang::SourceLocation, char const*, unsigned int).
942 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000943 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000944 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000945 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000946 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000947
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000948 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
949 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000950
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000951 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
952 return RewriteObjCSynchronizedStmt(StmtTry);
953
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000954 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
955 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000956
957 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
958 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000959
960 if (ObjCForCollectionStmt *StmtForCollection =
961 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000962 return RewriteObjCForCollectionStmt(StmtForCollection,
963 OrigStmtRange.getEnd());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000964 if (BreakStmt *StmtBreakStmt =
965 dyn_cast<BreakStmt>(S))
966 return RewriteBreakStmt(StmtBreakStmt);
967 if (ContinueStmt *StmtContinueStmt =
968 dyn_cast<ContinueStmt>(S))
969 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000970
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000971 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
972 isa<DoStmt>(S) || isa<ForStmt>(S)) {
973 assert(!Stmts.empty() && "Statement stack is empty");
974 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
975 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
976 && "Statement stack mismatch");
977 Stmts.pop_back();
978 }
Steve Naroff874e2322007-11-15 10:28:18 +0000979#if 0
980 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
981 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
982 // Get the new text.
983 std::ostringstream Buf;
984 Replacement->printPretty(Buf);
985 const std::string &Str = Buf.str();
986
987 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000988 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000989 delete S;
990 return Replacement;
991 }
992#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000993 // Return this stmt unmodified.
994 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000995}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000996
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000997/// SynthCountByEnumWithState - To print:
998/// ((unsigned int (*)
999/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1000/// (void *)objc_msgSend)((id)l_collection,
1001/// sel_registerName(
1002/// "countByEnumeratingWithState:objects:count:"),
1003/// &enumState,
1004/// (id *)items, (unsigned int)16)
1005///
Steve Naroffb29b4272008-04-14 22:03:09 +00001006void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001007 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1008 "id *, unsigned int))(void *)objc_msgSend)";
1009 buf += "\n\t\t";
1010 buf += "((id)l_collection,\n\t\t";
1011 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1012 buf += "\n\t\t";
1013 buf += "&enumState, "
1014 "(id *)items, (unsigned int)16)";
1015}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001016
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001017/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1018/// statement to exit to its outer synthesized loop.
1019///
Steve Naroffb29b4272008-04-14 22:03:09 +00001020Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001021 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1022 return S;
1023 // replace break with goto __break_label
1024 std::string buf;
1025
1026 SourceLocation startLoc = S->getLocStart();
1027 buf = "goto __break_label_";
1028 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001029 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001030
1031 return 0;
1032}
1033
1034/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1035/// statement to continue with its inner synthesized loop.
1036///
Steve Naroffb29b4272008-04-14 22:03:09 +00001037Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001038 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1039 return S;
1040 // replace continue with goto __continue_label
1041 std::string buf;
1042
1043 SourceLocation startLoc = S->getLocStart();
1044 buf = "goto __continue_label_";
1045 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001046 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001047
1048 return 0;
1049}
1050
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001051/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001052/// It rewrites:
1053/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001054
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001055/// Into:
1056/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001057/// type elem;
1058/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001059/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001060/// id l_collection = (id)collection;
1061/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1062/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001063/// if (limit) {
1064/// unsigned long startMutations = *enumState.mutationsPtr;
1065/// do {
1066/// unsigned long counter = 0;
1067/// do {
1068/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001069/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001070/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001071/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001072/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001073/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001074/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1075/// objects:items count:16]);
1076/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001077/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001078/// }
1079/// else
1080/// elem = nil;
1081/// }
1082///
Steve Naroffb29b4272008-04-14 22:03:09 +00001083Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001084 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001085 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1086 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1087 "ObjCForCollectionStmt Statement stack mismatch");
1088 assert(!ObjCBcLabelNo.empty() &&
1089 "ObjCForCollectionStmt - Label No stack empty");
1090
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001091 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001092 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001093 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001094 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001095 std::string buf;
1096 buf = "\n{\n\t";
1097 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1098 // type elem;
1099 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001100 elementTypeAsString = ElementType.getAsString();
1101 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001102 buf += " ";
1103 elementName = DS->getDecl()->getName();
1104 buf += elementName;
1105 buf += ";\n\t";
1106 }
Chris Lattner06767512008-04-08 05:52:18 +00001107 else {
1108 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001109 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001110 elementTypeAsString = DR->getDecl()->getType().getAsString();
1111 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001112
1113 // struct __objcFastEnumerationState enumState = { 0 };
1114 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1115 // id items[16];
1116 buf += "id items[16];\n\t";
1117 // id l_collection = (id)
1118 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001119 // Find start location of 'collection' the hard way!
1120 const char *startCollectionBuf = startBuf;
1121 startCollectionBuf += 3; // skip 'for'
1122 startCollectionBuf = strchr(startCollectionBuf, '(');
1123 startCollectionBuf++; // skip '('
1124 // find 'in' and skip it.
1125 while (*startCollectionBuf != ' ' ||
1126 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1127 (*(startCollectionBuf+3) != ' ' &&
1128 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1129 startCollectionBuf++;
1130 startCollectionBuf += 3;
1131
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001132 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001133 ReplaceText(startLoc, startCollectionBuf - startBuf,
1134 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001135 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001136 SourceLocation rightParenLoc = S->getRParenLoc();
1137 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1138 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001139 buf = ";\n\t";
1140
1141 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1142 // objects:items count:16];
1143 // which is synthesized into:
1144 // unsigned int limit =
1145 // ((unsigned int (*)
1146 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1147 // (void *)objc_msgSend)((id)l_collection,
1148 // sel_registerName(
1149 // "countByEnumeratingWithState:objects:count:"),
1150 // (struct __objcFastEnumerationState *)&state,
1151 // (id *)items, (unsigned int)16);
1152 buf += "unsigned long limit =\n\t\t";
1153 SynthCountByEnumWithState(buf);
1154 buf += ";\n\t";
1155 /// if (limit) {
1156 /// unsigned long startMutations = *enumState.mutationsPtr;
1157 /// do {
1158 /// unsigned long counter = 0;
1159 /// do {
1160 /// if (startMutations != *enumState.mutationsPtr)
1161 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001162 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001163 buf += "if (limit) {\n\t";
1164 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1165 buf += "do {\n\t\t";
1166 buf += "unsigned long counter = 0;\n\t\t";
1167 buf += "do {\n\t\t\t";
1168 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1169 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1170 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001171 buf += " = (";
1172 buf += elementTypeAsString;
1173 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001174 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001175 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001176
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001177 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001178 /// } while (counter < limit);
1179 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1180 /// objects:items count:16]);
1181 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001182 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001183 /// }
1184 /// else
1185 /// elem = nil;
1186 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001187 ///
1188 buf = ";\n\t";
1189 buf += "__continue_label_";
1190 buf += utostr(ObjCBcLabelNo.back());
1191 buf += ": ;";
1192 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001193 buf += "} while (counter < limit);\n\t";
1194 buf += "} while (limit = ";
1195 SynthCountByEnumWithState(buf);
1196 buf += ");\n\t";
1197 buf += elementName;
1198 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001199 buf += "__break_label_";
1200 buf += utostr(ObjCBcLabelNo.back());
1201 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001202 buf += "}\n\t";
1203 buf += "else\n\t\t";
1204 buf += elementName;
1205 buf += " = nil;\n";
1206 buf += "}\n";
1207 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001208 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001209 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001210 Stmts.pop_back();
1211 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001212 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001213}
1214
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001215/// RewriteObjCSynchronizedStmt -
1216/// This routine rewrites @synchronized(expr) stmt;
1217/// into:
1218/// objc_sync_enter(expr);
1219/// @try stmt @finally { objc_sync_exit(expr); }
1220///
Steve Naroffb29b4272008-04-14 22:03:09 +00001221Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001222 // Get the start location and compute the semi location.
1223 SourceLocation startLoc = S->getLocStart();
1224 const char *startBuf = SM->getCharacterData(startLoc);
1225
1226 assert((*startBuf == '@') && "bogus @synchronized location");
1227
1228 std::string buf;
1229 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001230 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001231 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1232 const char *endBuf = SM->getCharacterData(endLoc);
1233 endBuf++;
1234 const char *rparenBuf = strchr(endBuf, ')');
1235 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1236 buf = ");\n";
1237 // declare a new scope with two variables, _stack and _rethrow.
1238 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1239 buf += "int buf[18/*32-bit i386*/];\n";
1240 buf += "char *pointers[4];} _stack;\n";
1241 buf += "id volatile _rethrow = 0;\n";
1242 buf += "objc_exception_try_enter(&_stack);\n";
1243 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001244 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001245 startLoc = S->getSynchBody()->getLocEnd();
1246 startBuf = SM->getCharacterData(startLoc);
1247
1248 assert((*startBuf == '}') && "bogus @try block");
1249 SourceLocation lastCurlyLoc = startLoc;
1250 buf = "}\nelse {\n";
1251 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1252 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1253 // FIXME: This must be objc_sync_exit(syncExpr);
1254 buf += " objc_sync_exit();\n";
1255 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1256 buf += "}\n";
1257 buf += "}";
1258
Chris Lattneraadaf782008-01-31 19:51:04 +00001259 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001260 return 0;
1261}
1262
Steve Naroffb29b4272008-04-14 22:03:09 +00001263Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001264 // Get the start location and compute the semi location.
1265 SourceLocation startLoc = S->getLocStart();
1266 const char *startBuf = SM->getCharacterData(startLoc);
1267
1268 assert((*startBuf == '@') && "bogus @try location");
1269
1270 std::string buf;
1271 // declare a new scope with two variables, _stack and _rethrow.
1272 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1273 buf += "int buf[18/*32-bit i386*/];\n";
1274 buf += "char *pointers[4];} _stack;\n";
1275 buf += "id volatile _rethrow = 0;\n";
1276 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001277 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001278
Chris Lattneraadaf782008-01-31 19:51:04 +00001279 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001280
1281 startLoc = S->getTryBody()->getLocEnd();
1282 startBuf = SM->getCharacterData(startLoc);
1283
1284 assert((*startBuf == '}') && "bogus @try block");
1285
1286 SourceLocation lastCurlyLoc = startLoc;
1287
1288 startLoc = startLoc.getFileLocWithOffset(1);
1289 buf = " /* @catch begin */ else {\n";
1290 buf += " id _caught = objc_exception_extract(&_stack);\n";
1291 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001292 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001293 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1294 buf += " else { /* @catch continue */";
1295
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001296 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001297
1298 bool sawIdTypedCatch = false;
1299 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001300 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001301 while (catchList) {
1302 Stmt *catchStmt = catchList->getCatchParamStmt();
1303
1304 if (catchList == S->getCatchStmts())
1305 buf = "if ("; // we are generating code for the first catch clause
1306 else
1307 buf = "else if (";
1308 startLoc = catchList->getLocStart();
1309 startBuf = SM->getCharacterData(startLoc);
1310
1311 assert((*startBuf == '@') && "bogus @catch location");
1312
1313 const char *lParenLoc = strchr(startBuf, '(');
1314
Steve Naroffbe4b3332008-02-01 22:08:12 +00001315 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001316 // Now rewrite the body...
1317 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001318 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1319 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001320 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1321 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001322 assert((*bodyBuf == '{') && "bogus @catch body location");
1323
1324 buf += "1) { id _tmp = _caught;";
1325 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1326 buf.c_str(), buf.size());
1327 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001328 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001329 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001330 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001331 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001332 sawIdTypedCatch = true;
1333 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001334 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001335
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001336 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001337 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001338 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001339 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001340 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001341 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001342 }
1343 }
1344 // Now rewrite the body...
1345 lastCatchBody = catchList->getCatchBody();
1346 SourceLocation rParenLoc = catchList->getRParenLoc();
1347 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1348 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1349 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1350 assert((*rParenBuf == ')') && "bogus @catch paren location");
1351 assert((*bodyBuf == '{') && "bogus @catch body location");
1352
1353 buf = " = _caught;";
1354 // Here we replace ") {" with "= _caught;" (which initializes and
1355 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001356 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001357 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001358 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001359 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001360 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001361 catchList = catchList->getNextCatchStmt();
1362 }
1363 // Complete the catch list...
1364 if (lastCatchBody) {
1365 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001366 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1367 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001368 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1369 buf = " } } /* @catch end */\n";
1370
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001371 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001372
1373 // Set lastCurlyLoc
1374 lastCurlyLoc = lastCatchBody->getLocEnd();
1375 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001376 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001377 startLoc = finalStmt->getLocStart();
1378 startBuf = SM->getCharacterData(startLoc);
1379 assert((*startBuf == '@') && "bogus @finally start");
1380
1381 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001382 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001383
1384 Stmt *body = finalStmt->getFinallyBody();
1385 SourceLocation startLoc = body->getLocStart();
1386 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001387 assert(*SM->getCharacterData(startLoc) == '{' &&
1388 "bogus @finally body location");
1389 assert(*SM->getCharacterData(endLoc) == '}' &&
1390 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001391
1392 startLoc = startLoc.getFileLocWithOffset(1);
1393 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001394 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001395 endLoc = endLoc.getFileLocWithOffset(-1);
1396 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001397 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001398
1399 // Set lastCurlyLoc
1400 lastCurlyLoc = body->getLocEnd();
1401 }
1402 // Now emit the final closing curly brace...
1403 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1404 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001405 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001406 return 0;
1407}
1408
Steve Naroffb29b4272008-04-14 22:03:09 +00001409Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001410 return 0;
1411}
1412
Steve Naroffb29b4272008-04-14 22:03:09 +00001413Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001414 return 0;
1415}
1416
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001417// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001418// the throw expression is typically a message expression that's already
1419// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001420Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001421 // Get the start location and compute the semi location.
1422 SourceLocation startLoc = S->getLocStart();
1423 const char *startBuf = SM->getCharacterData(startLoc);
1424
1425 assert((*startBuf == '@') && "bogus @throw location");
1426
1427 std::string buf;
1428 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001429 if (S->getThrowExpr())
1430 buf = "objc_exception_throw(";
1431 else // add an implicit argument
1432 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001433 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001434 const char *semiBuf = strchr(startBuf, ';');
1435 assert((*semiBuf == ';') && "@throw: can't find ';'");
1436 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1437 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001438 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001439 return 0;
1440}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001441
Steve Naroffb29b4272008-04-14 22:03:09 +00001442Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001443 // Create a new string expression.
1444 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001445 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001446 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1447 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001448 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1449 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001450 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001451 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001452
Chris Lattner07506182007-11-30 22:53:43 +00001453 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001454 delete Exp;
1455 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001456}
1457
Steve Naroffb29b4272008-04-14 22:03:09 +00001458Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001459 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1460 // Create a call to sel_registerName("selName").
1461 llvm::SmallVector<Expr*, 8> SelExprs;
1462 QualType argType = Context->getPointerType(Context->CharTy);
1463 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1464 Exp->getSelector().getName().size(),
1465 false, argType, SourceLocation(),
1466 SourceLocation()));
1467 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1468 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001469 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001470 delete Exp;
1471 return SelExp;
1472}
1473
Steve Naroffb29b4272008-04-14 22:03:09 +00001474CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001475 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001476 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001477 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001478
1479 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001480 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001481
1482 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001483 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001484 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1485
1486 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001487
Steve Naroff934f2762007-10-24 22:48:43 +00001488 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1489}
1490
Steve Naroffd5255f52007-11-01 13:24:47 +00001491static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1492 const char *&startRef, const char *&endRef) {
1493 while (startBuf < endBuf) {
1494 if (*startBuf == '<')
1495 startRef = startBuf; // mark the start.
1496 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001497 if (startRef && *startRef == '<') {
1498 endRef = startBuf; // mark the end.
1499 return true;
1500 }
1501 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001502 }
1503 startBuf++;
1504 }
1505 return false;
1506}
1507
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001508static void scanToNextArgument(const char *&argRef) {
1509 int angle = 0;
1510 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1511 if (*argRef == '<')
1512 angle++;
1513 else if (*argRef == '>')
1514 angle--;
1515 argRef++;
1516 }
1517 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1518}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001519
Steve Naroffb29b4272008-04-14 22:03:09 +00001520bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001521
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001522 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001523 return true;
1524
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001525 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001526 return true;
1527
Steve Naroffd5255f52007-11-01 13:24:47 +00001528 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001529 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001530 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001531 return true; // we have "Class <Protocol> *".
1532 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001533 return false;
1534}
1535
Steve Naroffb29b4272008-04-14 22:03:09 +00001536void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001537 SourceLocation Loc;
1538 QualType Type;
1539 const FunctionTypeProto *proto = 0;
1540 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1541 Loc = VD->getLocation();
1542 Type = VD->getType();
1543 }
1544 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1545 Loc = FD->getLocation();
1546 // Check for ObjC 'id' and class types that have been adorned with protocol
1547 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1548 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1549 assert(funcType && "missing function type");
1550 proto = dyn_cast<FunctionTypeProto>(funcType);
1551 if (!proto)
1552 return;
1553 Type = proto->getResultType();
1554 }
1555 else
1556 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001557
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001558 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001559 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001560
1561 const char *endBuf = SM->getCharacterData(Loc);
1562 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001563 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001564 startBuf--; // scan backward (from the decl location) for return type.
1565 const char *startRef = 0, *endRef = 0;
1566 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1567 // Get the locations of the startRef, endRef.
1568 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1569 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1570 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001571 InsertText(LessLoc, "/*", 2);
1572 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001573 }
1574 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001575 if (!proto)
1576 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001577 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001578 const char *startBuf = SM->getCharacterData(Loc);
1579 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001580 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1581 if (needToScanForQualifiers(proto->getArgType(i))) {
1582 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001583
Steve Naroffd5255f52007-11-01 13:24:47 +00001584 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001585 // scan forward (from the decl location) for argument types.
1586 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001587 const char *startRef = 0, *endRef = 0;
1588 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1589 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001590 SourceLocation LessLoc =
1591 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1592 SourceLocation GreaterLoc =
1593 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001594 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001595 InsertText(LessLoc, "/*", 2);
1596 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001597 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001598 startBuf = ++endBuf;
1599 }
1600 else {
1601 while (*startBuf != ')' && *startBuf != ',')
1602 startBuf++; // scan forward (from the decl location) for argument types.
1603 startBuf++;
1604 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001605 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001606}
1607
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001608// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001609void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001610 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1611 llvm::SmallVector<QualType, 16> ArgTys;
1612 ArgTys.push_back(Context->getPointerType(
1613 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001614 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001615 &ArgTys[0], ArgTys.size(),
1616 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001617 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001618 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001619 SelGetUidIdent, getFuncType,
1620 FunctionDecl::Extern, false, 0);
1621}
1622
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001623// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001624void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001625 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1626 llvm::SmallVector<QualType, 16> ArgTys;
1627 ArgTys.push_back(Context->getPointerType(
1628 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001629 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001630 &ArgTys[0], ArgTys.size(),
1631 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001632 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001633 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001634 SelGetProtoIdent, getFuncType,
1635 FunctionDecl::Extern, false, 0);
1636}
1637
Steve Naroffb29b4272008-04-14 22:03:09 +00001638void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001639 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001640 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001641 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001642 return;
1643 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001644 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001645}
1646
Steve Naroffc0a123c2008-03-11 17:37:02 +00001647// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001648void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001649 if (SuperContructorFunctionDecl)
1650 return;
1651 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1652 llvm::SmallVector<QualType, 16> ArgTys;
1653 QualType argT = Context->getObjCIdType();
1654 assert(!argT.isNull() && "Can't find 'id' type");
1655 ArgTys.push_back(argT);
1656 ArgTys.push_back(argT);
1657 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1658 &ArgTys[0], ArgTys.size(),
1659 false);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001660 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001661 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001662 msgSendIdent, msgSendType,
1663 FunctionDecl::Extern, false, 0);
1664}
1665
Steve Naroff09b266e2007-10-30 23:14:51 +00001666// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001667void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001668 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1669 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001670 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001671 assert(!argT.isNull() && "Can't find 'id' type");
1672 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001673 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001674 assert(!argT.isNull() && "Can't find 'SEL' type");
1675 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001676 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001677 &ArgTys[0], ArgTys.size(),
1678 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001679 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001680 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001681 msgSendIdent, msgSendType,
1682 FunctionDecl::Extern, false, 0);
1683}
1684
Steve Naroff874e2322007-11-15 10:28:18 +00001685// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001686void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001687 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1688 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001689 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001690 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001691 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001692 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1693 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1694 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001695 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001696 assert(!argT.isNull() && "Can't find 'SEL' type");
1697 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001698 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001699 &ArgTys[0], ArgTys.size(),
1700 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001701 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001702 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001703 msgSendIdent, msgSendType,
1704 FunctionDecl::Extern, false, 0);
1705}
1706
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001707// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001708void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001709 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1710 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001711 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001712 assert(!argT.isNull() && "Can't find 'id' type");
1713 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001714 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001715 assert(!argT.isNull() && "Can't find 'SEL' type");
1716 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001717 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001718 &ArgTys[0], ArgTys.size(),
1719 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001720 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001721 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001722 msgSendIdent, msgSendType,
1723 FunctionDecl::Extern, false, 0);
1724}
1725
1726// SynthMsgSendSuperStretFunctionDecl -
1727// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001728void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001729 IdentifierInfo *msgSendIdent =
1730 &Context->Idents.get("objc_msgSendSuper_stret");
1731 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001732 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001733 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001734 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001735 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1736 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1737 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001738 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +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(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001742 &ArgTys[0], ArgTys.size(),
1743 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001744 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001745 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001746 msgSendIdent, msgSendType,
1747 FunctionDecl::Extern, false, 0);
1748}
1749
Steve Naroff1284db82008-05-08 22:02:18 +00001750// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001751void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001752 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1753 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001754 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001755 assert(!argT.isNull() && "Can't find 'id' type");
1756 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001757 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001758 assert(!argT.isNull() && "Can't find 'SEL' type");
1759 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001760 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001761 &ArgTys[0], ArgTys.size(),
1762 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001763 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001764 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001765 msgSendIdent, msgSendType,
1766 FunctionDecl::Extern, false, 0);
1767}
1768
Steve Naroff09b266e2007-10-30 23:14:51 +00001769// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001770void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001771 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1772 llvm::SmallVector<QualType, 16> ArgTys;
1773 ArgTys.push_back(Context->getPointerType(
1774 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001775 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001776 &ArgTys[0], ArgTys.size(),
1777 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001778 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001779 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001780 getClassIdent, getClassType,
1781 FunctionDecl::Extern, false, 0);
1782}
1783
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001784// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001785void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001786 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1787 llvm::SmallVector<QualType, 16> ArgTys;
1788 ArgTys.push_back(Context->getPointerType(
1789 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001790 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001791 &ArgTys[0], ArgTys.size(),
1792 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001793 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001794 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001795 getClassIdent, getClassType,
1796 FunctionDecl::Extern, false, 0);
1797}
1798
Steve Naroffb29b4272008-04-14 22:03:09 +00001799Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001800 QualType strType = getConstantStringStructType();
1801
1802 std::string S = "__NSConstantStringImpl_";
1803 S += utostr(NumObjCStringLiterals++);
1804
Steve Naroffba92b2e2008-03-27 22:29:16 +00001805 Preamble += "static __NSConstantStringImpl " + S;
1806 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1807 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001808 // The pretty printer for StringLiteral handles escape characters properly.
1809 std::ostringstream prettyBuf;
1810 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001811 Preamble += prettyBuf.str();
1812 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001813 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001814 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001815
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001816 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001817 &Context->Idents.get(S.c_str()), strType,
1818 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001819 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1820 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1821 Context->getPointerType(DRE->getType()),
1822 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001823 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001824 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001825 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001826 delete Exp;
1827 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001828}
1829
Steve Naroffb29b4272008-04-14 22:03:09 +00001830ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001831 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001832 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1833
1834 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1835 if (!CE) return 0;
1836
1837 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1838 if (!DRE) return 0;
1839
1840 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1841 if (!PVD) return 0;
1842
1843 if (strcmp(PVD->getName(), "self") != 0)
1844 return 0;
1845
1846 // is this id<P1..> type?
1847 if (CE->getType()->isObjCQualifiedIdType())
1848 return 0;
1849 const PointerType *PT = CE->getType()->getAsPointerType();
1850 if (!PT) return 0;
1851
1852 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1853 if (!IT) return 0;
1854
1855 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1856 return 0;
1857
1858 return IT->getDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001859}
1860
1861// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001862QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001863 if (!SuperStructDecl) {
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001864 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001865 SourceLocation(),
1866 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001867 QualType FieldTypes[2];
1868
1869 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001870 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001871 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001872 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001873 // Create fields
1874 FieldDecl *FieldDecls[2];
1875
1876 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001877 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001878 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001879
1880 SuperStructDecl->defineBody(FieldDecls, 4);
1881 }
1882 return Context->getTagDeclType(SuperStructDecl);
1883}
1884
Steve Naroffb29b4272008-04-14 22:03:09 +00001885QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001886 if (!ConstantStringDecl) {
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001887 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001888 SourceLocation(),
1889 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001890 QualType FieldTypes[4];
1891
1892 // struct objc_object *receiver;
1893 FieldTypes[0] = Context->getObjCIdType();
1894 // int flags;
1895 FieldTypes[1] = Context->IntTy;
1896 // char *str;
1897 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1898 // long length;
1899 FieldTypes[3] = Context->LongTy;
1900 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001901 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001902
1903 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001904 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001905 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001906
1907 ConstantStringDecl->defineBody(FieldDecls, 4);
1908 }
1909 return Context->getTagDeclType(ConstantStringDecl);
1910}
1911
Steve Naroffb29b4272008-04-14 22:03:09 +00001912Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001913 if (!SelGetUidFunctionDecl)
1914 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001915 if (!MsgSendFunctionDecl)
1916 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001917 if (!MsgSendSuperFunctionDecl)
1918 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001919 if (!MsgSendStretFunctionDecl)
1920 SynthMsgSendStretFunctionDecl();
1921 if (!MsgSendSuperStretFunctionDecl)
1922 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001923 if (!MsgSendFpretFunctionDecl)
1924 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001925 if (!GetClassFunctionDecl)
1926 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001927 if (!GetMetaClassFunctionDecl)
1928 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001929
Steve Naroff874e2322007-11-15 10:28:18 +00001930 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001931 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1932 // May need to use objc_msgSend_stret() as well.
1933 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001934 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001935 QualType resultType = mDecl->getResultType();
1936 if (resultType.getCanonicalType()->isStructureType()
1937 || resultType.getCanonicalType()->isUnionType())
1938 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001939 else if (resultType.getCanonicalType()->isRealFloatingType())
1940 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001941 }
Steve Naroff874e2322007-11-15 10:28:18 +00001942
Steve Naroff934f2762007-10-24 22:48:43 +00001943 // Synthesize a call to objc_msgSend().
1944 llvm::SmallVector<Expr*, 8> MsgExprs;
1945 IdentifierInfo *clsName = Exp->getClassName();
1946
1947 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1948 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001949 if (!strcmp(clsName->getName(), "super")) {
1950 MsgSendFlavor = MsgSendSuperFunctionDecl;
1951 if (MsgSendStretFlavor)
1952 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1953 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1954
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001955 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001956 CurMethodDecl->getClassInterface()->getSuperClass();
1957
1958 llvm::SmallVector<Expr*, 4> InitExprs;
1959
1960 // set the receiver to self, the first argument to all methods.
1961 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001962 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001963 SourceLocation()));
1964 llvm::SmallVector<Expr*, 8> ClsExprs;
1965 QualType argType = Context->getPointerType(Context->CharTy);
1966 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1967 SuperDecl->getIdentifier()->getLength(),
1968 false, argType, SourceLocation(),
1969 SourceLocation()));
1970 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1971 &ClsExprs[0],
1972 ClsExprs.size());
1973 // To turn off a warning, type-cast to 'id'
1974 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001975 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001976 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1977 // struct objc_super
1978 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001979 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001980
Steve Naroff23f41272008-03-11 18:14:26 +00001981 if (LangOpts.Microsoft) {
1982 SynthSuperContructorFunctionDecl();
1983 // Simulate a contructor call...
1984 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1985 superType, SourceLocation());
1986 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1987 superType, SourceLocation());
1988 } else {
1989 // (struct objc_super) { <exprs from above> }
1990 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1991 &InitExprs[0], InitExprs.size(),
1992 SourceLocation());
1993 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1994 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001995 // struct objc_super *
1996 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1997 Context->getPointerType(SuperRep->getType()),
1998 SourceLocation());
1999 MsgExprs.push_back(Unop);
2000 } else {
2001 llvm::SmallVector<Expr*, 8> ClsExprs;
2002 QualType argType = Context->getPointerType(Context->CharTy);
2003 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2004 clsName->getLength(),
2005 false, argType, SourceLocation(),
2006 SourceLocation()));
2007 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2008 &ClsExprs[0],
2009 ClsExprs.size());
2010 MsgExprs.push_back(Cls);
2011 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002012 } else { // instance message.
2013 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002014
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002015 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002016 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002017 if (MsgSendStretFlavor)
2018 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002019 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2020
2021 llvm::SmallVector<Expr*, 4> InitExprs;
2022
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002023 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002024 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002025 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002026
2027 llvm::SmallVector<Expr*, 8> ClsExprs;
2028 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002029 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2030 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002031 false, argType, SourceLocation(),
2032 SourceLocation()));
2033 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002034 &ClsExprs[0],
2035 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002036 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002037 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002038 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002039 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002040 // struct objc_super
2041 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002042 Expr *SuperRep;
2043
2044 if (LangOpts.Microsoft) {
2045 SynthSuperContructorFunctionDecl();
2046 // Simulate a contructor call...
2047 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2048 superType, SourceLocation());
2049 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2050 superType, SourceLocation());
2051 } else {
2052 // (struct objc_super) { <exprs from above> }
2053 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2054 &InitExprs[0], InitExprs.size(),
2055 SourceLocation());
2056 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2057 }
Steve Naroff874e2322007-11-15 10:28:18 +00002058 // struct objc_super *
2059 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2060 Context->getPointerType(SuperRep->getType()),
2061 SourceLocation());
2062 MsgExprs.push_back(Unop);
2063 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002064 // Remove all type-casts because it may contain objc-style types; e.g.
2065 // Foo<Proto> *.
2066 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2067 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002068 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002069 MsgExprs.push_back(recExpr);
2070 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002071 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002072 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002073 llvm::SmallVector<Expr*, 8> SelExprs;
2074 QualType argType = Context->getPointerType(Context->CharTy);
2075 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2076 Exp->getSelector().getName().size(),
2077 false, argType, SourceLocation(),
2078 SourceLocation()));
2079 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2080 &SelExprs[0], SelExprs.size());
2081 MsgExprs.push_back(SelExp);
2082
2083 // Now push any user supplied arguments.
2084 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002085 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002086 // Make all implicit casts explicit...ICE comes in handy:-)
2087 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2088 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002089 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2090 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002091 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002092 }
2093 // Make id<P...> cast into an 'id' cast.
2094 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002095 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002096 while ((CE = dyn_cast<CastExpr>(userExpr)))
2097 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002098 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002099 userExpr, SourceLocation());
2100 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002101 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002102 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002103 // We've transferred the ownership to MsgExprs. Null out the argument in
2104 // the original expression, since we will delete it below.
2105 Exp->setArg(i, 0);
2106 }
Steve Naroffab972d32007-11-04 22:37:50 +00002107 // Generate the funky cast.
2108 CastExpr *cast;
2109 llvm::SmallVector<QualType, 8> ArgTypes;
2110 QualType returnType;
2111
2112 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002113 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2114 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2115 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002116 ArgTypes.push_back(Context->getObjCIdType());
2117 ArgTypes.push_back(Context->getObjCSelType());
2118 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002119 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002120 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002121 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2122 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002123 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002124 ArgTypes.push_back(t);
2125 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002126 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2127 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002128 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002129 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002130 }
2131 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002132 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002133
2134 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002135 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2136 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002137
2138 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2139 // If we don't do this cast, we get the following bizarre warning/note:
2140 // xx.m:13: warning: function called through a non-compatible type
2141 // xx.m:13: note: if this code is reached, the program will abort
2142 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2143 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002144
Steve Naroffab972d32007-11-04 22:37:50 +00002145 // Now do the "normal" pointer to function cast.
2146 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002147 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002148 // If we don't have a method decl, force a variadic cast.
2149 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002150 castType = Context->getPointerType(castType);
2151 cast = new CastExpr(castType, cast, SourceLocation());
2152
2153 // Don't forget the parens to enforce the proper binding.
2154 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2155
2156 const FunctionType *FT = msgSendType->getAsFunctionType();
2157 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2158 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002159 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002160 if (MsgSendStretFlavor) {
2161 // We have the method which returns a struct/union. Must also generate
2162 // call to objc_msgSend_stret and hang both varieties on a conditional
2163 // expression which dictate which one to envoke depending on size of
2164 // method's return type.
2165
2166 // Create a reference to the objc_msgSend_stret() declaration.
2167 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2168 SourceLocation());
2169 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2170 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2171 SourceLocation());
2172 // Now do the "normal" pointer to function cast.
2173 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002174 &ArgTypes[0], ArgTypes.size(),
2175 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002176 castType = Context->getPointerType(castType);
2177 cast = new CastExpr(castType, cast, SourceLocation());
2178
2179 // Don't forget the parens to enforce the proper binding.
2180 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2181
2182 FT = msgSendType->getAsFunctionType();
2183 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2184 FT->getResultType(), SourceLocation());
2185
2186 // Build sizeof(returnType)
2187 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2188 returnType, Context->getSizeType(),
2189 SourceLocation(), SourceLocation());
2190 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2191 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2192 // For X86 it is more complicated and some kind of target specific routine
2193 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002194 unsigned IntSize =
2195 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002196 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2197 Context->IntTy,
2198 SourceLocation());
2199 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2200 BinaryOperator::LE,
2201 Context->IntTy,
2202 SourceLocation());
2203 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2204 ConditionalOperator *CondExpr =
2205 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002206 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002207 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002208 return ReplacingStmt;
2209}
2210
Steve Naroffb29b4272008-04-14 22:03:09 +00002211Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002212 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002213 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002214 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002215
Chris Lattnere64b7772007-10-24 16:57:36 +00002216 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002217 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002218}
2219
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002220/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2221/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002222Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002223 if (!GetProtocolFunctionDecl)
2224 SynthGetProtocolFunctionDecl();
2225 // Create a call to objc_getProtocol("ProtocolName").
2226 llvm::SmallVector<Expr*, 8> ProtoExprs;
2227 QualType argType = Context->getPointerType(Context->CharTy);
2228 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2229 strlen(Exp->getProtocol()->getName()),
2230 false, argType, SourceLocation(),
2231 SourceLocation()));
2232 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2233 &ProtoExprs[0],
2234 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002235 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002236 delete Exp;
2237 return ProtoExp;
2238
2239}
2240
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002241/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002242/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002243void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002244 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002245 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2246 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002247 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002248 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002249 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002250 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002251 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002252 SourceLocation LocStart = CDecl->getLocStart();
2253 SourceLocation LocEnd = CDecl->getLocEnd();
2254
2255 const char *startBuf = SM->getCharacterData(LocStart);
2256 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002257 // If no ivars and no root or if its root, directly or indirectly,
2258 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002259 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2260 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002261 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002262 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002263 return;
2264 }
2265
2266 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002267 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002268 Result += "\nstruct ";
2269 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002270 if (LangOpts.Microsoft)
2271 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002272
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002273 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002274 const char *cursor = strchr(startBuf, '{');
2275 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002276 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002277
2278 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002279 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002280 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002281 Result = "\n struct ";
2282 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002283 Result += "_IMPL ";
2284 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002285 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002286
2287 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002288 SourceLocation OnePastCurly =
2289 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2290 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002291 }
2292 cursor++; // past '{'
2293
2294 // Now comment out any visibility specifiers.
2295 while (cursor < endBuf) {
2296 if (*cursor == '@') {
2297 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002298 // Skip whitespace.
2299 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2300 /*scan*/;
2301
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002302 // FIXME: presence of @public, etc. inside comment results in
2303 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002304 if (!strncmp(cursor, "public", strlen("public")) ||
2305 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002306 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002307 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002308 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002309 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002310 // FIXME: If there are cases where '<' is used in ivar declaration part
2311 // of user code, then scan the ivar list and use needToScanForQualifiers
2312 // for type checking.
2313 else if (*cursor == '<') {
2314 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002315 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002316 cursor = strchr(cursor, '>');
2317 cursor++;
2318 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002319 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002320 }
Steve Narofffea763e82007-11-14 19:25:57 +00002321 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002322 }
Steve Narofffea763e82007-11-14 19:25:57 +00002323 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002324 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002325 } else { // we don't have any instance variables - insert super struct.
2326 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2327 Result += " {\n struct ";
2328 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002329 Result += "_IMPL ";
2330 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002331 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002332 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002333 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002334 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002335 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002336 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002337}
2338
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002339// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002340/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002341void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002342 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002343 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002344 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002345 const char *ClassName,
2346 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002347 if (MethodBegin == MethodEnd) return;
2348
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002349 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002350 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002351 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002352 SEL _cmd;
2353 char *method_types;
2354 void *_imp;
2355 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002356 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002357 Result += "\nstruct _objc_method {\n";
2358 Result += "\tSEL _cmd;\n";
2359 Result += "\tchar *method_types;\n";
2360 Result += "\tvoid *_imp;\n";
2361 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002362
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002363 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002364 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002365
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002366 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002367
2368 /* struct {
2369 struct _objc_method_list *next_method;
2370 int method_count;
2371 struct _objc_method method_list[];
2372 }
2373 */
2374 Result += "\nstatic struct {\n";
2375 Result += "\tstruct _objc_method_list *next_method;\n";
2376 Result += "\tint method_count;\n";
2377 Result += "\tstruct _objc_method method_list[";
2378 Result += utostr(MethodEnd-MethodBegin);
2379 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002380 Result += prefix;
2381 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2382 Result += "_METHODS_";
2383 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002384 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002385 Result += IsInstanceMethod ? "inst" : "cls";
2386 Result += "_meth\")))= ";
2387 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002388
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002389 Result += "\t,{{(SEL)\"";
2390 Result += (*MethodBegin)->getSelector().getName().c_str();
2391 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002392 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002393 Result += "\", \"";
2394 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002395 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002396 Result += MethodInternalNames[*MethodBegin];
2397 Result += "}\n";
2398 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2399 Result += "\t ,{(SEL)\"";
2400 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002401 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002402 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002403 Result += "\", \"";
2404 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002405 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002406 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002407 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002408 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002409 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002410}
2411
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002412/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Steve Naroffb29b4272008-04-14 22:03:09 +00002413void RewriteObjC::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002414 int NumProtocols,
2415 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002416 const char *ClassName,
2417 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002418 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002419 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002420 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002421 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002422 // Output struct protocol_methods holder of method selector and type.
Chris Lattnerc8581052008-03-16 20:19:15 +00002423 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002424 /* struct protocol_methods {
2425 SEL _cmd;
2426 char *method_types;
2427 }
2428 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002429 Result += "\nstruct protocol_methods {\n";
2430 Result += "\tSEL _cmd;\n";
2431 Result += "\tchar *method_types;\n";
2432 Result += "};\n";
2433
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002434 objc_protocol_methods = true;
2435 }
Steve Narofffbfe8252008-05-06 18:26:51 +00002436 // Do not synthesize the protocol more than once.
2437 if (ObjCSynthesizedProtocols.count(PDecl))
2438 continue;
2439
Chris Lattnerc8581052008-03-16 20:19:15 +00002440 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2441 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002442 /* struct _objc_protocol_method_list {
2443 int protocol_method_count;
2444 struct protocol_methods protocols[];
2445 }
2446 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002447 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002448 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002449 Result += "\tstruct protocol_methods protocols[";
2450 Result += utostr(NumMethods);
2451 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002452 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002453 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002454 "{\n\t" + utostr(NumMethods) + "\n";
2455
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002456 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002457 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002458 E = PDecl->instmeth_end(); I != E; ++I) {
2459 if (I == PDecl->instmeth_begin())
2460 Result += "\t ,{{(SEL)\"";
2461 else
2462 Result += "\t ,{(SEL)\"";
2463 Result += (*I)->getSelector().getName().c_str();
2464 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002465 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002466 Result += "\", \"";
2467 Result += MethodTypeString;
2468 Result += "\"}\n";
2469 }
2470 Result += "\t }\n};\n";
2471 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002472
2473 // Output class methods declared in this protocol.
Chris Lattnerc8581052008-03-16 20:19:15 +00002474 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002475 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002476 /* struct _objc_protocol_method_list {
2477 int protocol_method_count;
2478 struct protocol_methods protocols[];
2479 }
2480 */
2481 Result += "\nstatic struct {\n";
2482 Result += "\tint protocol_method_count;\n";
2483 Result += "\tstruct protocol_methods protocols[";
2484 Result += utostr(NumMethods);
2485 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002486 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002487 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002488 "{\n\t";
2489 Result += utostr(NumMethods);
2490 Result += "\n";
2491
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002492 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002493 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002494 E = PDecl->classmeth_end(); I != E; ++I) {
2495 if (I == PDecl->classmeth_begin())
2496 Result += "\t ,{{(SEL)\"";
2497 else
2498 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002499 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002500 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002501 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002502 Result += "\", \"";
2503 Result += MethodTypeString;
2504 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002505 }
2506 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002507 }
Steve Narofffbfe8252008-05-06 18:26:51 +00002508
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002509 // Output:
2510 /* struct _objc_protocol {
2511 // Objective-C 1.0 extensions
2512 struct _objc_protocol_extension *isa;
2513 char *protocol_name;
2514 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002515 struct _objc_protocol_method_list *instance_methods;
2516 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002517 };
2518 */
2519 static bool objc_protocol = false;
2520 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002521 Result += "\nstruct _objc_protocol {\n";
2522 Result += "\tstruct _objc_protocol_extension *isa;\n";
2523 Result += "\tchar *protocol_name;\n";
2524 Result += "\tstruct _objc_protocol **protocol_list;\n";
2525 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2526 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2527 Result += "};\n";
2528
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002529 objc_protocol = true;
2530 }
2531
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002532 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2533 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002534 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002535 "{\n\t0, \"";
2536 Result += PDecl->getName();
2537 Result += "\", 0, ";
Chris Lattnerc8581052008-03-16 20:19:15 +00002538 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002539 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002540 Result += PDecl->getName();
2541 Result += ", ";
2542 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002543 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002544 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002545 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002546 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002547 Result += PDecl->getName();
2548 Result += "\n";
2549 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002550 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002551 Result += "0\n";
2552 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002553
2554 // Mark this protocol as having been generated.
2555 if (!ObjCSynthesizedProtocols.insert(PDecl))
2556 assert(false && "protocol already synthesized");
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002557 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002558 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002559 /* struct _objc_protocol_list {
2560 struct _objc_protocol_list *next;
2561 int protocol_count;
2562 struct _objc_protocol *class_protocols[];
2563 }
2564 */
2565 Result += "\nstatic struct {\n";
2566 Result += "\tstruct _objc_protocol_list *next;\n";
2567 Result += "\tint protocol_count;\n";
2568 Result += "\tstruct _objc_protocol *class_protocols[";
2569 Result += utostr(NumProtocols);
2570 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002571 Result += prefix;
2572 Result += "_PROTOCOLS_";
2573 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002574 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002575 "{\n\t0, ";
2576 Result += utostr(NumProtocols);
2577 Result += "\n";
2578
2579 Result += "\t,{&_OBJC_PROTOCOL_";
2580 Result += Protocols[0]->getName();
2581 Result += " \n";
2582
2583 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002584 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Narofffa8ec622008-04-18 22:15:15 +00002585 Result += "\t ,&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002586 Result += PDecl->getName();
2587 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002588 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002589 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002590 }
2591}
2592
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002593/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002594/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002595void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002596 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002597 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002598 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002599 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002600 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2601 CDecl = CDecl->getNextClassCategory())
2602 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2603 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002604
Chris Lattnereb44eee2007-12-23 01:40:15 +00002605 std::string FullCategoryName = ClassDecl->getName();
2606 FullCategoryName += '_';
2607 FullCategoryName += IDecl->getName();
2608
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002609 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002610 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002611 true, "CATEGORY_", FullCategoryName.c_str(),
2612 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002613
2614 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002615 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002616 false, "CATEGORY_", FullCategoryName.c_str(),
2617 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002618
2619 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002620 // Null CDecl is case of a category implementation with no category interface
2621 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002622 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002623 CDecl->getNumReferencedProtocols(),
2624 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002625 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002626
2627 /* struct _objc_category {
2628 char *category_name;
2629 char *class_name;
2630 struct _objc_method_list *instance_methods;
2631 struct _objc_method_list *class_methods;
2632 struct _objc_protocol_list *protocols;
2633 // Objective-C 1.0 extensions
2634 uint32_t size; // sizeof (struct _objc_category)
2635 struct _objc_property_list *instance_properties; // category's own
2636 // @property decl.
2637 };
2638 */
2639
2640 static bool objc_category = false;
2641 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002642 Result += "\nstruct _objc_category {\n";
2643 Result += "\tchar *category_name;\n";
2644 Result += "\tchar *class_name;\n";
2645 Result += "\tstruct _objc_method_list *instance_methods;\n";
2646 Result += "\tstruct _objc_method_list *class_methods;\n";
2647 Result += "\tstruct _objc_protocol_list *protocols;\n";
2648 Result += "\tunsigned int size;\n";
2649 Result += "\tstruct _objc_property_list *instance_properties;\n";
2650 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002651 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002652 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002653 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2654 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002655 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002656 Result += IDecl->getName();
2657 Result += "\"\n\t, \"";
2658 Result += ClassDecl->getName();
2659 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002660
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002661 if (IDecl->getNumInstanceMethods() > 0) {
2662 Result += "\t, (struct _objc_method_list *)"
2663 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2664 Result += FullCategoryName;
2665 Result += "\n";
2666 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002667 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002668 Result += "\t, 0\n";
2669 if (IDecl->getNumClassMethods() > 0) {
2670 Result += "\t, (struct _objc_method_list *)"
2671 "&_OBJC_CATEGORY_CLASS_METHODS_";
2672 Result += FullCategoryName;
2673 Result += "\n";
2674 }
2675 else
2676 Result += "\t, 0\n";
2677
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002678 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002679 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2680 Result += FullCategoryName;
2681 Result += "\n";
2682 }
2683 else
2684 Result += "\t, 0\n";
2685 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002686}
2687
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002688/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2689/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002690void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002691 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002692 std::string &Result) {
Steve Naroff5df5b762008-05-07 21:23:49 +00002693 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002694 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002695 if (LangOpts.Microsoft)
2696 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002697 Result += ", ";
2698 Result += ivar->getName();
2699 Result += ")";
2700}
2701
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002702//===----------------------------------------------------------------------===//
2703// Meta Data Emission
2704//===----------------------------------------------------------------------===//
2705
Steve Naroffb29b4272008-04-14 22:03:09 +00002706void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002707 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002708 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002709
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002710 // Explictly declared @interface's are already synthesized.
2711 if (CDecl->ImplicitInterfaceDecl()) {
2712 // FIXME: Implementation of a class with no @interface (legacy) doese not
2713 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002714 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002715 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002716
Chris Lattnerbe6df082007-12-12 07:56:42 +00002717 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002718 unsigned NumIvars = !IDecl->ivar_empty()
2719 ? IDecl->ivar_size()
2720 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002721 if (NumIvars > 0) {
2722 static bool objc_ivar = false;
2723 if (!objc_ivar) {
2724 /* struct _objc_ivar {
2725 char *ivar_name;
2726 char *ivar_type;
2727 int ivar_offset;
2728 };
2729 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002730 Result += "\nstruct _objc_ivar {\n";
2731 Result += "\tchar *ivar_name;\n";
2732 Result += "\tchar *ivar_type;\n";
2733 Result += "\tint ivar_offset;\n";
2734 Result += "};\n";
2735
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002736 objc_ivar = true;
2737 }
2738
Steve Naroff946a6932008-03-11 00:12:29 +00002739 /* struct {
2740 int ivar_count;
2741 struct _objc_ivar ivar_list[nIvars];
2742 };
2743 */
2744 Result += "\nstatic struct {\n";
2745 Result += "\tint ivar_count;\n";
2746 Result += "\tstruct _objc_ivar ivar_list[";
2747 Result += utostr(NumIvars);
2748 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002749 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002750 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002751 "{\n\t";
2752 Result += utostr(NumIvars);
2753 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002754
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002755 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002756 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002757 IVI = IDecl->ivar_begin();
2758 IVE = IDecl->ivar_end();
2759 } else {
2760 IVI = CDecl->ivar_begin();
2761 IVE = CDecl->ivar_end();
2762 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002763 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002764 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002765 Result += "\", \"";
2766 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002767 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2768 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002769 Result += StrEncoding;
2770 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002771 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002772 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002773 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002774 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002775 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002776 Result += "\", \"";
2777 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002778 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2779 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002780 Result += StrEncoding;
2781 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002782 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002783 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002784 }
2785
2786 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002787 }
2788
2789 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002790 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002791 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002792
2793 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002794 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002795 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002796
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002797 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002798 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002799 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002800 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002801
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002802
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002803 // Declaration of class/meta-class metadata
2804 /* struct _objc_class {
2805 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002806 const char *super_class_name;
2807 char *name;
2808 long version;
2809 long info;
2810 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002811 struct _objc_ivar_list *ivars;
2812 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002813 struct objc_cache *cache;
2814 struct objc_protocol_list *protocols;
2815 const char *ivar_layout;
2816 struct _objc_class_ext *ext;
2817 };
2818 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002819 static bool objc_class = false;
2820 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002821 Result += "\nstruct _objc_class {\n";
2822 Result += "\tstruct _objc_class *isa;\n";
2823 Result += "\tconst char *super_class_name;\n";
2824 Result += "\tchar *name;\n";
2825 Result += "\tlong version;\n";
2826 Result += "\tlong info;\n";
2827 Result += "\tlong instance_size;\n";
2828 Result += "\tstruct _objc_ivar_list *ivars;\n";
2829 Result += "\tstruct _objc_method_list *methods;\n";
2830 Result += "\tstruct objc_cache *cache;\n";
2831 Result += "\tstruct _objc_protocol_list *protocols;\n";
2832 Result += "\tconst char *ivar_layout;\n";
2833 Result += "\tstruct _objc_class_ext *ext;\n";
2834 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002835 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002836 }
2837
2838 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002839 ObjCInterfaceDecl *RootClass = 0;
2840 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002841 while (SuperClass) {
2842 RootClass = SuperClass;
2843 SuperClass = SuperClass->getSuperClass();
2844 }
2845 SuperClass = CDecl->getSuperClass();
2846
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002847 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2848 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002849 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002850 "{\n\t(struct _objc_class *)\"";
2851 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2852 Result += "\"";
2853
2854 if (SuperClass) {
2855 Result += ", \"";
2856 Result += SuperClass->getName();
2857 Result += "\", \"";
2858 Result += CDecl->getName();
2859 Result += "\"";
2860 }
2861 else {
2862 Result += ", 0, \"";
2863 Result += CDecl->getName();
2864 Result += "\"";
2865 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002866 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002867 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002868 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002869 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002870 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002871 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002872 Result += "\n";
2873 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002874 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002875 Result += ", 0\n";
2876 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002877 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002878 Result += CDecl->getName();
2879 Result += ",0,0\n";
2880 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002881 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002882 Result += "\t,0,0,0,0\n";
2883 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002884
2885 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002886 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2887 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002888 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002889 "{\n\t&_OBJC_METACLASS_";
2890 Result += CDecl->getName();
2891 if (SuperClass) {
2892 Result += ", \"";
2893 Result += SuperClass->getName();
2894 Result += "\", \"";
2895 Result += CDecl->getName();
2896 Result += "\"";
2897 }
2898 else {
2899 Result += ", 0, \"";
2900 Result += CDecl->getName();
2901 Result += "\"";
2902 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002903 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002904 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002905 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002906 Result += ",0";
2907 else {
2908 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002909 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002910 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002911 if (LangOpts.Microsoft)
2912 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002913 Result += ")";
2914 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002915 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002916 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002917 Result += CDecl->getName();
2918 Result += "\n\t";
2919 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002920 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002921 Result += ",0";
2922 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002923 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002924 Result += CDecl->getName();
2925 Result += ", 0\n\t";
2926 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002927 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002928 Result += ",0,0";
2929 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002930 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002931 Result += CDecl->getName();
2932 Result += ", 0,0\n";
2933 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002934 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002935 Result += ",0,0,0\n";
2936 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002937}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002938
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002939/// RewriteImplementations - This routine rewrites all method implementations
2940/// and emits meta-data.
2941
Steve Naroffb29b4272008-04-14 22:03:09 +00002942void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002943 int ClsDefCount = ClassImplementation.size();
2944 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002945
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002946 if (ClsDefCount == 0 && CatDefCount == 0)
2947 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002948 // Rewrite implemented methods
2949 for (int i = 0; i < ClsDefCount; i++)
2950 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002951
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002952 for (int i = 0; i < CatDefCount; i++)
2953 RewriteImplementationDecl(CategoryImplementation[i]);
2954
Steve Naroff5df5b762008-05-07 21:23:49 +00002955 // This is needed for determining instance variable offsets.
2956 Result += "#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002957 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002958 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002959 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002960
2961 // For each implemented category, write out all its meta data.
2962 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002963 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002964
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002965 // Write objc_symtab metadata
2966 /*
2967 struct _objc_symtab
2968 {
2969 long sel_ref_cnt;
2970 SEL *refs;
2971 short cls_def_cnt;
2972 short cat_def_cnt;
2973 void *defs[cls_def_cnt + cat_def_cnt];
2974 };
2975 */
2976
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002977 Result += "\nstruct _objc_symtab {\n";
2978 Result += "\tlong sel_ref_cnt;\n";
2979 Result += "\tSEL *refs;\n";
2980 Result += "\tshort cls_def_cnt;\n";
2981 Result += "\tshort cat_def_cnt;\n";
2982 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2983 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002984
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002985 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002986 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002987 Result += "\t0, 0, " + utostr(ClsDefCount)
2988 + ", " + utostr(CatDefCount) + "\n";
2989 for (int i = 0; i < ClsDefCount; i++) {
2990 Result += "\t,&_OBJC_CLASS_";
2991 Result += ClassImplementation[i]->getName();
2992 Result += "\n";
2993 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002994
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002995 for (int i = 0; i < CatDefCount; i++) {
2996 Result += "\t,&_OBJC_CATEGORY_";
2997 Result += CategoryImplementation[i]->getClassInterface()->getName();
2998 Result += "_";
2999 Result += CategoryImplementation[i]->getName();
3000 Result += "\n";
3001 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003002
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003003 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003004
3005 // Write objc_module metadata
3006
3007 /*
3008 struct _objc_module {
3009 long version;
3010 long size;
3011 const char *name;
3012 struct _objc_symtab *symtab;
3013 }
3014 */
3015
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003016 Result += "\nstruct _objc_module {\n";
3017 Result += "\tlong version;\n";
3018 Result += "\tlong size;\n";
3019 Result += "\tconst char *name;\n";
3020 Result += "\tstruct _objc_symtab *symtab;\n";
3021 Result += "};\n\n";
3022 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003023 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003024 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3025 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003026 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003027
3028 if (LangOpts.Microsoft) {
3029 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003030 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003031 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3032 Result += "&_OBJC_MODULES;\n";
3033 Result += "#pragma data_seg(pop)\n\n";
3034 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003035}
Chris Lattner311ff022007-10-16 22:36:42 +00003036
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003037