blob: fc64b5d9123c4e94f47d0b0e000b37d84629e31c [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"
Chris Lattnerc68ab772008-03-22 00:08:40 +000026#include "llvm/System/Path.h"
Steve Naroff0d4e9632008-04-14 22:53:48 +000027#include <sstream>
Chris Lattnerc68ab772008-03-22 00:08:40 +000028#include <fstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031
Steve Naroff0113c9d2008-01-28 21:34:52 +000032static llvm::cl::opt<bool>
33SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
34 llvm::cl::desc("Silence ObjC rewriting warnings"));
35
Chris Lattner77cd2a02007-10-11 00:43:27 +000036namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000037 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000038 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000039 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000040 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000041 unsigned RewriteFailedDiag;
42
Chris Lattner01c57482007-10-17 22:35:30 +000043 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000044 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000045 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000046 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000047 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000048 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000049
Ted Kremeneka526c5c2008-01-07 19:49:32 +000050 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
51 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
52 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000053 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000054 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
55 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000056 llvm::SmallVector<Stmt *, 32> Stmts;
57 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000058 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000059
Steve Naroffd82a9ab2008-03-15 00:55:56 +000060 unsigned NumObjCStringLiterals;
61
Steve Naroffebf2b562007-10-23 23:50:29 +000062 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000063 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000064 FunctionDecl *MsgSendStretFunctionDecl;
65 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000066 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000067 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000068 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000069 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000070 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000071 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000072 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000073
Steve Naroffbeaf2992007-11-03 11:27:19 +000074 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000075 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000076 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000077
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000078 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000079 int BcLabelCount;
80
Steve Naroff874e2322007-11-15 10:28:18 +000081 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000082 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000083 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000084 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000085
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000086 // Needed for header files being rewritten
87 bool IsHeader;
88
Steve Naroffa7b402d2008-03-28 22:26:09 +000089 std::string InFileName;
90 std::string OutFileName;
91
Steve Naroffba92b2e2008-03-27 22:29:16 +000092 std::string Preamble;
93
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000094 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000095 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000096 void Initialize(ASTContext &context);
97
Chris Lattner8a12c272007-10-11 18:38:32 +000098
Chris Lattnerf04da132007-10-24 17:06:59 +000099 // Top Level Driver code.
100 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000101 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000102 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000103 Diagnostic &D, const LangOptions &LOpts);
Steve Naroffb29b4272008-04-14 22:03:09 +0000104 ~RewriteObjC();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000105
106 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000107 // If replacement succeeded or warning disabled return with no warning.
108 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000109 return;
110
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000111 SourceRange Range = Old->getSourceRange();
112 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
113 0, 0, &Range, 1);
114 }
115
Steve Naroffba92b2e2008-03-27 22:29:16 +0000116 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
117 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000118 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000119 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000120 SilenceRewriteMacroWarning)
121 return;
122
123 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
124 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000125
Chris Lattneraadaf782008-01-31 19:51:04 +0000126 void RemoveText(SourceLocation Loc, unsigned StrLen) {
127 // If removal succeeded or warning disabled return with no warning.
128 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
129 return;
130
131 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
132 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000133
Chris Lattneraadaf782008-01-31 19:51:04 +0000134 void ReplaceText(SourceLocation Start, unsigned OrigLength,
135 const char *NewStr, unsigned NewLength) {
136 // If removal succeeded or warning disabled return with no warning.
137 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
138 SilenceRewriteMacroWarning)
139 return;
140
141 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
142 }
143
Chris Lattnerf04da132007-10-24 17:06:59 +0000144 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000145 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000146 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000147 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000148 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
149 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000150 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000151 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
152 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
153 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
154 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
155 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000156 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000157 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000158 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000159 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000160 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000161 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000162 QualType getConstantStringStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000163
Chris Lattnerf04da132007-10-24 17:06:59 +0000164 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000165 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000166 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000167 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000168 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000169 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000170 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000171 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000172 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000173 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000174 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
175 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
176 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000177 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
178 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000179 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
180 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000181 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000182 Stmt *RewriteBreakStmt(BreakStmt *S);
183 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000184 void SynthCountByEnumWithState(std::string &buf);
185
Steve Naroff09b266e2007-10-30 23:14:51 +0000186 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000187 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000188 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000189 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000190 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000191 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000192 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000193 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000194 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000195 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000196
Chris Lattnerf04da132007-10-24 17:06:59 +0000197 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000199 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000200
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000201 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000202 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000203
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000204 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
205 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000206 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000207 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000208 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000209 const char *ClassName,
210 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000211
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000212 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000213 int NumProtocols,
214 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000215 const char *ClassName,
216 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000217 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000218 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000219 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
220 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000221 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000222 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000223 };
224}
225
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000226static bool IsHeaderFile(const std::string &Filename) {
227 std::string::size_type DotPos = Filename.rfind('.');
228
229 if (DotPos == std::string::npos) {
230 // no file extension
231 return false;
232 }
233
234 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
235 // C header: .h
236 // C++ header: .hh or .H;
237 return Ext == "h" || Ext == "hh" || Ext == "H";
238}
239
Steve Naroffb29b4272008-04-14 22:03:09 +0000240RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000241 Diagnostic &D, const LangOptions &LOpts)
242 : Diags(D), LangOpts(LOpts) {
243 IsHeader = IsHeaderFile(inFile);
244 InFileName = inFile;
245 OutFileName = outFile;
246 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
247 "rewriting sub-expression within a macro (may not be correct)");
248}
249
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000250ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000251 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000252 Diagnostic &Diags,
253 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000254 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000255}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000256
Steve Naroffb29b4272008-04-14 22:03:09 +0000257void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000258 Context = &context;
259 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000260 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000261 MsgSendFunctionDecl = 0;
262 MsgSendSuperFunctionDecl = 0;
263 MsgSendStretFunctionDecl = 0;
264 MsgSendSuperStretFunctionDecl = 0;
265 MsgSendFpretFunctionDecl = 0;
266 GetClassFunctionDecl = 0;
267 GetMetaClassFunctionDecl = 0;
268 SelGetUidFunctionDecl = 0;
269 CFStringFunctionDecl = 0;
270 GetProtocolFunctionDecl = 0;
271 ConstantStringClassReference = 0;
272 NSStringRecord = 0;
273 CurMethodDecl = 0;
274 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000275 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000276 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000277 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000278 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000279
280 // Get the ID and start/end of the main file.
281 MainFileID = SM->getMainFileID();
282 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
283 MainFileStart = MainBuf->getBufferStart();
284 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000285
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000286 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000287
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000288 // declaring objc_selector outside the parameter list removes a silly
289 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000290 if (IsHeader)
291 Preamble = "#pragma once\n";
292 Preamble += "struct objc_selector; struct objc_class;\n";
293 Preamble += "#ifndef OBJC_SUPER\n";
294 Preamble += "struct objc_super { struct objc_object *object; ";
295 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000296 if (LangOpts.Microsoft) {
297 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000298 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
299 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000300 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000301 Preamble += "};\n";
302 Preamble += "#define OBJC_SUPER\n";
303 Preamble += "#endif\n";
304 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
305 Preamble += "typedef struct objc_object Protocol;\n";
306 Preamble += "#define _REWRITER_typedef_Protocol\n";
307 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000308 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000309 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
310 else
311 Preamble += "#define __OBJC_RW_EXTERN extern\n";
312 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000313 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000314 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000315 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000316 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000317 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000318 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000319 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000320 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000321 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000322 Preamble += "__OBJC_RW_EXTERN objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000323 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000324 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000325 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000326 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
327 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
328 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
329 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
330 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000331 Preamble += "(struct objc_class *, struct objc_object *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000332 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000333 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000334 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000335 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
336 Preamble += "struct __objcFastEnumerationState {\n\t";
337 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000338 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000339 Preamble += "unsigned long *mutationsPtr;\n\t";
340 Preamble += "unsigned long extra[5];\n};\n";
341 Preamble += "#define __FASTENUMERATIONSTATE\n";
342 Preamble += "#endif\n";
343 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
344 Preamble += "struct __NSConstantStringImpl {\n";
345 Preamble += " int *isa;\n";
346 Preamble += " int flags;\n";
347 Preamble += " char *str;\n";
348 Preamble += " long length;\n";
349 Preamble += "};\n";
350 Preamble += "extern int __CFConstantStringClassReference[];\n";
351 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
352 Preamble += "#endif\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000353 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000354 Preamble += "#define __attribute__(X)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000355}
356
357
Chris Lattnerf04da132007-10-24 17:06:59 +0000358//===----------------------------------------------------------------------===//
359// Top Level Driver Code
360//===----------------------------------------------------------------------===//
361
Steve Naroffb29b4272008-04-14 22:03:09 +0000362void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000363 // Two cases: either the decl could be in the main file, or it could be in a
364 // #included file. If the former, rewrite it now. If the later, check to see
365 // if we rewrote the #include/#import.
366 SourceLocation Loc = D->getLocation();
367 Loc = SM->getLogicalLoc(Loc);
368
369 // If this is for a builtin, ignore it.
370 if (Loc.isInvalid()) return;
371
Steve Naroffebf2b562007-10-23 23:50:29 +0000372 // Look for built-in declarations that we need to refer during the rewrite.
373 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000374 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000375 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000376 // declared in <Foundation/NSString.h>
377 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
378 ConstantStringClassReference = FVD;
379 return;
380 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000381 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000382 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000383 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000384 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000385 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000386 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000387 } else if (ObjCForwardProtocolDecl *FP =
388 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000389 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000390 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000391 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000392 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000393 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000394}
395
Chris Lattnerf04da132007-10-24 17:06:59 +0000396/// HandleDeclInMainFile - This is called for each top-level decl defined in the
397/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000398void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000399 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
400 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000401 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000402
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000403 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000404 if (Stmt *Body = MD->getBody()) {
405 //Body->dump();
406 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000407 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000408 CurMethodDecl = 0;
409 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000410 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000411 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000412 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000413 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000414 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000415 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000416 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000417 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000418 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000419 if (VD->getInit())
420 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
421 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000422 // Nothing yet.
423}
424
Steve Naroffb29b4272008-04-14 22:03:09 +0000425RewriteObjC::~RewriteObjC() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000426 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000427
428 // Rewrite tabs if we care.
429 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000430
Steve Naroffa7b402d2008-03-28 22:26:09 +0000431 if (Diags.hasErrorOccurred())
432 return;
433
434 // Create the output file.
435
436 std::ostream *OutFile;
437 if (OutFileName == "-") {
438 OutFile = llvm::cout.stream();
439 } else if (!OutFileName.empty()) {
440 OutFile = new std::ofstream(OutFileName.c_str(),
441 std::ios_base::binary|std::ios_base::out);
442 } else if (InFileName == "-") {
443 OutFile = llvm::cout.stream();
444 } else {
445 llvm::sys::Path Path(InFileName);
446 Path.eraseSuffix();
447 Path.appendSuffix("cpp");
448 OutFile = new std::ofstream(Path.toString().c_str(),
449 std::ios_base::binary|std::ios_base::out);
450 }
451
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000452 RewriteInclude();
453
Steve Naroffba92b2e2008-03-27 22:29:16 +0000454 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
455 Preamble.c_str(), Preamble.size(), false);
456
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000457 // Rewrite Objective-c meta data*
458 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000459 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000460
Chris Lattnerf04da132007-10-24 17:06:59 +0000461 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
462 // we are done.
463 if (const RewriteBuffer *RewriteBuf =
464 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000465 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000466 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000467 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000468 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000469 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000470 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000471 *OutFile << ResultStr;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000472}
473
Chris Lattnerf04da132007-10-24 17:06:59 +0000474//===----------------------------------------------------------------------===//
475// Syntactic (non-AST) Rewriting Code
476//===----------------------------------------------------------------------===//
477
Steve Naroffb29b4272008-04-14 22:03:09 +0000478void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000479 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
480 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
481 const char *MainBufStart = MainBuf.first;
482 const char *MainBufEnd = MainBuf.second;
483 size_t ImportLen = strlen("import");
484 size_t IncludeLen = strlen("include");
485
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000486 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000487 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
488 if (*BufPtr == '#') {
489 if (++BufPtr == MainBufEnd)
490 return;
491 while (*BufPtr == ' ' || *BufPtr == '\t')
492 if (++BufPtr == MainBufEnd)
493 return;
494 if (!strncmp(BufPtr, "import", ImportLen)) {
495 // replace import with include
496 SourceLocation ImportLoc =
497 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000498 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000499 BufPtr += ImportLen;
500 }
501 }
502 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000503}
504
Steve Naroffb29b4272008-04-14 22:03:09 +0000505void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000506 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
507 const char *MainBufStart = MainBuf.first;
508 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000509
Chris Lattnerf04da132007-10-24 17:06:59 +0000510 // Loop over the whole file, looking for tabs.
511 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
512 if (*BufPtr != '\t')
513 continue;
514
515 // Okay, we found a tab. This tab will turn into at least one character,
516 // but it depends on which 'virtual column' it is in. Compute that now.
517 unsigned VCol = 0;
518 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
519 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
520 ++VCol;
521
522 // Okay, now that we know the virtual column, we know how many spaces to
523 // insert. We assume 8-character tab-stops.
524 unsigned Spaces = 8-(VCol & 7);
525
526 // Get the location of the tab.
527 SourceLocation TabLoc =
528 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
529
530 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000531 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000532 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000533}
534
535
Steve Naroffb29b4272008-04-14 22:03:09 +0000536void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000537 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000538 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000539
540 // Get the start location and compute the semi location.
541 SourceLocation startLoc = ClassDecl->getLocation();
542 const char *startBuf = SM->getCharacterData(startLoc);
543 const char *semiPtr = strchr(startBuf, ';');
544
545 // Translate to typedef's that forward reference structs with the same name
546 // as the class. As a convenience, we include the original declaration
547 // as a comment.
548 std::string typedefString;
549 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000550 typedefString.append(startBuf, semiPtr-startBuf+1);
551 typedefString += "\n";
552 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000553 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000554 typedefString += "#ifndef _REWRITER_typedef_";
555 typedefString += ForwardDecl->getName();
556 typedefString += "\n";
557 typedefString += "#define _REWRITER_typedef_";
558 typedefString += ForwardDecl->getName();
559 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000560 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000561 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000562 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000563 }
564
565 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000566 ReplaceText(startLoc, semiPtr-startBuf+1,
567 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000568}
569
Steve Naroffb29b4272008-04-14 22:03:09 +0000570void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000571 SourceLocation LocStart = Method->getLocStart();
572 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000573
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000574 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000575 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000576 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000577 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000578 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000579 }
580}
581
Steve Naroffb29b4272008-04-14 22:03:09 +0000582void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000583{
Chris Lattner55d13b42008-03-16 21:23:50 +0000584 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000585 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000586 SourceLocation Loc = Property->getLocation();
587
Chris Lattneraadaf782008-01-31 19:51:04 +0000588 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000589
590 // FIXME: handle properties that are declared across multiple lines.
591 }
592}
593
Steve Naroffb29b4272008-04-14 22:03:09 +0000594void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000595 SourceLocation LocStart = CatDecl->getLocStart();
596
597 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000598 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000599
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000600 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000601 E = CatDecl->instmeth_end(); I != E; ++I)
602 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000603 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000604 E = CatDecl->classmeth_end(); I != E; ++I)
605 RewriteMethodDeclaration(*I);
606
Steve Naroff423cb562007-10-30 13:30:57 +0000607 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000608 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000609}
610
Steve Naroffb29b4272008-04-14 22:03:09 +0000611void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000612 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000613
Steve Naroff752d6ef2007-10-30 16:42:30 +0000614 SourceLocation LocStart = PDecl->getLocStart();
615
616 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000617 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000618
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000619 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000620 E = PDecl->instmeth_end(); I != E; ++I)
621 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000622 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000623 E = PDecl->classmeth_end(); I != E; ++I)
624 RewriteMethodDeclaration(*I);
625
Steve Naroff752d6ef2007-10-30 16:42:30 +0000626 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000627 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000628 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000629
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000630 // Must comment out @optional/@required
631 const char *startBuf = SM->getCharacterData(LocStart);
632 const char *endBuf = SM->getCharacterData(LocEnd);
633 for (const char *p = startBuf; p < endBuf; p++) {
634 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
635 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000636 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000637 ReplaceText(OptionalLoc, strlen("@optional"),
638 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000639
640 }
641 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
642 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000643 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000644 ReplaceText(OptionalLoc, strlen("@required"),
645 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000646
647 }
648 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000649}
650
Steve Naroffb29b4272008-04-14 22:03:09 +0000651void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000652 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000653 if (LocStart.isInvalid())
654 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000655 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000656 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000657}
658
Steve Naroffb29b4272008-04-14 22:03:09 +0000659void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000660 std::string &ResultStr) {
661 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000662 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000663 ResultStr += "id";
664 else
665 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000666 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000667
668 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000669 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000670
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000671 if (OMD->isInstance())
672 NameStr += "_I_";
673 else
674 NameStr += "_C_";
675
676 NameStr += OMD->getClassInterface()->getName();
677 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000678
679 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000680 if (ObjCCategoryImplDecl *CID =
681 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000682 NameStr += CID->getName();
683 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000684 }
Steve Naroff563b8282008-04-04 22:23:44 +0000685 // Append selector names, replacing ':' with '_'
686 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000687 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000688 else {
689 std::string selString = OMD->getSelector().getName();
690 int len = selString.size();
691 for (int i = 0; i < len; i++)
692 if (selString[i] == ':')
693 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000694 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000695 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000696 // Remember this name for metadata emission
697 MethodInternalNames[OMD] = NameStr;
698 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000699
700 // Rewrite arguments
701 ResultStr += "(";
702
703 // invisible arguments
704 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000705 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000706 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000707 if (!LangOpts.Microsoft) {
708 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
709 ResultStr += "struct ";
710 }
711 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000712 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000713 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000714 }
715 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000717
718 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000719 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000720 ResultStr += " _cmd";
721
722 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000723 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000724 ParmVarDecl *PDecl = OMD->getParamDecl(i);
725 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000726 if (PDecl->getType()->isObjCQualifiedIdType()) {
727 ResultStr += "id ";
728 ResultStr += PDecl->getName();
729 } else {
730 std::string Name = PDecl->getName();
731 PDecl->getType().getAsStringInternal(Name);
732 ResultStr += Name;
733 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000734 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000735 if (OMD->isVariadic())
736 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000737 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000738
739}
Steve Naroffb29b4272008-04-14 22:03:09 +0000740void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000741 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
742 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000743
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000744 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000745 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000746 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000747 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000748
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000749 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000750 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
751 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000752 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000753 ObjCMethodDecl *OMD = *I;
754 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000755 SourceLocation LocStart = OMD->getLocStart();
756 SourceLocation LocEnd = OMD->getBody()->getLocStart();
757
758 const char *startBuf = SM->getCharacterData(LocStart);
759 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000760 ReplaceText(LocStart, endBuf-startBuf,
761 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000762 }
763
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000764 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000765 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
766 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000767 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000768 ObjCMethodDecl *OMD = *I;
769 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000770 SourceLocation LocStart = OMD->getLocStart();
771 SourceLocation LocEnd = OMD->getBody()->getLocStart();
772
773 const char *startBuf = SM->getCharacterData(LocStart);
774 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000775 ReplaceText(LocStart, endBuf-startBuf,
776 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000777 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000778 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000779 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000780 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000781 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000782}
783
Steve Naroffb29b4272008-04-14 22:03:09 +0000784void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000785 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000786 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000787 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000788 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000789 ResultStr += ClassDecl->getName();
790 ResultStr += "\n";
791 ResultStr += "#define _REWRITER_typedef_";
792 ResultStr += ClassDecl->getName();
793 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000794 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000795 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000796 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000797 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000798 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000799 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000800 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000801
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000802 RewriteProperties(ClassDecl->getNumPropertyDecl(),
803 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000804 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000805 E = ClassDecl->instmeth_end(); I != E; ++I)
806 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000807 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000808 E = ClassDecl->classmeth_end(); I != E; ++I)
809 RewriteMethodDeclaration(*I);
810
Steve Naroff2feac5e2007-10-30 03:43:13 +0000811 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000812 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000813}
814
Steve Naroffb29b4272008-04-14 22:03:09 +0000815Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000816 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000817 if (CurMethodDecl) {
818 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
819 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
820 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000821 // lookup which class implements the instance variable.
822 ObjCInterfaceDecl *clsDeclared = 0;
823 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
824 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5518e7c2008-03-12 23:15:19 +0000825
826 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000827 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff05b8c782008-03-12 00:25:36 +0000828 RecName += "_IMPL";
829 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000830 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000831 SourceLocation(), II, 0);
Steve Naroff05b8c782008-03-12 00:25:36 +0000832 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
833 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
834 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
835 // Don't forget the parens to enforce the proper binding.
836 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
837 if (IV->isFreeIvar()) {
838 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
839 ReplaceStmt(IV, ME);
840 delete IV;
841 return ME;
842 } else {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000843 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5518e7c2008-03-12 23:15:19 +0000844 // Cannot delete IV->getBase(), since PE points to it.
845 // Replace the old base with the cast. This is important when doing
846 // embedded rewrites. For example, [newInv->_container addObject:0].
847 IV->setBase(PE);
848 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000849 }
850 }
851 }
Steve Naroff84472a82008-04-18 21:55:08 +0000852 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000853 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
854
855 // Explicit ivar refs need to have a cast inserted.
856 // FIXME: consider sharing some of this code with the code above.
857 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
858 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
859 // lookup which class implements the instance variable.
860 ObjCInterfaceDecl *clsDeclared = 0;
861 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
862 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
863
864 // Synthesize an explicit cast to gain access to the ivar.
865 std::string RecName = clsDeclared->getIdentifier()->getName();
866 RecName += "_IMPL";
867 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
868 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
869 SourceLocation(), II, 0);
870 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
871 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
872 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
873 // Don't forget the parens to enforce the proper binding.
874 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
875 ReplaceStmt(IV->getBase(), PE);
876 // Cannot delete IV->getBase(), since PE points to it.
877 // Replace the old base with the cast. This is important when doing
878 // embedded rewrites. For example, [newInv->_container addObject:0].
879 IV->setBase(PE);
880 return IV;
881 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000882 }
Steve Naroff84472a82008-04-18 21:55:08 +0000883 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000884}
885
Chris Lattnerf04da132007-10-24 17:06:59 +0000886//===----------------------------------------------------------------------===//
887// Function Body / Expression rewriting
888//===----------------------------------------------------------------------===//
889
Steve Naroffb29b4272008-04-14 22:03:09 +0000890Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000891 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
892 isa<DoStmt>(S) || isa<ForStmt>(S))
893 Stmts.push_back(S);
894 else if (isa<ObjCForCollectionStmt>(S)) {
895 Stmts.push_back(S);
896 ObjCBcLabelNo.push_back(++BcLabelCount);
897 }
898
Chris Lattner338d1e22008-01-31 05:10:40 +0000899 SourceLocation OrigStmtEnd = S->getLocEnd();
900
901 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000902 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
903 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000904 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000905 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000906 if (newStmt)
907 *CI = newStmt;
908 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000909
910 // Handle specific things.
911 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
912 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000913
914 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
915 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000916
917 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
918 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000919
Steve Naroffbeaf2992007-11-03 11:27:19 +0000920 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
921 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000922
Steve Naroff934f2762007-10-24 22:48:43 +0000923 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
924 // Before we rewrite it, put the original message expression in a comment.
925 SourceLocation startLoc = MessExpr->getLocStart();
926 SourceLocation endLoc = MessExpr->getLocEnd();
927
928 const char *startBuf = SM->getCharacterData(startLoc);
929 const char *endBuf = SM->getCharacterData(endLoc);
930
931 std::string messString;
932 messString += "// ";
933 messString.append(startBuf, endBuf-startBuf+1);
934 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000935
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000936 // FIXME: Missing definition of
937 // InsertText(clang::SourceLocation, char const*, unsigned int).
938 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000939 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000940 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000941 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000942 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000943
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000944 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
945 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000946
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000947 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
948 return RewriteObjCSynchronizedStmt(StmtTry);
949
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000950 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
951 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000952
953 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
954 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000955
956 if (ObjCForCollectionStmt *StmtForCollection =
957 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000958 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000959 if (BreakStmt *StmtBreakStmt =
960 dyn_cast<BreakStmt>(S))
961 return RewriteBreakStmt(StmtBreakStmt);
962 if (ContinueStmt *StmtContinueStmt =
963 dyn_cast<ContinueStmt>(S))
964 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000965
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000966 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
967 isa<DoStmt>(S) || isa<ForStmt>(S)) {
968 assert(!Stmts.empty() && "Statement stack is empty");
969 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
970 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
971 && "Statement stack mismatch");
972 Stmts.pop_back();
973 }
Steve Naroff874e2322007-11-15 10:28:18 +0000974#if 0
975 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
976 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
977 // Get the new text.
978 std::ostringstream Buf;
979 Replacement->printPretty(Buf);
980 const std::string &Str = Buf.str();
981
982 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000983 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000984 delete S;
985 return Replacement;
986 }
987#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000988 // Return this stmt unmodified.
989 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000990}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000991
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000992/// SynthCountByEnumWithState - To print:
993/// ((unsigned int (*)
994/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
995/// (void *)objc_msgSend)((id)l_collection,
996/// sel_registerName(
997/// "countByEnumeratingWithState:objects:count:"),
998/// &enumState,
999/// (id *)items, (unsigned int)16)
1000///
Steve Naroffb29b4272008-04-14 22:03:09 +00001001void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001002 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1003 "id *, unsigned int))(void *)objc_msgSend)";
1004 buf += "\n\t\t";
1005 buf += "((id)l_collection,\n\t\t";
1006 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1007 buf += "\n\t\t";
1008 buf += "&enumState, "
1009 "(id *)items, (unsigned int)16)";
1010}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001011
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001012/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1013/// statement to exit to its outer synthesized loop.
1014///
Steve Naroffb29b4272008-04-14 22:03:09 +00001015Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001016 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1017 return S;
1018 // replace break with goto __break_label
1019 std::string buf;
1020
1021 SourceLocation startLoc = S->getLocStart();
1022 buf = "goto __break_label_";
1023 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001024 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001025
1026 return 0;
1027}
1028
1029/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1030/// statement to continue with its inner synthesized loop.
1031///
Steve Naroffb29b4272008-04-14 22:03:09 +00001032Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001033 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1034 return S;
1035 // replace continue with goto __continue_label
1036 std::string buf;
1037
1038 SourceLocation startLoc = S->getLocStart();
1039 buf = "goto __continue_label_";
1040 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001041 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001042
1043 return 0;
1044}
1045
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001046/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001047/// It rewrites:
1048/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001049
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001050/// Into:
1051/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001052/// type elem;
1053/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001054/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001055/// id l_collection = (id)collection;
1056/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1057/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001058/// if (limit) {
1059/// unsigned long startMutations = *enumState.mutationsPtr;
1060/// do {
1061/// unsigned long counter = 0;
1062/// do {
1063/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001064/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001065/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001066/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001067/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001068/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001069/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1070/// objects:items count:16]);
1071/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001072/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001073/// }
1074/// else
1075/// elem = nil;
1076/// }
1077///
Steve Naroffb29b4272008-04-14 22:03:09 +00001078Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001079 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001080 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1081 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1082 "ObjCForCollectionStmt Statement stack mismatch");
1083 assert(!ObjCBcLabelNo.empty() &&
1084 "ObjCForCollectionStmt - Label No stack empty");
1085
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001086 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001087 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001088 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001089 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001090 std::string buf;
1091 buf = "\n{\n\t";
1092 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1093 // type elem;
1094 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001095 elementTypeAsString = ElementType.getAsString();
1096 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001097 buf += " ";
1098 elementName = DS->getDecl()->getName();
1099 buf += elementName;
1100 buf += ";\n\t";
1101 }
Chris Lattner06767512008-04-08 05:52:18 +00001102 else {
1103 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001104 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001105 elementTypeAsString = DR->getDecl()->getType().getAsString();
1106 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001107
1108 // struct __objcFastEnumerationState enumState = { 0 };
1109 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1110 // id items[16];
1111 buf += "id items[16];\n\t";
1112 // id l_collection = (id)
1113 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001114 // Find start location of 'collection' the hard way!
1115 const char *startCollectionBuf = startBuf;
1116 startCollectionBuf += 3; // skip 'for'
1117 startCollectionBuf = strchr(startCollectionBuf, '(');
1118 startCollectionBuf++; // skip '('
1119 // find 'in' and skip it.
1120 while (*startCollectionBuf != ' ' ||
1121 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1122 (*(startCollectionBuf+3) != ' ' &&
1123 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1124 startCollectionBuf++;
1125 startCollectionBuf += 3;
1126
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001127 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001128 ReplaceText(startLoc, startCollectionBuf - startBuf,
1129 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001130 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001131 SourceLocation rightParenLoc = S->getRParenLoc();
1132 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1133 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001134 buf = ";\n\t";
1135
1136 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1137 // objects:items count:16];
1138 // which is synthesized into:
1139 // unsigned int limit =
1140 // ((unsigned int (*)
1141 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1142 // (void *)objc_msgSend)((id)l_collection,
1143 // sel_registerName(
1144 // "countByEnumeratingWithState:objects:count:"),
1145 // (struct __objcFastEnumerationState *)&state,
1146 // (id *)items, (unsigned int)16);
1147 buf += "unsigned long limit =\n\t\t";
1148 SynthCountByEnumWithState(buf);
1149 buf += ";\n\t";
1150 /// if (limit) {
1151 /// unsigned long startMutations = *enumState.mutationsPtr;
1152 /// do {
1153 /// unsigned long counter = 0;
1154 /// do {
1155 /// if (startMutations != *enumState.mutationsPtr)
1156 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001157 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001158 buf += "if (limit) {\n\t";
1159 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1160 buf += "do {\n\t\t";
1161 buf += "unsigned long counter = 0;\n\t\t";
1162 buf += "do {\n\t\t\t";
1163 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1164 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1165 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001166 buf += " = (";
1167 buf += elementTypeAsString;
1168 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001169 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001170 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001171
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001172 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001173 /// } while (counter < limit);
1174 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1175 /// objects:items count:16]);
1176 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001177 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001178 /// }
1179 /// else
1180 /// elem = nil;
1181 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001182 ///
1183 buf = ";\n\t";
1184 buf += "__continue_label_";
1185 buf += utostr(ObjCBcLabelNo.back());
1186 buf += ": ;";
1187 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001188 buf += "} while (counter < limit);\n\t";
1189 buf += "} while (limit = ";
1190 SynthCountByEnumWithState(buf);
1191 buf += ");\n\t";
1192 buf += elementName;
1193 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001194 buf += "__break_label_";
1195 buf += utostr(ObjCBcLabelNo.back());
1196 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001197 buf += "}\n\t";
1198 buf += "else\n\t\t";
1199 buf += elementName;
1200 buf += " = nil;\n";
1201 buf += "}\n";
1202 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001203 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001204 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001205 Stmts.pop_back();
1206 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001207 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001208}
1209
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001210/// RewriteObjCSynchronizedStmt -
1211/// This routine rewrites @synchronized(expr) stmt;
1212/// into:
1213/// objc_sync_enter(expr);
1214/// @try stmt @finally { objc_sync_exit(expr); }
1215///
Steve Naroffb29b4272008-04-14 22:03:09 +00001216Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001217 // Get the start location and compute the semi location.
1218 SourceLocation startLoc = S->getLocStart();
1219 const char *startBuf = SM->getCharacterData(startLoc);
1220
1221 assert((*startBuf == '@') && "bogus @synchronized location");
1222
1223 std::string buf;
1224 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001225 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001226 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1227 const char *endBuf = SM->getCharacterData(endLoc);
1228 endBuf++;
1229 const char *rparenBuf = strchr(endBuf, ')');
1230 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1231 buf = ");\n";
1232 // declare a new scope with two variables, _stack and _rethrow.
1233 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1234 buf += "int buf[18/*32-bit i386*/];\n";
1235 buf += "char *pointers[4];} _stack;\n";
1236 buf += "id volatile _rethrow = 0;\n";
1237 buf += "objc_exception_try_enter(&_stack);\n";
1238 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001239 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001240 startLoc = S->getSynchBody()->getLocEnd();
1241 startBuf = SM->getCharacterData(startLoc);
1242
1243 assert((*startBuf == '}') && "bogus @try block");
1244 SourceLocation lastCurlyLoc = startLoc;
1245 buf = "}\nelse {\n";
1246 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1247 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1248 // FIXME: This must be objc_sync_exit(syncExpr);
1249 buf += " objc_sync_exit();\n";
1250 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1251 buf += "}\n";
1252 buf += "}";
1253
Chris Lattneraadaf782008-01-31 19:51:04 +00001254 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001255 return 0;
1256}
1257
Steve Naroffb29b4272008-04-14 22:03:09 +00001258Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001259 // Get the start location and compute the semi location.
1260 SourceLocation startLoc = S->getLocStart();
1261 const char *startBuf = SM->getCharacterData(startLoc);
1262
1263 assert((*startBuf == '@') && "bogus @try location");
1264
1265 std::string buf;
1266 // declare a new scope with two variables, _stack and _rethrow.
1267 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1268 buf += "int buf[18/*32-bit i386*/];\n";
1269 buf += "char *pointers[4];} _stack;\n";
1270 buf += "id volatile _rethrow = 0;\n";
1271 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001272 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001273
Chris Lattneraadaf782008-01-31 19:51:04 +00001274 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001275
1276 startLoc = S->getTryBody()->getLocEnd();
1277 startBuf = SM->getCharacterData(startLoc);
1278
1279 assert((*startBuf == '}') && "bogus @try block");
1280
1281 SourceLocation lastCurlyLoc = startLoc;
1282
1283 startLoc = startLoc.getFileLocWithOffset(1);
1284 buf = " /* @catch begin */ else {\n";
1285 buf += " id _caught = objc_exception_extract(&_stack);\n";
1286 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001287 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001288 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1289 buf += " else { /* @catch continue */";
1290
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001291 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001292
1293 bool sawIdTypedCatch = false;
1294 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001295 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001296 while (catchList) {
1297 Stmt *catchStmt = catchList->getCatchParamStmt();
1298
1299 if (catchList == S->getCatchStmts())
1300 buf = "if ("; // we are generating code for the first catch clause
1301 else
1302 buf = "else if (";
1303 startLoc = catchList->getLocStart();
1304 startBuf = SM->getCharacterData(startLoc);
1305
1306 assert((*startBuf == '@') && "bogus @catch location");
1307
1308 const char *lParenLoc = strchr(startBuf, '(');
1309
Steve Naroffbe4b3332008-02-01 22:08:12 +00001310 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001311 // Now rewrite the body...
1312 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001313 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1314 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001315 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1316 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001317 assert((*bodyBuf == '{') && "bogus @catch body location");
1318
1319 buf += "1) { id _tmp = _caught;";
1320 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1321 buf.c_str(), buf.size());
1322 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001323 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001324 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001325 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001326 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001327 sawIdTypedCatch = true;
1328 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001329 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001330
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001331 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001332 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001333 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001334 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001335 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001336 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001337 }
1338 }
1339 // Now rewrite the body...
1340 lastCatchBody = catchList->getCatchBody();
1341 SourceLocation rParenLoc = catchList->getRParenLoc();
1342 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1343 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1344 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1345 assert((*rParenBuf == ')') && "bogus @catch paren location");
1346 assert((*bodyBuf == '{') && "bogus @catch body location");
1347
1348 buf = " = _caught;";
1349 // Here we replace ") {" with "= _caught;" (which initializes and
1350 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001351 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001352 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001353 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001354 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001355 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001356 catchList = catchList->getNextCatchStmt();
1357 }
1358 // Complete the catch list...
1359 if (lastCatchBody) {
1360 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001361 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1362 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001363 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1364 buf = " } } /* @catch end */\n";
1365
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001366 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001367
1368 // Set lastCurlyLoc
1369 lastCurlyLoc = lastCatchBody->getLocEnd();
1370 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001371 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001372 startLoc = finalStmt->getLocStart();
1373 startBuf = SM->getCharacterData(startLoc);
1374 assert((*startBuf == '@') && "bogus @finally start");
1375
1376 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001377 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001378
1379 Stmt *body = finalStmt->getFinallyBody();
1380 SourceLocation startLoc = body->getLocStart();
1381 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001382 assert(*SM->getCharacterData(startLoc) == '{' &&
1383 "bogus @finally body location");
1384 assert(*SM->getCharacterData(endLoc) == '}' &&
1385 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001386
1387 startLoc = startLoc.getFileLocWithOffset(1);
1388 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001389 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001390 endLoc = endLoc.getFileLocWithOffset(-1);
1391 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001392 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001393
1394 // Set lastCurlyLoc
1395 lastCurlyLoc = body->getLocEnd();
1396 }
1397 // Now emit the final closing curly brace...
1398 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1399 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001400 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001401 return 0;
1402}
1403
Steve Naroffb29b4272008-04-14 22:03:09 +00001404Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001405 return 0;
1406}
1407
Steve Naroffb29b4272008-04-14 22:03:09 +00001408Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001409 return 0;
1410}
1411
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001412// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001413// the throw expression is typically a message expression that's already
1414// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001415Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001416 // Get the start location and compute the semi location.
1417 SourceLocation startLoc = S->getLocStart();
1418 const char *startBuf = SM->getCharacterData(startLoc);
1419
1420 assert((*startBuf == '@') && "bogus @throw location");
1421
1422 std::string buf;
1423 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001424 if (S->getThrowExpr())
1425 buf = "objc_exception_throw(";
1426 else // add an implicit argument
1427 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001428 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001429 const char *semiBuf = strchr(startBuf, ';');
1430 assert((*semiBuf == ';') && "@throw: can't find ';'");
1431 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1432 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001433 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001434 return 0;
1435}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001436
Steve Naroffb29b4272008-04-14 22:03:09 +00001437Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001438 // Create a new string expression.
1439 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001440 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001441 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1442 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001443 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1444 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001445 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001446 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001447
Chris Lattner07506182007-11-30 22:53:43 +00001448 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001449 delete Exp;
1450 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001451}
1452
Steve Naroffb29b4272008-04-14 22:03:09 +00001453Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001454 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1455 // Create a call to sel_registerName("selName").
1456 llvm::SmallVector<Expr*, 8> SelExprs;
1457 QualType argType = Context->getPointerType(Context->CharTy);
1458 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1459 Exp->getSelector().getName().size(),
1460 false, argType, SourceLocation(),
1461 SourceLocation()));
1462 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1463 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001464 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001465 delete Exp;
1466 return SelExp;
1467}
1468
Steve Naroffb29b4272008-04-14 22:03:09 +00001469CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001470 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001471 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001472 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001473
1474 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001475 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001476
1477 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001478 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001479 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1480
1481 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001482
Steve Naroff934f2762007-10-24 22:48:43 +00001483 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1484}
1485
Steve Naroffd5255f52007-11-01 13:24:47 +00001486static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1487 const char *&startRef, const char *&endRef) {
1488 while (startBuf < endBuf) {
1489 if (*startBuf == '<')
1490 startRef = startBuf; // mark the start.
1491 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001492 if (startRef && *startRef == '<') {
1493 endRef = startBuf; // mark the end.
1494 return true;
1495 }
1496 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001497 }
1498 startBuf++;
1499 }
1500 return false;
1501}
1502
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001503static void scanToNextArgument(const char *&argRef) {
1504 int angle = 0;
1505 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1506 if (*argRef == '<')
1507 angle++;
1508 else if (*argRef == '>')
1509 angle--;
1510 argRef++;
1511 }
1512 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1513}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001514
Steve Naroffb29b4272008-04-14 22:03:09 +00001515bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001516
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001517 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001518 return true;
1519
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001520 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001521 return true;
1522
Steve Naroffd5255f52007-11-01 13:24:47 +00001523 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001524 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001525 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001526 return true; // we have "Class <Protocol> *".
1527 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001528 return false;
1529}
1530
Steve Naroffb29b4272008-04-14 22:03:09 +00001531void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001532 SourceLocation Loc;
1533 QualType Type;
1534 const FunctionTypeProto *proto = 0;
1535 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1536 Loc = VD->getLocation();
1537 Type = VD->getType();
1538 }
1539 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1540 Loc = FD->getLocation();
1541 // Check for ObjC 'id' and class types that have been adorned with protocol
1542 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1543 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1544 assert(funcType && "missing function type");
1545 proto = dyn_cast<FunctionTypeProto>(funcType);
1546 if (!proto)
1547 return;
1548 Type = proto->getResultType();
1549 }
1550 else
1551 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001552
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001553 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001554 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001555
1556 const char *endBuf = SM->getCharacterData(Loc);
1557 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001558 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001559 startBuf--; // scan backward (from the decl location) for return type.
1560 const char *startRef = 0, *endRef = 0;
1561 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1562 // Get the locations of the startRef, endRef.
1563 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1564 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1565 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001566 InsertText(LessLoc, "/*", 2);
1567 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001568 }
1569 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001570 if (!proto)
1571 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001572 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001573 const char *startBuf = SM->getCharacterData(Loc);
1574 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001575 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1576 if (needToScanForQualifiers(proto->getArgType(i))) {
1577 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001578
Steve Naroffd5255f52007-11-01 13:24:47 +00001579 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001580 // scan forward (from the decl location) for argument types.
1581 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001582 const char *startRef = 0, *endRef = 0;
1583 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1584 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001585 SourceLocation LessLoc =
1586 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1587 SourceLocation GreaterLoc =
1588 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001589 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001590 InsertText(LessLoc, "/*", 2);
1591 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001592 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001593 startBuf = ++endBuf;
1594 }
1595 else {
1596 while (*startBuf != ')' && *startBuf != ',')
1597 startBuf++; // scan forward (from the decl location) for argument types.
1598 startBuf++;
1599 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001600 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001601}
1602
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001603// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001604void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001605 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1606 llvm::SmallVector<QualType, 16> ArgTys;
1607 ArgTys.push_back(Context->getPointerType(
1608 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001609 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001610 &ArgTys[0], ArgTys.size(),
1611 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001612 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001613 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001614 SelGetUidIdent, getFuncType,
1615 FunctionDecl::Extern, false, 0);
1616}
1617
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001618// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001619void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001620 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1621 llvm::SmallVector<QualType, 16> ArgTys;
1622 ArgTys.push_back(Context->getPointerType(
1623 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001624 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001625 &ArgTys[0], ArgTys.size(),
1626 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001627 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001628 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001629 SelGetProtoIdent, getFuncType,
1630 FunctionDecl::Extern, false, 0);
1631}
1632
Steve Naroffb29b4272008-04-14 22:03:09 +00001633void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001634 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001635 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001636 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001637 return;
1638 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001639 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001640}
1641
Steve Naroffc0a123c2008-03-11 17:37:02 +00001642// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001643void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001644 if (SuperContructorFunctionDecl)
1645 return;
1646 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1647 llvm::SmallVector<QualType, 16> ArgTys;
1648 QualType argT = Context->getObjCIdType();
1649 assert(!argT.isNull() && "Can't find 'id' type");
1650 ArgTys.push_back(argT);
1651 ArgTys.push_back(argT);
1652 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1653 &ArgTys[0], ArgTys.size(),
1654 false);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001655 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001656 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001657 msgSendIdent, msgSendType,
1658 FunctionDecl::Extern, false, 0);
1659}
1660
Steve Naroff09b266e2007-10-30 23:14:51 +00001661// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001662void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001663 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1664 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001665 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001666 assert(!argT.isNull() && "Can't find 'id' type");
1667 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001668 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001669 assert(!argT.isNull() && "Can't find 'SEL' type");
1670 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001671 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001672 &ArgTys[0], ArgTys.size(),
1673 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001674 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001675 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001676 msgSendIdent, msgSendType,
1677 FunctionDecl::Extern, false, 0);
1678}
1679
Steve Naroff874e2322007-11-15 10:28:18 +00001680// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001681void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001682 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1683 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001684 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001685 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001686 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001687 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1688 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1689 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001690 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001691 assert(!argT.isNull() && "Can't find 'SEL' type");
1692 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001693 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001694 &ArgTys[0], ArgTys.size(),
1695 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001696 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001697 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001698 msgSendIdent, msgSendType,
1699 FunctionDecl::Extern, false, 0);
1700}
1701
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001702// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001703void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001704 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1705 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001706 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001707 assert(!argT.isNull() && "Can't find 'id' type");
1708 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001709 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001710 assert(!argT.isNull() && "Can't find 'SEL' type");
1711 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001712 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001713 &ArgTys[0], ArgTys.size(),
1714 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001715 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001716 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001717 msgSendIdent, msgSendType,
1718 FunctionDecl::Extern, false, 0);
1719}
1720
1721// SynthMsgSendSuperStretFunctionDecl -
1722// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001723void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001724 IdentifierInfo *msgSendIdent =
1725 &Context->Idents.get("objc_msgSendSuper_stret");
1726 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001727 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001728 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001729 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001730 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1731 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1732 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001733 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001734 assert(!argT.isNull() && "Can't find 'SEL' type");
1735 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001736 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001737 &ArgTys[0], ArgTys.size(),
1738 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001739 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001740 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001741 msgSendIdent, msgSendType,
1742 FunctionDecl::Extern, false, 0);
1743}
1744
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001745// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001746void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001747 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1748 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001749 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001750 assert(!argT.isNull() && "Can't find 'id' type");
1751 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001752 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001753 assert(!argT.isNull() && "Can't find 'SEL' type");
1754 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001755 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001756 &ArgTys[0], ArgTys.size(),
1757 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001758 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001759 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001760 msgSendIdent, msgSendType,
1761 FunctionDecl::Extern, false, 0);
1762}
1763
Steve Naroff09b266e2007-10-30 23:14:51 +00001764// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001765void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001766 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1767 llvm::SmallVector<QualType, 16> ArgTys;
1768 ArgTys.push_back(Context->getPointerType(
1769 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001770 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001771 &ArgTys[0], ArgTys.size(),
1772 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001773 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001774 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001775 getClassIdent, getClassType,
1776 FunctionDecl::Extern, false, 0);
1777}
1778
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001779// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001780void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001781 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1782 llvm::SmallVector<QualType, 16> ArgTys;
1783 ArgTys.push_back(Context->getPointerType(
1784 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001785 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001786 &ArgTys[0], ArgTys.size(),
1787 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001788 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001789 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001790 getClassIdent, getClassType,
1791 FunctionDecl::Extern, false, 0);
1792}
1793
Steve Naroffb29b4272008-04-14 22:03:09 +00001794Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001795 QualType strType = getConstantStringStructType();
1796
1797 std::string S = "__NSConstantStringImpl_";
1798 S += utostr(NumObjCStringLiterals++);
1799
Steve Naroffba92b2e2008-03-27 22:29:16 +00001800 Preamble += "static __NSConstantStringImpl " + S;
1801 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1802 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001803 // The pretty printer for StringLiteral handles escape characters properly.
1804 std::ostringstream prettyBuf;
1805 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001806 Preamble += prettyBuf.str();
1807 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001808 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001809 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001810
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001811 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001812 &Context->Idents.get(S.c_str()), strType,
1813 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001814 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1815 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1816 Context->getPointerType(DRE->getType()),
1817 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001818 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001819 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001820 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001821 delete Exp;
1822 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001823}
1824
Steve Naroffb29b4272008-04-14 22:03:09 +00001825ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001826 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001827 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1828
1829 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1830 if (!CE) return 0;
1831
1832 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1833 if (!DRE) return 0;
1834
1835 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1836 if (!PVD) return 0;
1837
1838 if (strcmp(PVD->getName(), "self") != 0)
1839 return 0;
1840
1841 // is this id<P1..> type?
1842 if (CE->getType()->isObjCQualifiedIdType())
1843 return 0;
1844 const PointerType *PT = CE->getType()->getAsPointerType();
1845 if (!PT) return 0;
1846
1847 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1848 if (!IT) return 0;
1849
1850 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1851 return 0;
1852
1853 return IT->getDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001854}
1855
1856// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001857QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001858 if (!SuperStructDecl) {
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001859 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001860 SourceLocation(),
1861 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001862 QualType FieldTypes[2];
1863
1864 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001865 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001866 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001867 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001868 // Create fields
1869 FieldDecl *FieldDecls[2];
1870
1871 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001872 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001873 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001874
1875 SuperStructDecl->defineBody(FieldDecls, 4);
1876 }
1877 return Context->getTagDeclType(SuperStructDecl);
1878}
1879
Steve Naroffb29b4272008-04-14 22:03:09 +00001880QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001881 if (!ConstantStringDecl) {
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001882 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001883 SourceLocation(),
1884 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001885 QualType FieldTypes[4];
1886
1887 // struct objc_object *receiver;
1888 FieldTypes[0] = Context->getObjCIdType();
1889 // int flags;
1890 FieldTypes[1] = Context->IntTy;
1891 // char *str;
1892 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1893 // long length;
1894 FieldTypes[3] = Context->LongTy;
1895 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001896 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001897
1898 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001899 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001900 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001901
1902 ConstantStringDecl->defineBody(FieldDecls, 4);
1903 }
1904 return Context->getTagDeclType(ConstantStringDecl);
1905}
1906
Steve Naroffb29b4272008-04-14 22:03:09 +00001907Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001908 if (!SelGetUidFunctionDecl)
1909 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001910 if (!MsgSendFunctionDecl)
1911 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001912 if (!MsgSendSuperFunctionDecl)
1913 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001914 if (!MsgSendStretFunctionDecl)
1915 SynthMsgSendStretFunctionDecl();
1916 if (!MsgSendSuperStretFunctionDecl)
1917 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001918 if (!MsgSendFpretFunctionDecl)
1919 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001920 if (!GetClassFunctionDecl)
1921 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001922 if (!GetMetaClassFunctionDecl)
1923 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001924
Steve Naroff874e2322007-11-15 10:28:18 +00001925 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001926 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1927 // May need to use objc_msgSend_stret() as well.
1928 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001929 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001930 QualType resultType = mDecl->getResultType();
1931 if (resultType.getCanonicalType()->isStructureType()
1932 || resultType.getCanonicalType()->isUnionType())
1933 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001934 else if (resultType.getCanonicalType()->isRealFloatingType())
1935 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001936 }
Steve Naroff874e2322007-11-15 10:28:18 +00001937
Steve Naroff934f2762007-10-24 22:48:43 +00001938 // Synthesize a call to objc_msgSend().
1939 llvm::SmallVector<Expr*, 8> MsgExprs;
1940 IdentifierInfo *clsName = Exp->getClassName();
1941
1942 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1943 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001944 if (!strcmp(clsName->getName(), "super")) {
1945 MsgSendFlavor = MsgSendSuperFunctionDecl;
1946 if (MsgSendStretFlavor)
1947 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1948 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1949
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001950 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001951 CurMethodDecl->getClassInterface()->getSuperClass();
1952
1953 llvm::SmallVector<Expr*, 4> InitExprs;
1954
1955 // set the receiver to self, the first argument to all methods.
1956 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001957 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001958 SourceLocation()));
1959 llvm::SmallVector<Expr*, 8> ClsExprs;
1960 QualType argType = Context->getPointerType(Context->CharTy);
1961 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1962 SuperDecl->getIdentifier()->getLength(),
1963 false, argType, SourceLocation(),
1964 SourceLocation()));
1965 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1966 &ClsExprs[0],
1967 ClsExprs.size());
1968 // To turn off a warning, type-cast to 'id'
1969 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001970 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001971 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1972 // struct objc_super
1973 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001974 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001975
Steve Naroff23f41272008-03-11 18:14:26 +00001976 if (LangOpts.Microsoft) {
1977 SynthSuperContructorFunctionDecl();
1978 // Simulate a contructor call...
1979 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1980 superType, SourceLocation());
1981 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1982 superType, SourceLocation());
1983 } else {
1984 // (struct objc_super) { <exprs from above> }
1985 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1986 &InitExprs[0], InitExprs.size(),
1987 SourceLocation());
1988 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1989 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001990 // struct objc_super *
1991 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1992 Context->getPointerType(SuperRep->getType()),
1993 SourceLocation());
1994 MsgExprs.push_back(Unop);
1995 } else {
1996 llvm::SmallVector<Expr*, 8> ClsExprs;
1997 QualType argType = Context->getPointerType(Context->CharTy);
1998 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1999 clsName->getLength(),
2000 false, argType, SourceLocation(),
2001 SourceLocation()));
2002 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2003 &ClsExprs[0],
2004 ClsExprs.size());
2005 MsgExprs.push_back(Cls);
2006 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002007 } else { // instance message.
2008 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002009
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002010 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002011 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002012 if (MsgSendStretFlavor)
2013 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002014 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2015
2016 llvm::SmallVector<Expr*, 4> InitExprs;
2017
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002018 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002019 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002020 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002021
2022 llvm::SmallVector<Expr*, 8> ClsExprs;
2023 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002024 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2025 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002026 false, argType, SourceLocation(),
2027 SourceLocation()));
2028 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002029 &ClsExprs[0],
2030 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002031 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002032 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002033 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002034 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002035 // struct objc_super
2036 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002037 Expr *SuperRep;
2038
2039 if (LangOpts.Microsoft) {
2040 SynthSuperContructorFunctionDecl();
2041 // Simulate a contructor call...
2042 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2043 superType, SourceLocation());
2044 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2045 superType, SourceLocation());
2046 } else {
2047 // (struct objc_super) { <exprs from above> }
2048 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2049 &InitExprs[0], InitExprs.size(),
2050 SourceLocation());
2051 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2052 }
Steve Naroff874e2322007-11-15 10:28:18 +00002053 // struct objc_super *
2054 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2055 Context->getPointerType(SuperRep->getType()),
2056 SourceLocation());
2057 MsgExprs.push_back(Unop);
2058 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002059 // Remove all type-casts because it may contain objc-style types; e.g.
2060 // Foo<Proto> *.
2061 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2062 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002063 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002064 MsgExprs.push_back(recExpr);
2065 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002066 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002067 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002068 llvm::SmallVector<Expr*, 8> SelExprs;
2069 QualType argType = Context->getPointerType(Context->CharTy);
2070 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2071 Exp->getSelector().getName().size(),
2072 false, argType, SourceLocation(),
2073 SourceLocation()));
2074 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2075 &SelExprs[0], SelExprs.size());
2076 MsgExprs.push_back(SelExp);
2077
2078 // Now push any user supplied arguments.
2079 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002080 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002081 // Make all implicit casts explicit...ICE comes in handy:-)
2082 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2083 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002084 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2085 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002086 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002087 }
2088 // Make id<P...> cast into an 'id' cast.
2089 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002090 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002091 while ((CE = dyn_cast<CastExpr>(userExpr)))
2092 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002093 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002094 userExpr, SourceLocation());
2095 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002096 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002097 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002098 // We've transferred the ownership to MsgExprs. Null out the argument in
2099 // the original expression, since we will delete it below.
2100 Exp->setArg(i, 0);
2101 }
Steve Naroffab972d32007-11-04 22:37:50 +00002102 // Generate the funky cast.
2103 CastExpr *cast;
2104 llvm::SmallVector<QualType, 8> ArgTypes;
2105 QualType returnType;
2106
2107 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002108 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2109 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2110 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002111 ArgTypes.push_back(Context->getObjCIdType());
2112 ArgTypes.push_back(Context->getObjCSelType());
2113 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002114 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002115 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002116 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2117 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002118 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002119 ArgTypes.push_back(t);
2120 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002121 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2122 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002123 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002124 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002125 }
2126 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002127 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002128
2129 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002130 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2131 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002132
2133 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2134 // If we don't do this cast, we get the following bizarre warning/note:
2135 // xx.m:13: warning: function called through a non-compatible type
2136 // xx.m:13: note: if this code is reached, the program will abort
2137 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2138 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002139
Steve Naroffab972d32007-11-04 22:37:50 +00002140 // Now do the "normal" pointer to function cast.
2141 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002142 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002143 // If we don't have a method decl, force a variadic cast.
2144 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002145 castType = Context->getPointerType(castType);
2146 cast = new CastExpr(castType, cast, SourceLocation());
2147
2148 // Don't forget the parens to enforce the proper binding.
2149 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2150
2151 const FunctionType *FT = msgSendType->getAsFunctionType();
2152 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2153 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002154 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002155 if (MsgSendStretFlavor) {
2156 // We have the method which returns a struct/union. Must also generate
2157 // call to objc_msgSend_stret and hang both varieties on a conditional
2158 // expression which dictate which one to envoke depending on size of
2159 // method's return type.
2160
2161 // Create a reference to the objc_msgSend_stret() declaration.
2162 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2163 SourceLocation());
2164 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2165 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2166 SourceLocation());
2167 // Now do the "normal" pointer to function cast.
2168 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002169 &ArgTypes[0], ArgTypes.size(),
2170 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002171 castType = Context->getPointerType(castType);
2172 cast = new CastExpr(castType, cast, SourceLocation());
2173
2174 // Don't forget the parens to enforce the proper binding.
2175 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2176
2177 FT = msgSendType->getAsFunctionType();
2178 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2179 FT->getResultType(), SourceLocation());
2180
2181 // Build sizeof(returnType)
2182 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2183 returnType, Context->getSizeType(),
2184 SourceLocation(), SourceLocation());
2185 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2186 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2187 // For X86 it is more complicated and some kind of target specific routine
2188 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002189 unsigned IntSize =
2190 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002191 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2192 Context->IntTy,
2193 SourceLocation());
2194 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2195 BinaryOperator::LE,
2196 Context->IntTy,
2197 SourceLocation());
2198 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2199 ConditionalOperator *CondExpr =
2200 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002201 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002202 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002203 return ReplacingStmt;
2204}
2205
Steve Naroffb29b4272008-04-14 22:03:09 +00002206Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002207 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002208 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002209 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002210
Chris Lattnere64b7772007-10-24 16:57:36 +00002211 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002212 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002213}
2214
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002215/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2216/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002217Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002218 if (!GetProtocolFunctionDecl)
2219 SynthGetProtocolFunctionDecl();
2220 // Create a call to objc_getProtocol("ProtocolName").
2221 llvm::SmallVector<Expr*, 8> ProtoExprs;
2222 QualType argType = Context->getPointerType(Context->CharTy);
2223 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2224 strlen(Exp->getProtocol()->getName()),
2225 false, argType, SourceLocation(),
2226 SourceLocation()));
2227 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2228 &ProtoExprs[0],
2229 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002230 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002231 delete Exp;
2232 return ProtoExp;
2233
2234}
2235
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002236/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002237/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002238void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002239 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002240 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2241 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002242 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002243 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002244 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002245 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002246 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002247 SourceLocation LocStart = CDecl->getLocStart();
2248 SourceLocation LocEnd = CDecl->getLocEnd();
2249
2250 const char *startBuf = SM->getCharacterData(LocStart);
2251 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002252 // If no ivars and no root or if its root, directly or indirectly,
2253 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002254 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2255 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002256 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002257 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002258 return;
2259 }
2260
2261 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002262 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002263 Result += "\nstruct ";
2264 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002265 if (LangOpts.Microsoft)
2266 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002267
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002268 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002269 const char *cursor = strchr(startBuf, '{');
2270 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002271 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002272
2273 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002274 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002275 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002276 Result = "\n struct ";
2277 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002278 Result += "_IMPL ";
2279 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002280 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002281
2282 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002283 SourceLocation OnePastCurly =
2284 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2285 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002286 }
2287 cursor++; // past '{'
2288
2289 // Now comment out any visibility specifiers.
2290 while (cursor < endBuf) {
2291 if (*cursor == '@') {
2292 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002293 // Skip whitespace.
2294 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2295 /*scan*/;
2296
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002297 // FIXME: presence of @public, etc. inside comment results in
2298 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002299 if (!strncmp(cursor, "public", strlen("public")) ||
2300 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002301 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002302 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002303 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002304 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002305 // FIXME: If there are cases where '<' is used in ivar declaration part
2306 // of user code, then scan the ivar list and use needToScanForQualifiers
2307 // for type checking.
2308 else if (*cursor == '<') {
2309 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002310 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002311 cursor = strchr(cursor, '>');
2312 cursor++;
2313 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002314 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002315 }
Steve Narofffea763e82007-11-14 19:25:57 +00002316 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002317 }
Steve Narofffea763e82007-11-14 19:25:57 +00002318 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002319 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002320 } else { // we don't have any instance variables - insert super struct.
2321 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2322 Result += " {\n struct ";
2323 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002324 Result += "_IMPL ";
2325 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002326 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002327 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002328 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002329 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002330 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002331 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002332}
2333
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002334// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002335/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002336void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002337 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002338 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002339 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002340 const char *ClassName,
2341 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002342 if (MethodBegin == MethodEnd) return;
2343
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002344 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002345 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002346 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002347 SEL _cmd;
2348 char *method_types;
2349 void *_imp;
2350 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002351 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002352 Result += "\nstruct _objc_method {\n";
2353 Result += "\tSEL _cmd;\n";
2354 Result += "\tchar *method_types;\n";
2355 Result += "\tvoid *_imp;\n";
2356 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002357
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002358 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002359 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002360
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002361 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002362
2363 /* struct {
2364 struct _objc_method_list *next_method;
2365 int method_count;
2366 struct _objc_method method_list[];
2367 }
2368 */
2369 Result += "\nstatic struct {\n";
2370 Result += "\tstruct _objc_method_list *next_method;\n";
2371 Result += "\tint method_count;\n";
2372 Result += "\tstruct _objc_method method_list[";
2373 Result += utostr(MethodEnd-MethodBegin);
2374 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002375 Result += prefix;
2376 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2377 Result += "_METHODS_";
2378 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002379 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002380 Result += IsInstanceMethod ? "inst" : "cls";
2381 Result += "_meth\")))= ";
2382 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002383
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002384 Result += "\t,{{(SEL)\"";
2385 Result += (*MethodBegin)->getSelector().getName().c_str();
2386 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002387 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002388 Result += "\", \"";
2389 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002390 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002391 Result += MethodInternalNames[*MethodBegin];
2392 Result += "}\n";
2393 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2394 Result += "\t ,{(SEL)\"";
2395 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002396 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002397 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002398 Result += "\", \"";
2399 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002400 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002401 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002402 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002403 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002404 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002405}
2406
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002407/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Steve Naroffb29b4272008-04-14 22:03:09 +00002408void RewriteObjC::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002409 int NumProtocols,
2410 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002411 const char *ClassName,
2412 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002413 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002414 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002415 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002416 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002417 // Output struct protocol_methods holder of method selector and type.
Chris Lattnerc8581052008-03-16 20:19:15 +00002418 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002419 /* struct protocol_methods {
2420 SEL _cmd;
2421 char *method_types;
2422 }
2423 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002424 Result += "\nstruct protocol_methods {\n";
2425 Result += "\tSEL _cmd;\n";
2426 Result += "\tchar *method_types;\n";
2427 Result += "};\n";
2428
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002429 objc_protocol_methods = true;
2430 }
Steve Narofffbfe8252008-05-06 18:26:51 +00002431 // Do not synthesize the protocol more than once.
2432 if (ObjCSynthesizedProtocols.count(PDecl))
2433 continue;
2434
Chris Lattnerc8581052008-03-16 20:19:15 +00002435 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2436 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002437 /* struct _objc_protocol_method_list {
2438 int protocol_method_count;
2439 struct protocol_methods protocols[];
2440 }
2441 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002442 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002443 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002444 Result += "\tstruct protocol_methods protocols[";
2445 Result += utostr(NumMethods);
2446 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002447 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002448 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002449 "{\n\t" + utostr(NumMethods) + "\n";
2450
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002451 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002452 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002453 E = PDecl->instmeth_end(); I != E; ++I) {
2454 if (I == PDecl->instmeth_begin())
2455 Result += "\t ,{{(SEL)\"";
2456 else
2457 Result += "\t ,{(SEL)\"";
2458 Result += (*I)->getSelector().getName().c_str();
2459 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002460 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002461 Result += "\", \"";
2462 Result += MethodTypeString;
2463 Result += "\"}\n";
2464 }
2465 Result += "\t }\n};\n";
2466 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002467
2468 // Output class methods declared in this protocol.
Chris Lattnerc8581052008-03-16 20:19:15 +00002469 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002470 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002471 /* struct _objc_protocol_method_list {
2472 int protocol_method_count;
2473 struct protocol_methods protocols[];
2474 }
2475 */
2476 Result += "\nstatic struct {\n";
2477 Result += "\tint protocol_method_count;\n";
2478 Result += "\tstruct protocol_methods protocols[";
2479 Result += utostr(NumMethods);
2480 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002481 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002482 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002483 "{\n\t";
2484 Result += utostr(NumMethods);
2485 Result += "\n";
2486
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002487 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002488 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002489 E = PDecl->classmeth_end(); I != E; ++I) {
2490 if (I == PDecl->classmeth_begin())
2491 Result += "\t ,{{(SEL)\"";
2492 else
2493 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002494 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002495 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002496 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002497 Result += "\", \"";
2498 Result += MethodTypeString;
2499 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002500 }
2501 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002502 }
Steve Narofffbfe8252008-05-06 18:26:51 +00002503
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002504 // Output:
2505 /* struct _objc_protocol {
2506 // Objective-C 1.0 extensions
2507 struct _objc_protocol_extension *isa;
2508 char *protocol_name;
2509 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002510 struct _objc_protocol_method_list *instance_methods;
2511 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002512 };
2513 */
2514 static bool objc_protocol = false;
2515 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002516 Result += "\nstruct _objc_protocol {\n";
2517 Result += "\tstruct _objc_protocol_extension *isa;\n";
2518 Result += "\tchar *protocol_name;\n";
2519 Result += "\tstruct _objc_protocol **protocol_list;\n";
2520 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2521 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2522 Result += "};\n";
2523
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002524 objc_protocol = true;
2525 }
2526
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002527 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2528 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002529 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002530 "{\n\t0, \"";
2531 Result += PDecl->getName();
2532 Result += "\", 0, ";
Chris Lattnerc8581052008-03-16 20:19:15 +00002533 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002534 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002535 Result += PDecl->getName();
2536 Result += ", ";
2537 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002538 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002539 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002540 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002541 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002542 Result += PDecl->getName();
2543 Result += "\n";
2544 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002545 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002546 Result += "0\n";
2547 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002548
2549 // Mark this protocol as having been generated.
2550 if (!ObjCSynthesizedProtocols.insert(PDecl))
2551 assert(false && "protocol already synthesized");
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002552 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002553 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002554 /* struct _objc_protocol_list {
2555 struct _objc_protocol_list *next;
2556 int protocol_count;
2557 struct _objc_protocol *class_protocols[];
2558 }
2559 */
2560 Result += "\nstatic struct {\n";
2561 Result += "\tstruct _objc_protocol_list *next;\n";
2562 Result += "\tint protocol_count;\n";
2563 Result += "\tstruct _objc_protocol *class_protocols[";
2564 Result += utostr(NumProtocols);
2565 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002566 Result += prefix;
2567 Result += "_PROTOCOLS_";
2568 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002569 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002570 "{\n\t0, ";
2571 Result += utostr(NumProtocols);
2572 Result += "\n";
2573
2574 Result += "\t,{&_OBJC_PROTOCOL_";
2575 Result += Protocols[0]->getName();
2576 Result += " \n";
2577
2578 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002579 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Narofffa8ec622008-04-18 22:15:15 +00002580 Result += "\t ,&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002581 Result += PDecl->getName();
2582 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002583 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002584 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002585 }
2586}
2587
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002588/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002589/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002590void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002591 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002592 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002593 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002594 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002595 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2596 CDecl = CDecl->getNextClassCategory())
2597 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2598 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002599
Chris Lattnereb44eee2007-12-23 01:40:15 +00002600 std::string FullCategoryName = ClassDecl->getName();
2601 FullCategoryName += '_';
2602 FullCategoryName += IDecl->getName();
2603
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002604 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002605 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002606 true, "CATEGORY_", FullCategoryName.c_str(),
2607 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002608
2609 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002610 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002611 false, "CATEGORY_", FullCategoryName.c_str(),
2612 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002613
2614 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002615 // Null CDecl is case of a category implementation with no category interface
2616 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002617 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002618 CDecl->getNumReferencedProtocols(),
2619 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002620 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002621
2622 /* struct _objc_category {
2623 char *category_name;
2624 char *class_name;
2625 struct _objc_method_list *instance_methods;
2626 struct _objc_method_list *class_methods;
2627 struct _objc_protocol_list *protocols;
2628 // Objective-C 1.0 extensions
2629 uint32_t size; // sizeof (struct _objc_category)
2630 struct _objc_property_list *instance_properties; // category's own
2631 // @property decl.
2632 };
2633 */
2634
2635 static bool objc_category = false;
2636 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002637 Result += "\nstruct _objc_category {\n";
2638 Result += "\tchar *category_name;\n";
2639 Result += "\tchar *class_name;\n";
2640 Result += "\tstruct _objc_method_list *instance_methods;\n";
2641 Result += "\tstruct _objc_method_list *class_methods;\n";
2642 Result += "\tstruct _objc_protocol_list *protocols;\n";
2643 Result += "\tunsigned int size;\n";
2644 Result += "\tstruct _objc_property_list *instance_properties;\n";
2645 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002646 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002647 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002648 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2649 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002650 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002651 Result += IDecl->getName();
2652 Result += "\"\n\t, \"";
2653 Result += ClassDecl->getName();
2654 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002655
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002656 if (IDecl->getNumInstanceMethods() > 0) {
2657 Result += "\t, (struct _objc_method_list *)"
2658 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2659 Result += FullCategoryName;
2660 Result += "\n";
2661 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002662 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002663 Result += "\t, 0\n";
2664 if (IDecl->getNumClassMethods() > 0) {
2665 Result += "\t, (struct _objc_method_list *)"
2666 "&_OBJC_CATEGORY_CLASS_METHODS_";
2667 Result += FullCategoryName;
2668 Result += "\n";
2669 }
2670 else
2671 Result += "\t, 0\n";
2672
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002673 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002674 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2675 Result += FullCategoryName;
2676 Result += "\n";
2677 }
2678 else
2679 Result += "\t, 0\n";
2680 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002681}
2682
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002683/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2684/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002685void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002686 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002687 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002688 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002689 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002690 if (LangOpts.Microsoft)
2691 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002692 Result += ", ";
2693 Result += ivar->getName();
2694 Result += ")";
2695}
2696
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002697//===----------------------------------------------------------------------===//
2698// Meta Data Emission
2699//===----------------------------------------------------------------------===//
2700
Steve Naroffb29b4272008-04-14 22:03:09 +00002701void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002702 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002703 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002704
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002705 // Explictly declared @interface's are already synthesized.
2706 if (CDecl->ImplicitInterfaceDecl()) {
2707 // FIXME: Implementation of a class with no @interface (legacy) doese not
2708 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002709 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002710 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002711
Chris Lattnerbe6df082007-12-12 07:56:42 +00002712 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002713 unsigned NumIvars = !IDecl->ivar_empty()
2714 ? IDecl->ivar_size()
2715 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002716 if (NumIvars > 0) {
2717 static bool objc_ivar = false;
2718 if (!objc_ivar) {
2719 /* struct _objc_ivar {
2720 char *ivar_name;
2721 char *ivar_type;
2722 int ivar_offset;
2723 };
2724 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002725 Result += "\nstruct _objc_ivar {\n";
2726 Result += "\tchar *ivar_name;\n";
2727 Result += "\tchar *ivar_type;\n";
2728 Result += "\tint ivar_offset;\n";
2729 Result += "};\n";
2730
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002731 objc_ivar = true;
2732 }
2733
Steve Naroff946a6932008-03-11 00:12:29 +00002734 /* struct {
2735 int ivar_count;
2736 struct _objc_ivar ivar_list[nIvars];
2737 };
2738 */
2739 Result += "\nstatic struct {\n";
2740 Result += "\tint ivar_count;\n";
2741 Result += "\tstruct _objc_ivar ivar_list[";
2742 Result += utostr(NumIvars);
2743 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002744 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002745 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002746 "{\n\t";
2747 Result += utostr(NumIvars);
2748 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002749
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002750 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002751 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002752 IVI = IDecl->ivar_begin();
2753 IVE = IDecl->ivar_end();
2754 } else {
2755 IVI = CDecl->ivar_begin();
2756 IVE = CDecl->ivar_end();
2757 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002758 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002759 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002760 Result += "\", \"";
2761 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002762 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2763 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002764 Result += StrEncoding;
2765 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002766 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002767 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002768 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002769 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002770 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002771 Result += "\", \"";
2772 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002773 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2774 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002775 Result += StrEncoding;
2776 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002777 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002778 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002779 }
2780
2781 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002782 }
2783
2784 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002785 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002786 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002787
2788 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002789 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002790 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002791
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002792 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002793 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002794 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002795 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002796
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002797
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002798 // Declaration of class/meta-class metadata
2799 /* struct _objc_class {
2800 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002801 const char *super_class_name;
2802 char *name;
2803 long version;
2804 long info;
2805 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002806 struct _objc_ivar_list *ivars;
2807 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002808 struct objc_cache *cache;
2809 struct objc_protocol_list *protocols;
2810 const char *ivar_layout;
2811 struct _objc_class_ext *ext;
2812 };
2813 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002814 static bool objc_class = false;
2815 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002816 Result += "\nstruct _objc_class {\n";
2817 Result += "\tstruct _objc_class *isa;\n";
2818 Result += "\tconst char *super_class_name;\n";
2819 Result += "\tchar *name;\n";
2820 Result += "\tlong version;\n";
2821 Result += "\tlong info;\n";
2822 Result += "\tlong instance_size;\n";
2823 Result += "\tstruct _objc_ivar_list *ivars;\n";
2824 Result += "\tstruct _objc_method_list *methods;\n";
2825 Result += "\tstruct objc_cache *cache;\n";
2826 Result += "\tstruct _objc_protocol_list *protocols;\n";
2827 Result += "\tconst char *ivar_layout;\n";
2828 Result += "\tstruct _objc_class_ext *ext;\n";
2829 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002830 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002831 }
2832
2833 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002834 ObjCInterfaceDecl *RootClass = 0;
2835 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002836 while (SuperClass) {
2837 RootClass = SuperClass;
2838 SuperClass = SuperClass->getSuperClass();
2839 }
2840 SuperClass = CDecl->getSuperClass();
2841
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002842 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2843 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002844 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002845 "{\n\t(struct _objc_class *)\"";
2846 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2847 Result += "\"";
2848
2849 if (SuperClass) {
2850 Result += ", \"";
2851 Result += SuperClass->getName();
2852 Result += "\", \"";
2853 Result += CDecl->getName();
2854 Result += "\"";
2855 }
2856 else {
2857 Result += ", 0, \"";
2858 Result += CDecl->getName();
2859 Result += "\"";
2860 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002861 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002862 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002863 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002864 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002865 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002866 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002867 Result += "\n";
2868 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002869 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002870 Result += ", 0\n";
2871 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002872 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002873 Result += CDecl->getName();
2874 Result += ",0,0\n";
2875 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002876 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002877 Result += "\t,0,0,0,0\n";
2878 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002879
2880 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002881 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2882 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002883 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002884 "{\n\t&_OBJC_METACLASS_";
2885 Result += CDecl->getName();
2886 if (SuperClass) {
2887 Result += ", \"";
2888 Result += SuperClass->getName();
2889 Result += "\", \"";
2890 Result += CDecl->getName();
2891 Result += "\"";
2892 }
2893 else {
2894 Result += ", 0, \"";
2895 Result += CDecl->getName();
2896 Result += "\"";
2897 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002898 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002899 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002900 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002901 Result += ",0";
2902 else {
2903 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002904 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002905 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002906 if (LangOpts.Microsoft)
2907 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002908 Result += ")";
2909 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002910 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002911 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002912 Result += CDecl->getName();
2913 Result += "\n\t";
2914 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002915 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002916 Result += ",0";
2917 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002918 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002919 Result += CDecl->getName();
2920 Result += ", 0\n\t";
2921 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002922 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002923 Result += ",0,0";
2924 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002925 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002926 Result += CDecl->getName();
2927 Result += ", 0,0\n";
2928 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002929 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002930 Result += ",0,0,0\n";
2931 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002932}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002933
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002934/// RewriteImplementations - This routine rewrites all method implementations
2935/// and emits meta-data.
2936
Steve Naroffb29b4272008-04-14 22:03:09 +00002937void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002938 int ClsDefCount = ClassImplementation.size();
2939 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002940
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002941 if (ClsDefCount == 0 && CatDefCount == 0)
2942 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002943 // Rewrite implemented methods
2944 for (int i = 0; i < ClsDefCount; i++)
2945 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002946
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002947 for (int i = 0; i < CatDefCount; i++)
2948 RewriteImplementationDecl(CategoryImplementation[i]);
2949
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002950 // This is needed for use of offsetof
Steve Naroffb10f2732008-04-04 22:58:22 +00002951 Result += "#define offsetof(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002952 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002953 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002954 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002955
2956 // For each implemented category, write out all its meta data.
2957 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002958 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002959
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002960 // Write objc_symtab metadata
2961 /*
2962 struct _objc_symtab
2963 {
2964 long sel_ref_cnt;
2965 SEL *refs;
2966 short cls_def_cnt;
2967 short cat_def_cnt;
2968 void *defs[cls_def_cnt + cat_def_cnt];
2969 };
2970 */
2971
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002972 Result += "\nstruct _objc_symtab {\n";
2973 Result += "\tlong sel_ref_cnt;\n";
2974 Result += "\tSEL *refs;\n";
2975 Result += "\tshort cls_def_cnt;\n";
2976 Result += "\tshort cat_def_cnt;\n";
2977 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2978 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002979
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002980 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002981 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002982 Result += "\t0, 0, " + utostr(ClsDefCount)
2983 + ", " + utostr(CatDefCount) + "\n";
2984 for (int i = 0; i < ClsDefCount; i++) {
2985 Result += "\t,&_OBJC_CLASS_";
2986 Result += ClassImplementation[i]->getName();
2987 Result += "\n";
2988 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002989
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002990 for (int i = 0; i < CatDefCount; i++) {
2991 Result += "\t,&_OBJC_CATEGORY_";
2992 Result += CategoryImplementation[i]->getClassInterface()->getName();
2993 Result += "_";
2994 Result += CategoryImplementation[i]->getName();
2995 Result += "\n";
2996 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002997
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002998 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002999
3000 // Write objc_module metadata
3001
3002 /*
3003 struct _objc_module {
3004 long version;
3005 long size;
3006 const char *name;
3007 struct _objc_symtab *symtab;
3008 }
3009 */
3010
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003011 Result += "\nstruct _objc_module {\n";
3012 Result += "\tlong version;\n";
3013 Result += "\tlong size;\n";
3014 Result += "\tconst char *name;\n";
3015 Result += "\tstruct _objc_symtab *symtab;\n";
3016 Result += "};\n\n";
3017 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003018 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003019 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3020 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003021 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003022
3023 if (LangOpts.Microsoft) {
3024 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
3025 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
3026 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3027 Result += "&_OBJC_MODULES;\n";
3028 Result += "#pragma data_seg(pop)\n\n";
3029 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003030}
Chris Lattner311ff022007-10-16 22:36:42 +00003031
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003032