blob: 5473e28499d13c418dba6b0aa51671c81342d4f1 [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 Naroff1284db82008-05-08 22:02:18 +0000320 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000321 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000322 Preamble += "__OBJC_RW_EXTERN struct 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()) {
Steve Narofff0757612008-05-08 17:52:16 +0000819 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
820 // lookup which class implements the instance variable.
821 ObjCInterfaceDecl *clsDeclared = 0;
822 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
823 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
824
825 // Synthesize an explicit cast to gain access to the ivar.
826 std::string RecName = clsDeclared->getIdentifier()->getName();
827 RecName += "_IMPL";
828 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
829 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
830 SourceLocation(), II, 0);
831 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
832 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
833 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
834 // Don't forget the parens to enforce the proper binding.
835 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
836 if (IV->isFreeIvar() &&
837 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
838 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
839 ReplaceStmt(IV, ME);
840 delete IV;
841 return ME;
842 } else {
843 ReplaceStmt(IV->getBase(), PE);
844 // 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 }
Steve Naroff84472a82008-04-18 21:55:08 +0000851 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000852 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
853
854 // Explicit ivar refs need to have a cast inserted.
855 // FIXME: consider sharing some of this code with the code above.
856 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000857 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000858 // lookup which class implements the instance variable.
859 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000860 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000861 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
862
863 // Synthesize an explicit cast to gain access to the ivar.
864 std::string RecName = clsDeclared->getIdentifier()->getName();
865 RecName += "_IMPL";
866 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
867 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
868 SourceLocation(), II, 0);
869 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
870 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
871 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
872 // Don't forget the parens to enforce the proper binding.
873 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
874 ReplaceStmt(IV->getBase(), PE);
875 // Cannot delete IV->getBase(), since PE points to it.
876 // Replace the old base with the cast. This is important when doing
877 // embedded rewrites. For example, [newInv->_container addObject:0].
878 IV->setBase(PE);
879 return IV;
880 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000881 }
Steve Naroff84472a82008-04-18 21:55:08 +0000882 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000883}
884
Chris Lattnerf04da132007-10-24 17:06:59 +0000885//===----------------------------------------------------------------------===//
886// Function Body / Expression rewriting
887//===----------------------------------------------------------------------===//
888
Steve Naroffb29b4272008-04-14 22:03:09 +0000889Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000890 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
891 isa<DoStmt>(S) || isa<ForStmt>(S))
892 Stmts.push_back(S);
893 else if (isa<ObjCForCollectionStmt>(S)) {
894 Stmts.push_back(S);
895 ObjCBcLabelNo.push_back(++BcLabelCount);
896 }
897
Chris Lattner338d1e22008-01-31 05:10:40 +0000898 SourceLocation OrigStmtEnd = S->getLocEnd();
899
900 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000901 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
902 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000903 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000904 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000905 if (newStmt)
906 *CI = newStmt;
907 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000908
909 // Handle specific things.
910 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
911 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000912
913 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
914 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000915
916 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
917 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000918
Steve Naroffbeaf2992007-11-03 11:27:19 +0000919 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
920 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000921
Steve Naroff934f2762007-10-24 22:48:43 +0000922 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
923 // Before we rewrite it, put the original message expression in a comment.
924 SourceLocation startLoc = MessExpr->getLocStart();
925 SourceLocation endLoc = MessExpr->getLocEnd();
926
927 const char *startBuf = SM->getCharacterData(startLoc);
928 const char *endBuf = SM->getCharacterData(endLoc);
929
930 std::string messString;
931 messString += "// ";
932 messString.append(startBuf, endBuf-startBuf+1);
933 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000934
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000935 // FIXME: Missing definition of
936 // InsertText(clang::SourceLocation, char const*, unsigned int).
937 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000938 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000939 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000940 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000941 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000942
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000943 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
944 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000945
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000946 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
947 return RewriteObjCSynchronizedStmt(StmtTry);
948
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000949 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
950 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000951
952 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
953 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000954
955 if (ObjCForCollectionStmt *StmtForCollection =
956 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000957 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000958 if (BreakStmt *StmtBreakStmt =
959 dyn_cast<BreakStmt>(S))
960 return RewriteBreakStmt(StmtBreakStmt);
961 if (ContinueStmt *StmtContinueStmt =
962 dyn_cast<ContinueStmt>(S))
963 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000964
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000965 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
966 isa<DoStmt>(S) || isa<ForStmt>(S)) {
967 assert(!Stmts.empty() && "Statement stack is empty");
968 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
969 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
970 && "Statement stack mismatch");
971 Stmts.pop_back();
972 }
Steve Naroff874e2322007-11-15 10:28:18 +0000973#if 0
974 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
975 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
976 // Get the new text.
977 std::ostringstream Buf;
978 Replacement->printPretty(Buf);
979 const std::string &Str = Buf.str();
980
981 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000982 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000983 delete S;
984 return Replacement;
985 }
986#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000987 // Return this stmt unmodified.
988 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000989}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000990
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000991/// SynthCountByEnumWithState - To print:
992/// ((unsigned int (*)
993/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
994/// (void *)objc_msgSend)((id)l_collection,
995/// sel_registerName(
996/// "countByEnumeratingWithState:objects:count:"),
997/// &enumState,
998/// (id *)items, (unsigned int)16)
999///
Steve Naroffb29b4272008-04-14 22:03:09 +00001000void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001001 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1002 "id *, unsigned int))(void *)objc_msgSend)";
1003 buf += "\n\t\t";
1004 buf += "((id)l_collection,\n\t\t";
1005 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1006 buf += "\n\t\t";
1007 buf += "&enumState, "
1008 "(id *)items, (unsigned int)16)";
1009}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001010
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001011/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1012/// statement to exit to its outer synthesized loop.
1013///
Steve Naroffb29b4272008-04-14 22:03:09 +00001014Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001015 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1016 return S;
1017 // replace break with goto __break_label
1018 std::string buf;
1019
1020 SourceLocation startLoc = S->getLocStart();
1021 buf = "goto __break_label_";
1022 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001023 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001024
1025 return 0;
1026}
1027
1028/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1029/// statement to continue with its inner synthesized loop.
1030///
Steve Naroffb29b4272008-04-14 22:03:09 +00001031Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001032 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1033 return S;
1034 // replace continue with goto __continue_label
1035 std::string buf;
1036
1037 SourceLocation startLoc = S->getLocStart();
1038 buf = "goto __continue_label_";
1039 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001040 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001041
1042 return 0;
1043}
1044
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001045/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001046/// It rewrites:
1047/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001048
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001049/// Into:
1050/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001051/// type elem;
1052/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001053/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001054/// id l_collection = (id)collection;
1055/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1056/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001057/// if (limit) {
1058/// unsigned long startMutations = *enumState.mutationsPtr;
1059/// do {
1060/// unsigned long counter = 0;
1061/// do {
1062/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001063/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001064/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001065/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001066/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001067/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001068/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1069/// objects:items count:16]);
1070/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001071/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001072/// }
1073/// else
1074/// elem = nil;
1075/// }
1076///
Steve Naroffb29b4272008-04-14 22:03:09 +00001077Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001078 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001079 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1080 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1081 "ObjCForCollectionStmt Statement stack mismatch");
1082 assert(!ObjCBcLabelNo.empty() &&
1083 "ObjCForCollectionStmt - Label No stack empty");
1084
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001085 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001086 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001087 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001088 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001089 std::string buf;
1090 buf = "\n{\n\t";
1091 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1092 // type elem;
1093 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001094 elementTypeAsString = ElementType.getAsString();
1095 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001096 buf += " ";
1097 elementName = DS->getDecl()->getName();
1098 buf += elementName;
1099 buf += ";\n\t";
1100 }
Chris Lattner06767512008-04-08 05:52:18 +00001101 else {
1102 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001103 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001104 elementTypeAsString = DR->getDecl()->getType().getAsString();
1105 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001106
1107 // struct __objcFastEnumerationState enumState = { 0 };
1108 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1109 // id items[16];
1110 buf += "id items[16];\n\t";
1111 // id l_collection = (id)
1112 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001113 // Find start location of 'collection' the hard way!
1114 const char *startCollectionBuf = startBuf;
1115 startCollectionBuf += 3; // skip 'for'
1116 startCollectionBuf = strchr(startCollectionBuf, '(');
1117 startCollectionBuf++; // skip '('
1118 // find 'in' and skip it.
1119 while (*startCollectionBuf != ' ' ||
1120 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1121 (*(startCollectionBuf+3) != ' ' &&
1122 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1123 startCollectionBuf++;
1124 startCollectionBuf += 3;
1125
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001126 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001127 ReplaceText(startLoc, startCollectionBuf - startBuf,
1128 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001129 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001130 SourceLocation rightParenLoc = S->getRParenLoc();
1131 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1132 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001133 buf = ";\n\t";
1134
1135 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1136 // objects:items count:16];
1137 // which is synthesized into:
1138 // unsigned int limit =
1139 // ((unsigned int (*)
1140 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1141 // (void *)objc_msgSend)((id)l_collection,
1142 // sel_registerName(
1143 // "countByEnumeratingWithState:objects:count:"),
1144 // (struct __objcFastEnumerationState *)&state,
1145 // (id *)items, (unsigned int)16);
1146 buf += "unsigned long limit =\n\t\t";
1147 SynthCountByEnumWithState(buf);
1148 buf += ";\n\t";
1149 /// if (limit) {
1150 /// unsigned long startMutations = *enumState.mutationsPtr;
1151 /// do {
1152 /// unsigned long counter = 0;
1153 /// do {
1154 /// if (startMutations != *enumState.mutationsPtr)
1155 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001156 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001157 buf += "if (limit) {\n\t";
1158 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1159 buf += "do {\n\t\t";
1160 buf += "unsigned long counter = 0;\n\t\t";
1161 buf += "do {\n\t\t\t";
1162 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1163 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1164 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001165 buf += " = (";
1166 buf += elementTypeAsString;
1167 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001168 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001169 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001170
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001171 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001172 /// } while (counter < limit);
1173 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1174 /// objects:items count:16]);
1175 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001176 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001177 /// }
1178 /// else
1179 /// elem = nil;
1180 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001181 ///
1182 buf = ";\n\t";
1183 buf += "__continue_label_";
1184 buf += utostr(ObjCBcLabelNo.back());
1185 buf += ": ;";
1186 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001187 buf += "} while (counter < limit);\n\t";
1188 buf += "} while (limit = ";
1189 SynthCountByEnumWithState(buf);
1190 buf += ");\n\t";
1191 buf += elementName;
1192 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001193 buf += "__break_label_";
1194 buf += utostr(ObjCBcLabelNo.back());
1195 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001196 buf += "}\n\t";
1197 buf += "else\n\t\t";
1198 buf += elementName;
1199 buf += " = nil;\n";
1200 buf += "}\n";
1201 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001202 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001203 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001204 Stmts.pop_back();
1205 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001206 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001207}
1208
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001209/// RewriteObjCSynchronizedStmt -
1210/// This routine rewrites @synchronized(expr) stmt;
1211/// into:
1212/// objc_sync_enter(expr);
1213/// @try stmt @finally { objc_sync_exit(expr); }
1214///
Steve Naroffb29b4272008-04-14 22:03:09 +00001215Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001216 // Get the start location and compute the semi location.
1217 SourceLocation startLoc = S->getLocStart();
1218 const char *startBuf = SM->getCharacterData(startLoc);
1219
1220 assert((*startBuf == '@') && "bogus @synchronized location");
1221
1222 std::string buf;
1223 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001224 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001225 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1226 const char *endBuf = SM->getCharacterData(endLoc);
1227 endBuf++;
1228 const char *rparenBuf = strchr(endBuf, ')');
1229 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1230 buf = ");\n";
1231 // declare a new scope with two variables, _stack and _rethrow.
1232 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1233 buf += "int buf[18/*32-bit i386*/];\n";
1234 buf += "char *pointers[4];} _stack;\n";
1235 buf += "id volatile _rethrow = 0;\n";
1236 buf += "objc_exception_try_enter(&_stack);\n";
1237 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001238 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001239 startLoc = S->getSynchBody()->getLocEnd();
1240 startBuf = SM->getCharacterData(startLoc);
1241
1242 assert((*startBuf == '}') && "bogus @try block");
1243 SourceLocation lastCurlyLoc = startLoc;
1244 buf = "}\nelse {\n";
1245 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1246 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1247 // FIXME: This must be objc_sync_exit(syncExpr);
1248 buf += " objc_sync_exit();\n";
1249 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1250 buf += "}\n";
1251 buf += "}";
1252
Chris Lattneraadaf782008-01-31 19:51:04 +00001253 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001254 return 0;
1255}
1256
Steve Naroffb29b4272008-04-14 22:03:09 +00001257Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001258 // Get the start location and compute the semi location.
1259 SourceLocation startLoc = S->getLocStart();
1260 const char *startBuf = SM->getCharacterData(startLoc);
1261
1262 assert((*startBuf == '@') && "bogus @try location");
1263
1264 std::string buf;
1265 // declare a new scope with two variables, _stack and _rethrow.
1266 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1267 buf += "int buf[18/*32-bit i386*/];\n";
1268 buf += "char *pointers[4];} _stack;\n";
1269 buf += "id volatile _rethrow = 0;\n";
1270 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001271 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001272
Chris Lattneraadaf782008-01-31 19:51:04 +00001273 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001274
1275 startLoc = S->getTryBody()->getLocEnd();
1276 startBuf = SM->getCharacterData(startLoc);
1277
1278 assert((*startBuf == '}') && "bogus @try block");
1279
1280 SourceLocation lastCurlyLoc = startLoc;
1281
1282 startLoc = startLoc.getFileLocWithOffset(1);
1283 buf = " /* @catch begin */ else {\n";
1284 buf += " id _caught = objc_exception_extract(&_stack);\n";
1285 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001286 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001287 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1288 buf += " else { /* @catch continue */";
1289
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001290 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001291
1292 bool sawIdTypedCatch = false;
1293 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001294 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001295 while (catchList) {
1296 Stmt *catchStmt = catchList->getCatchParamStmt();
1297
1298 if (catchList == S->getCatchStmts())
1299 buf = "if ("; // we are generating code for the first catch clause
1300 else
1301 buf = "else if (";
1302 startLoc = catchList->getLocStart();
1303 startBuf = SM->getCharacterData(startLoc);
1304
1305 assert((*startBuf == '@') && "bogus @catch location");
1306
1307 const char *lParenLoc = strchr(startBuf, '(');
1308
Steve Naroffbe4b3332008-02-01 22:08:12 +00001309 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001310 // Now rewrite the body...
1311 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001312 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1313 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001314 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1315 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001316 assert((*bodyBuf == '{') && "bogus @catch body location");
1317
1318 buf += "1) { id _tmp = _caught;";
1319 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1320 buf.c_str(), buf.size());
1321 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001322 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001323 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001324 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001325 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001326 sawIdTypedCatch = true;
1327 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001328 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001329
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001330 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001331 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001332 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001333 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001334 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001335 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001336 }
1337 }
1338 // Now rewrite the body...
1339 lastCatchBody = catchList->getCatchBody();
1340 SourceLocation rParenLoc = catchList->getRParenLoc();
1341 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1342 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1343 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1344 assert((*rParenBuf == ')') && "bogus @catch paren location");
1345 assert((*bodyBuf == '{') && "bogus @catch body location");
1346
1347 buf = " = _caught;";
1348 // Here we replace ") {" with "= _caught;" (which initializes and
1349 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001350 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001351 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001352 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001353 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001354 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001355 catchList = catchList->getNextCatchStmt();
1356 }
1357 // Complete the catch list...
1358 if (lastCatchBody) {
1359 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001360 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1361 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001362 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1363 buf = " } } /* @catch end */\n";
1364
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001365 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001366
1367 // Set lastCurlyLoc
1368 lastCurlyLoc = lastCatchBody->getLocEnd();
1369 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001370 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001371 startLoc = finalStmt->getLocStart();
1372 startBuf = SM->getCharacterData(startLoc);
1373 assert((*startBuf == '@') && "bogus @finally start");
1374
1375 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001376 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001377
1378 Stmt *body = finalStmt->getFinallyBody();
1379 SourceLocation startLoc = body->getLocStart();
1380 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001381 assert(*SM->getCharacterData(startLoc) == '{' &&
1382 "bogus @finally body location");
1383 assert(*SM->getCharacterData(endLoc) == '}' &&
1384 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001385
1386 startLoc = startLoc.getFileLocWithOffset(1);
1387 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001388 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001389 endLoc = endLoc.getFileLocWithOffset(-1);
1390 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001391 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001392
1393 // Set lastCurlyLoc
1394 lastCurlyLoc = body->getLocEnd();
1395 }
1396 // Now emit the final closing curly brace...
1397 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1398 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001399 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001400 return 0;
1401}
1402
Steve Naroffb29b4272008-04-14 22:03:09 +00001403Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001404 return 0;
1405}
1406
Steve Naroffb29b4272008-04-14 22:03:09 +00001407Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001408 return 0;
1409}
1410
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001411// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001412// the throw expression is typically a message expression that's already
1413// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001414Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001415 // Get the start location and compute the semi location.
1416 SourceLocation startLoc = S->getLocStart();
1417 const char *startBuf = SM->getCharacterData(startLoc);
1418
1419 assert((*startBuf == '@') && "bogus @throw location");
1420
1421 std::string buf;
1422 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001423 if (S->getThrowExpr())
1424 buf = "objc_exception_throw(";
1425 else // add an implicit argument
1426 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001427 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001428 const char *semiBuf = strchr(startBuf, ';');
1429 assert((*semiBuf == ';') && "@throw: can't find ';'");
1430 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1431 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001432 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001433 return 0;
1434}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001435
Steve Naroffb29b4272008-04-14 22:03:09 +00001436Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001437 // Create a new string expression.
1438 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001439 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001440 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1441 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001442 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1443 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001444 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001445 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001446
Chris Lattner07506182007-11-30 22:53:43 +00001447 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001448 delete Exp;
1449 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001450}
1451
Steve Naroffb29b4272008-04-14 22:03:09 +00001452Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001453 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1454 // Create a call to sel_registerName("selName").
1455 llvm::SmallVector<Expr*, 8> SelExprs;
1456 QualType argType = Context->getPointerType(Context->CharTy);
1457 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1458 Exp->getSelector().getName().size(),
1459 false, argType, SourceLocation(),
1460 SourceLocation()));
1461 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1462 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001463 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001464 delete Exp;
1465 return SelExp;
1466}
1467
Steve Naroffb29b4272008-04-14 22:03:09 +00001468CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001469 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001470 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001471 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001472
1473 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001474 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001475
1476 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001477 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001478 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1479
1480 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001481
Steve Naroff934f2762007-10-24 22:48:43 +00001482 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1483}
1484
Steve Naroffd5255f52007-11-01 13:24:47 +00001485static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1486 const char *&startRef, const char *&endRef) {
1487 while (startBuf < endBuf) {
1488 if (*startBuf == '<')
1489 startRef = startBuf; // mark the start.
1490 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001491 if (startRef && *startRef == '<') {
1492 endRef = startBuf; // mark the end.
1493 return true;
1494 }
1495 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001496 }
1497 startBuf++;
1498 }
1499 return false;
1500}
1501
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001502static void scanToNextArgument(const char *&argRef) {
1503 int angle = 0;
1504 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1505 if (*argRef == '<')
1506 angle++;
1507 else if (*argRef == '>')
1508 angle--;
1509 argRef++;
1510 }
1511 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1512}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001513
Steve Naroffb29b4272008-04-14 22:03:09 +00001514bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001515
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001516 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001517 return true;
1518
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001519 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001520 return true;
1521
Steve Naroffd5255f52007-11-01 13:24:47 +00001522 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001523 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001524 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001525 return true; // we have "Class <Protocol> *".
1526 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001527 return false;
1528}
1529
Steve Naroffb29b4272008-04-14 22:03:09 +00001530void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001531 SourceLocation Loc;
1532 QualType Type;
1533 const FunctionTypeProto *proto = 0;
1534 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1535 Loc = VD->getLocation();
1536 Type = VD->getType();
1537 }
1538 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1539 Loc = FD->getLocation();
1540 // Check for ObjC 'id' and class types that have been adorned with protocol
1541 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1542 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1543 assert(funcType && "missing function type");
1544 proto = dyn_cast<FunctionTypeProto>(funcType);
1545 if (!proto)
1546 return;
1547 Type = proto->getResultType();
1548 }
1549 else
1550 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001551
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001552 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001553 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001554
1555 const char *endBuf = SM->getCharacterData(Loc);
1556 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001557 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001558 startBuf--; // scan backward (from the decl location) for return type.
1559 const char *startRef = 0, *endRef = 0;
1560 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1561 // Get the locations of the startRef, endRef.
1562 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1563 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1564 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001565 InsertText(LessLoc, "/*", 2);
1566 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001567 }
1568 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001569 if (!proto)
1570 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001571 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001572 const char *startBuf = SM->getCharacterData(Loc);
1573 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001574 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1575 if (needToScanForQualifiers(proto->getArgType(i))) {
1576 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001577
Steve Naroffd5255f52007-11-01 13:24:47 +00001578 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001579 // scan forward (from the decl location) for argument types.
1580 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001581 const char *startRef = 0, *endRef = 0;
1582 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1583 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001584 SourceLocation LessLoc =
1585 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1586 SourceLocation GreaterLoc =
1587 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001588 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001589 InsertText(LessLoc, "/*", 2);
1590 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001591 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001592 startBuf = ++endBuf;
1593 }
1594 else {
1595 while (*startBuf != ')' && *startBuf != ',')
1596 startBuf++; // scan forward (from the decl location) for argument types.
1597 startBuf++;
1598 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001599 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001600}
1601
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001602// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001603void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001604 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1605 llvm::SmallVector<QualType, 16> ArgTys;
1606 ArgTys.push_back(Context->getPointerType(
1607 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001608 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001609 &ArgTys[0], ArgTys.size(),
1610 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001611 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001612 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001613 SelGetUidIdent, getFuncType,
1614 FunctionDecl::Extern, false, 0);
1615}
1616
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001617// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001618void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001619 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1620 llvm::SmallVector<QualType, 16> ArgTys;
1621 ArgTys.push_back(Context->getPointerType(
1622 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001623 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001624 &ArgTys[0], ArgTys.size(),
1625 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001626 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001627 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001628 SelGetProtoIdent, getFuncType,
1629 FunctionDecl::Extern, false, 0);
1630}
1631
Steve Naroffb29b4272008-04-14 22:03:09 +00001632void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001633 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001634 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001635 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001636 return;
1637 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001638 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001639}
1640
Steve Naroffc0a123c2008-03-11 17:37:02 +00001641// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001642void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001643 if (SuperContructorFunctionDecl)
1644 return;
1645 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1646 llvm::SmallVector<QualType, 16> ArgTys;
1647 QualType argT = Context->getObjCIdType();
1648 assert(!argT.isNull() && "Can't find 'id' type");
1649 ArgTys.push_back(argT);
1650 ArgTys.push_back(argT);
1651 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1652 &ArgTys[0], ArgTys.size(),
1653 false);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001654 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001655 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001656 msgSendIdent, msgSendType,
1657 FunctionDecl::Extern, false, 0);
1658}
1659
Steve Naroff09b266e2007-10-30 23:14:51 +00001660// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001661void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001662 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1663 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001664 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001665 assert(!argT.isNull() && "Can't find 'id' type");
1666 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001667 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001668 assert(!argT.isNull() && "Can't find 'SEL' type");
1669 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001670 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001671 &ArgTys[0], ArgTys.size(),
1672 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001673 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001674 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001675 msgSendIdent, msgSendType,
1676 FunctionDecl::Extern, false, 0);
1677}
1678
Steve Naroff874e2322007-11-15 10:28:18 +00001679// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001680void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001681 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1682 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001683 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001684 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001685 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001686 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1687 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1688 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001689 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001690 assert(!argT.isNull() && "Can't find 'SEL' type");
1691 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001692 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001693 &ArgTys[0], ArgTys.size(),
1694 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001695 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001696 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001697 msgSendIdent, msgSendType,
1698 FunctionDecl::Extern, false, 0);
1699}
1700
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001701// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001702void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001703 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1704 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001705 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001706 assert(!argT.isNull() && "Can't find 'id' type");
1707 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001708 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001709 assert(!argT.isNull() && "Can't find 'SEL' type");
1710 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001711 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001712 &ArgTys[0], ArgTys.size(),
1713 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001714 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001715 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001716 msgSendIdent, msgSendType,
1717 FunctionDecl::Extern, false, 0);
1718}
1719
1720// SynthMsgSendSuperStretFunctionDecl -
1721// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001722void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001723 IdentifierInfo *msgSendIdent =
1724 &Context->Idents.get("objc_msgSendSuper_stret");
1725 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001726 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001727 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001728 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001729 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1730 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1731 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001732 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001733 assert(!argT.isNull() && "Can't find 'SEL' type");
1734 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001735 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001736 &ArgTys[0], ArgTys.size(),
1737 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001738 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001739 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001740 msgSendIdent, msgSendType,
1741 FunctionDecl::Extern, false, 0);
1742}
1743
Steve Naroff1284db82008-05-08 22:02:18 +00001744// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001745void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001746 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1747 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001748 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001749 assert(!argT.isNull() && "Can't find 'id' type");
1750 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001751 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001752 assert(!argT.isNull() && "Can't find 'SEL' type");
1753 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001754 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001755 &ArgTys[0], ArgTys.size(),
1756 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001757 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001758 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001759 msgSendIdent, msgSendType,
1760 FunctionDecl::Extern, false, 0);
1761}
1762
Steve Naroff09b266e2007-10-30 23:14:51 +00001763// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001764void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001765 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1766 llvm::SmallVector<QualType, 16> ArgTys;
1767 ArgTys.push_back(Context->getPointerType(
1768 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001769 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001770 &ArgTys[0], ArgTys.size(),
1771 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001772 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001773 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001774 getClassIdent, getClassType,
1775 FunctionDecl::Extern, false, 0);
1776}
1777
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001778// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001779void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001780 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1781 llvm::SmallVector<QualType, 16> ArgTys;
1782 ArgTys.push_back(Context->getPointerType(
1783 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001784 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001785 &ArgTys[0], ArgTys.size(),
1786 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001787 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001788 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001789 getClassIdent, getClassType,
1790 FunctionDecl::Extern, false, 0);
1791}
1792
Steve Naroffb29b4272008-04-14 22:03:09 +00001793Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001794 QualType strType = getConstantStringStructType();
1795
1796 std::string S = "__NSConstantStringImpl_";
1797 S += utostr(NumObjCStringLiterals++);
1798
Steve Naroffba92b2e2008-03-27 22:29:16 +00001799 Preamble += "static __NSConstantStringImpl " + S;
1800 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1801 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001802 // The pretty printer for StringLiteral handles escape characters properly.
1803 std::ostringstream prettyBuf;
1804 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001805 Preamble += prettyBuf.str();
1806 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001807 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001808 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001809
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001810 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001811 &Context->Idents.get(S.c_str()), strType,
1812 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001813 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1814 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1815 Context->getPointerType(DRE->getType()),
1816 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001817 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001818 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001819 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001820 delete Exp;
1821 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001822}
1823
Steve Naroffb29b4272008-04-14 22:03:09 +00001824ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001825 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001826 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1827
1828 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1829 if (!CE) return 0;
1830
1831 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1832 if (!DRE) return 0;
1833
1834 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1835 if (!PVD) return 0;
1836
1837 if (strcmp(PVD->getName(), "self") != 0)
1838 return 0;
1839
1840 // is this id<P1..> type?
1841 if (CE->getType()->isObjCQualifiedIdType())
1842 return 0;
1843 const PointerType *PT = CE->getType()->getAsPointerType();
1844 if (!PT) return 0;
1845
1846 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1847 if (!IT) return 0;
1848
1849 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1850 return 0;
1851
1852 return IT->getDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001853}
1854
1855// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001856QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001857 if (!SuperStructDecl) {
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001858 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001859 SourceLocation(),
1860 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001861 QualType FieldTypes[2];
1862
1863 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001864 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001865 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001866 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001867 // Create fields
1868 FieldDecl *FieldDecls[2];
1869
1870 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001871 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001872 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001873
1874 SuperStructDecl->defineBody(FieldDecls, 4);
1875 }
1876 return Context->getTagDeclType(SuperStructDecl);
1877}
1878
Steve Naroffb29b4272008-04-14 22:03:09 +00001879QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001880 if (!ConstantStringDecl) {
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001881 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001882 SourceLocation(),
1883 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001884 QualType FieldTypes[4];
1885
1886 // struct objc_object *receiver;
1887 FieldTypes[0] = Context->getObjCIdType();
1888 // int flags;
1889 FieldTypes[1] = Context->IntTy;
1890 // char *str;
1891 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1892 // long length;
1893 FieldTypes[3] = Context->LongTy;
1894 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001895 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001896
1897 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001898 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001899 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001900
1901 ConstantStringDecl->defineBody(FieldDecls, 4);
1902 }
1903 return Context->getTagDeclType(ConstantStringDecl);
1904}
1905
Steve Naroffb29b4272008-04-14 22:03:09 +00001906Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001907 if (!SelGetUidFunctionDecl)
1908 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001909 if (!MsgSendFunctionDecl)
1910 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001911 if (!MsgSendSuperFunctionDecl)
1912 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001913 if (!MsgSendStretFunctionDecl)
1914 SynthMsgSendStretFunctionDecl();
1915 if (!MsgSendSuperStretFunctionDecl)
1916 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001917 if (!MsgSendFpretFunctionDecl)
1918 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001919 if (!GetClassFunctionDecl)
1920 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001921 if (!GetMetaClassFunctionDecl)
1922 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001923
Steve Naroff874e2322007-11-15 10:28:18 +00001924 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001925 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1926 // May need to use objc_msgSend_stret() as well.
1927 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001928 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001929 QualType resultType = mDecl->getResultType();
1930 if (resultType.getCanonicalType()->isStructureType()
1931 || resultType.getCanonicalType()->isUnionType())
1932 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001933 else if (resultType.getCanonicalType()->isRealFloatingType())
1934 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001935 }
Steve Naroff874e2322007-11-15 10:28:18 +00001936
Steve Naroff934f2762007-10-24 22:48:43 +00001937 // Synthesize a call to objc_msgSend().
1938 llvm::SmallVector<Expr*, 8> MsgExprs;
1939 IdentifierInfo *clsName = Exp->getClassName();
1940
1941 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1942 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001943 if (!strcmp(clsName->getName(), "super")) {
1944 MsgSendFlavor = MsgSendSuperFunctionDecl;
1945 if (MsgSendStretFlavor)
1946 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1947 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1948
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001949 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001950 CurMethodDecl->getClassInterface()->getSuperClass();
1951
1952 llvm::SmallVector<Expr*, 4> InitExprs;
1953
1954 // set the receiver to self, the first argument to all methods.
1955 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001956 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001957 SourceLocation()));
1958 llvm::SmallVector<Expr*, 8> ClsExprs;
1959 QualType argType = Context->getPointerType(Context->CharTy);
1960 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1961 SuperDecl->getIdentifier()->getLength(),
1962 false, argType, SourceLocation(),
1963 SourceLocation()));
1964 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1965 &ClsExprs[0],
1966 ClsExprs.size());
1967 // To turn off a warning, type-cast to 'id'
1968 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001969 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001970 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1971 // struct objc_super
1972 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001973 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001974
Steve Naroff23f41272008-03-11 18:14:26 +00001975 if (LangOpts.Microsoft) {
1976 SynthSuperContructorFunctionDecl();
1977 // Simulate a contructor call...
1978 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1979 superType, SourceLocation());
1980 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1981 superType, SourceLocation());
1982 } else {
1983 // (struct objc_super) { <exprs from above> }
1984 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1985 &InitExprs[0], InitExprs.size(),
1986 SourceLocation());
1987 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1988 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001989 // struct objc_super *
1990 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1991 Context->getPointerType(SuperRep->getType()),
1992 SourceLocation());
1993 MsgExprs.push_back(Unop);
1994 } else {
1995 llvm::SmallVector<Expr*, 8> ClsExprs;
1996 QualType argType = Context->getPointerType(Context->CharTy);
1997 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1998 clsName->getLength(),
1999 false, argType, SourceLocation(),
2000 SourceLocation()));
2001 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2002 &ClsExprs[0],
2003 ClsExprs.size());
2004 MsgExprs.push_back(Cls);
2005 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002006 } else { // instance message.
2007 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002008
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002009 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002010 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002011 if (MsgSendStretFlavor)
2012 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002013 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2014
2015 llvm::SmallVector<Expr*, 4> InitExprs;
2016
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002017 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002018 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002019 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002020
2021 llvm::SmallVector<Expr*, 8> ClsExprs;
2022 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002023 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2024 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002025 false, argType, SourceLocation(),
2026 SourceLocation()));
2027 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002028 &ClsExprs[0],
2029 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002030 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002031 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002032 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002033 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002034 // struct objc_super
2035 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002036 Expr *SuperRep;
2037
2038 if (LangOpts.Microsoft) {
2039 SynthSuperContructorFunctionDecl();
2040 // Simulate a contructor call...
2041 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2042 superType, SourceLocation());
2043 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2044 superType, SourceLocation());
2045 } else {
2046 // (struct objc_super) { <exprs from above> }
2047 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2048 &InitExprs[0], InitExprs.size(),
2049 SourceLocation());
2050 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2051 }
Steve Naroff874e2322007-11-15 10:28:18 +00002052 // struct objc_super *
2053 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2054 Context->getPointerType(SuperRep->getType()),
2055 SourceLocation());
2056 MsgExprs.push_back(Unop);
2057 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002058 // Remove all type-casts because it may contain objc-style types; e.g.
2059 // Foo<Proto> *.
2060 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2061 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002062 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002063 MsgExprs.push_back(recExpr);
2064 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002065 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002066 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002067 llvm::SmallVector<Expr*, 8> SelExprs;
2068 QualType argType = Context->getPointerType(Context->CharTy);
2069 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2070 Exp->getSelector().getName().size(),
2071 false, argType, SourceLocation(),
2072 SourceLocation()));
2073 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2074 &SelExprs[0], SelExprs.size());
2075 MsgExprs.push_back(SelExp);
2076
2077 // Now push any user supplied arguments.
2078 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002079 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002080 // Make all implicit casts explicit...ICE comes in handy:-)
2081 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2082 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002083 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2084 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002085 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002086 }
2087 // Make id<P...> cast into an 'id' cast.
2088 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002089 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002090 while ((CE = dyn_cast<CastExpr>(userExpr)))
2091 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002092 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002093 userExpr, SourceLocation());
2094 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002095 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002096 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002097 // We've transferred the ownership to MsgExprs. Null out the argument in
2098 // the original expression, since we will delete it below.
2099 Exp->setArg(i, 0);
2100 }
Steve Naroffab972d32007-11-04 22:37:50 +00002101 // Generate the funky cast.
2102 CastExpr *cast;
2103 llvm::SmallVector<QualType, 8> ArgTypes;
2104 QualType returnType;
2105
2106 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002107 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2108 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2109 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002110 ArgTypes.push_back(Context->getObjCIdType());
2111 ArgTypes.push_back(Context->getObjCSelType());
2112 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002113 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002114 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002115 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2116 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002117 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002118 ArgTypes.push_back(t);
2119 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002120 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2121 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002122 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002123 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002124 }
2125 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002126 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002127
2128 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002129 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2130 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002131
2132 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2133 // If we don't do this cast, we get the following bizarre warning/note:
2134 // xx.m:13: warning: function called through a non-compatible type
2135 // xx.m:13: note: if this code is reached, the program will abort
2136 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2137 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002138
Steve Naroffab972d32007-11-04 22:37:50 +00002139 // Now do the "normal" pointer to function cast.
2140 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002141 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002142 // If we don't have a method decl, force a variadic cast.
2143 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002144 castType = Context->getPointerType(castType);
2145 cast = new CastExpr(castType, cast, SourceLocation());
2146
2147 // Don't forget the parens to enforce the proper binding.
2148 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2149
2150 const FunctionType *FT = msgSendType->getAsFunctionType();
2151 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2152 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002153 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002154 if (MsgSendStretFlavor) {
2155 // We have the method which returns a struct/union. Must also generate
2156 // call to objc_msgSend_stret and hang both varieties on a conditional
2157 // expression which dictate which one to envoke depending on size of
2158 // method's return type.
2159
2160 // Create a reference to the objc_msgSend_stret() declaration.
2161 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2162 SourceLocation());
2163 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2164 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2165 SourceLocation());
2166 // Now do the "normal" pointer to function cast.
2167 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002168 &ArgTypes[0], ArgTypes.size(),
2169 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002170 castType = Context->getPointerType(castType);
2171 cast = new CastExpr(castType, cast, SourceLocation());
2172
2173 // Don't forget the parens to enforce the proper binding.
2174 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2175
2176 FT = msgSendType->getAsFunctionType();
2177 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2178 FT->getResultType(), SourceLocation());
2179
2180 // Build sizeof(returnType)
2181 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2182 returnType, Context->getSizeType(),
2183 SourceLocation(), SourceLocation());
2184 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2185 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2186 // For X86 it is more complicated and some kind of target specific routine
2187 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002188 unsigned IntSize =
2189 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002190 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2191 Context->IntTy,
2192 SourceLocation());
2193 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2194 BinaryOperator::LE,
2195 Context->IntTy,
2196 SourceLocation());
2197 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2198 ConditionalOperator *CondExpr =
2199 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002200 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002201 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002202 return ReplacingStmt;
2203}
2204
Steve Naroffb29b4272008-04-14 22:03:09 +00002205Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002206 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002207 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002208 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002209
Chris Lattnere64b7772007-10-24 16:57:36 +00002210 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002211 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002212}
2213
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002214/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2215/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002216Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002217 if (!GetProtocolFunctionDecl)
2218 SynthGetProtocolFunctionDecl();
2219 // Create a call to objc_getProtocol("ProtocolName").
2220 llvm::SmallVector<Expr*, 8> ProtoExprs;
2221 QualType argType = Context->getPointerType(Context->CharTy);
2222 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2223 strlen(Exp->getProtocol()->getName()),
2224 false, argType, SourceLocation(),
2225 SourceLocation()));
2226 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2227 &ProtoExprs[0],
2228 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002229 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002230 delete Exp;
2231 return ProtoExp;
2232
2233}
2234
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002235/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002236/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002237void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002238 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002239 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2240 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002241 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002242 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002243 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002244 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002245 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002246 SourceLocation LocStart = CDecl->getLocStart();
2247 SourceLocation LocEnd = CDecl->getLocEnd();
2248
2249 const char *startBuf = SM->getCharacterData(LocStart);
2250 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002251 // If no ivars and no root or if its root, directly or indirectly,
2252 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002253 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2254 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002255 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002256 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002257 return;
2258 }
2259
2260 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002261 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002262 Result += "\nstruct ";
2263 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002264 if (LangOpts.Microsoft)
2265 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002266
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002267 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002268 const char *cursor = strchr(startBuf, '{');
2269 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002270 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002271
2272 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002273 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002274 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002275 Result = "\n struct ";
2276 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002277 Result += "_IMPL ";
2278 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002279 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002280
2281 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002282 SourceLocation OnePastCurly =
2283 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2284 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002285 }
2286 cursor++; // past '{'
2287
2288 // Now comment out any visibility specifiers.
2289 while (cursor < endBuf) {
2290 if (*cursor == '@') {
2291 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002292 // Skip whitespace.
2293 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2294 /*scan*/;
2295
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002296 // FIXME: presence of @public, etc. inside comment results in
2297 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002298 if (!strncmp(cursor, "public", strlen("public")) ||
2299 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002300 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002301 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002302 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002303 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002304 // FIXME: If there are cases where '<' is used in ivar declaration part
2305 // of user code, then scan the ivar list and use needToScanForQualifiers
2306 // for type checking.
2307 else if (*cursor == '<') {
2308 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002309 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002310 cursor = strchr(cursor, '>');
2311 cursor++;
2312 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002313 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002314 }
Steve Narofffea763e82007-11-14 19:25:57 +00002315 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002316 }
Steve Narofffea763e82007-11-14 19:25:57 +00002317 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002318 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002319 } else { // we don't have any instance variables - insert super struct.
2320 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2321 Result += " {\n struct ";
2322 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002323 Result += "_IMPL ";
2324 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002325 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002326 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002327 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002328 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002329 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002330 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002331}
2332
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002333// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002334/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002335void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002336 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002337 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002338 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002339 const char *ClassName,
2340 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002341 if (MethodBegin == MethodEnd) return;
2342
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002343 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002344 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002345 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002346 SEL _cmd;
2347 char *method_types;
2348 void *_imp;
2349 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002350 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002351 Result += "\nstruct _objc_method {\n";
2352 Result += "\tSEL _cmd;\n";
2353 Result += "\tchar *method_types;\n";
2354 Result += "\tvoid *_imp;\n";
2355 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002356
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002357 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002358 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002359
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002360 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002361
2362 /* struct {
2363 struct _objc_method_list *next_method;
2364 int method_count;
2365 struct _objc_method method_list[];
2366 }
2367 */
2368 Result += "\nstatic struct {\n";
2369 Result += "\tstruct _objc_method_list *next_method;\n";
2370 Result += "\tint method_count;\n";
2371 Result += "\tstruct _objc_method method_list[";
2372 Result += utostr(MethodEnd-MethodBegin);
2373 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002374 Result += prefix;
2375 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2376 Result += "_METHODS_";
2377 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002378 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002379 Result += IsInstanceMethod ? "inst" : "cls";
2380 Result += "_meth\")))= ";
2381 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002382
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002383 Result += "\t,{{(SEL)\"";
2384 Result += (*MethodBegin)->getSelector().getName().c_str();
2385 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002386 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002387 Result += "\", \"";
2388 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002389 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002390 Result += MethodInternalNames[*MethodBegin];
2391 Result += "}\n";
2392 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2393 Result += "\t ,{(SEL)\"";
2394 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002395 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002396 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002397 Result += "\", \"";
2398 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002399 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002400 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002401 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002402 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002403 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002404}
2405
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002406/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Steve Naroffb29b4272008-04-14 22:03:09 +00002407void RewriteObjC::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002408 int NumProtocols,
2409 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002410 const char *ClassName,
2411 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002412 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002413 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002414 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002415 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002416 // Output struct protocol_methods holder of method selector and type.
Chris Lattnerc8581052008-03-16 20:19:15 +00002417 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002418 /* struct protocol_methods {
2419 SEL _cmd;
2420 char *method_types;
2421 }
2422 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002423 Result += "\nstruct protocol_methods {\n";
2424 Result += "\tSEL _cmd;\n";
2425 Result += "\tchar *method_types;\n";
2426 Result += "};\n";
2427
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002428 objc_protocol_methods = true;
2429 }
Steve Narofffbfe8252008-05-06 18:26:51 +00002430 // Do not synthesize the protocol more than once.
2431 if (ObjCSynthesizedProtocols.count(PDecl))
2432 continue;
2433
Chris Lattnerc8581052008-03-16 20:19:15 +00002434 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2435 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002436 /* struct _objc_protocol_method_list {
2437 int protocol_method_count;
2438 struct protocol_methods protocols[];
2439 }
2440 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002441 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002442 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002443 Result += "\tstruct protocol_methods protocols[";
2444 Result += utostr(NumMethods);
2445 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002446 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002447 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002448 "{\n\t" + utostr(NumMethods) + "\n";
2449
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002450 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002451 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002452 E = PDecl->instmeth_end(); I != E; ++I) {
2453 if (I == PDecl->instmeth_begin())
2454 Result += "\t ,{{(SEL)\"";
2455 else
2456 Result += "\t ,{(SEL)\"";
2457 Result += (*I)->getSelector().getName().c_str();
2458 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002459 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002460 Result += "\", \"";
2461 Result += MethodTypeString;
2462 Result += "\"}\n";
2463 }
2464 Result += "\t }\n};\n";
2465 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002466
2467 // Output class methods declared in this protocol.
Chris Lattnerc8581052008-03-16 20:19:15 +00002468 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002469 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002470 /* struct _objc_protocol_method_list {
2471 int protocol_method_count;
2472 struct protocol_methods protocols[];
2473 }
2474 */
2475 Result += "\nstatic struct {\n";
2476 Result += "\tint protocol_method_count;\n";
2477 Result += "\tstruct protocol_methods protocols[";
2478 Result += utostr(NumMethods);
2479 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002480 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002481 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002482 "{\n\t";
2483 Result += utostr(NumMethods);
2484 Result += "\n";
2485
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002486 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002487 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002488 E = PDecl->classmeth_end(); I != E; ++I) {
2489 if (I == PDecl->classmeth_begin())
2490 Result += "\t ,{{(SEL)\"";
2491 else
2492 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002493 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002494 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002495 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002496 Result += "\", \"";
2497 Result += MethodTypeString;
2498 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002499 }
2500 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002501 }
Steve Narofffbfe8252008-05-06 18:26:51 +00002502
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002503 // Output:
2504 /* struct _objc_protocol {
2505 // Objective-C 1.0 extensions
2506 struct _objc_protocol_extension *isa;
2507 char *protocol_name;
2508 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002509 struct _objc_protocol_method_list *instance_methods;
2510 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002511 };
2512 */
2513 static bool objc_protocol = false;
2514 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002515 Result += "\nstruct _objc_protocol {\n";
2516 Result += "\tstruct _objc_protocol_extension *isa;\n";
2517 Result += "\tchar *protocol_name;\n";
2518 Result += "\tstruct _objc_protocol **protocol_list;\n";
2519 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2520 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2521 Result += "};\n";
2522
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002523 objc_protocol = true;
2524 }
2525
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002526 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2527 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002528 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002529 "{\n\t0, \"";
2530 Result += PDecl->getName();
2531 Result += "\", 0, ";
Chris Lattnerc8581052008-03-16 20:19:15 +00002532 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002533 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002534 Result += PDecl->getName();
2535 Result += ", ";
2536 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002537 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002538 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002539 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002540 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002541 Result += PDecl->getName();
2542 Result += "\n";
2543 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002544 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002545 Result += "0\n";
2546 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002547
2548 // Mark this protocol as having been generated.
2549 if (!ObjCSynthesizedProtocols.insert(PDecl))
2550 assert(false && "protocol already synthesized");
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002551 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002552 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002553 /* struct _objc_protocol_list {
2554 struct _objc_protocol_list *next;
2555 int protocol_count;
2556 struct _objc_protocol *class_protocols[];
2557 }
2558 */
2559 Result += "\nstatic struct {\n";
2560 Result += "\tstruct _objc_protocol_list *next;\n";
2561 Result += "\tint protocol_count;\n";
2562 Result += "\tstruct _objc_protocol *class_protocols[";
2563 Result += utostr(NumProtocols);
2564 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002565 Result += prefix;
2566 Result += "_PROTOCOLS_";
2567 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002568 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002569 "{\n\t0, ";
2570 Result += utostr(NumProtocols);
2571 Result += "\n";
2572
2573 Result += "\t,{&_OBJC_PROTOCOL_";
2574 Result += Protocols[0]->getName();
2575 Result += " \n";
2576
2577 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002578 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Narofffa8ec622008-04-18 22:15:15 +00002579 Result += "\t ,&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002580 Result += PDecl->getName();
2581 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002582 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002583 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002584 }
2585}
2586
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002587/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002588/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002589void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002590 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002591 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002592 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002593 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002594 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2595 CDecl = CDecl->getNextClassCategory())
2596 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2597 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002598
Chris Lattnereb44eee2007-12-23 01:40:15 +00002599 std::string FullCategoryName = ClassDecl->getName();
2600 FullCategoryName += '_';
2601 FullCategoryName += IDecl->getName();
2602
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002603 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002604 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002605 true, "CATEGORY_", FullCategoryName.c_str(),
2606 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002607
2608 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002609 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002610 false, "CATEGORY_", FullCategoryName.c_str(),
2611 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002612
2613 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002614 // Null CDecl is case of a category implementation with no category interface
2615 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002616 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002617 CDecl->getNumReferencedProtocols(),
2618 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002619 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002620
2621 /* struct _objc_category {
2622 char *category_name;
2623 char *class_name;
2624 struct _objc_method_list *instance_methods;
2625 struct _objc_method_list *class_methods;
2626 struct _objc_protocol_list *protocols;
2627 // Objective-C 1.0 extensions
2628 uint32_t size; // sizeof (struct _objc_category)
2629 struct _objc_property_list *instance_properties; // category's own
2630 // @property decl.
2631 };
2632 */
2633
2634 static bool objc_category = false;
2635 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002636 Result += "\nstruct _objc_category {\n";
2637 Result += "\tchar *category_name;\n";
2638 Result += "\tchar *class_name;\n";
2639 Result += "\tstruct _objc_method_list *instance_methods;\n";
2640 Result += "\tstruct _objc_method_list *class_methods;\n";
2641 Result += "\tstruct _objc_protocol_list *protocols;\n";
2642 Result += "\tunsigned int size;\n";
2643 Result += "\tstruct _objc_property_list *instance_properties;\n";
2644 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002645 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002646 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002647 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2648 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002649 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002650 Result += IDecl->getName();
2651 Result += "\"\n\t, \"";
2652 Result += ClassDecl->getName();
2653 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002654
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002655 if (IDecl->getNumInstanceMethods() > 0) {
2656 Result += "\t, (struct _objc_method_list *)"
2657 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2658 Result += FullCategoryName;
2659 Result += "\n";
2660 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002661 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002662 Result += "\t, 0\n";
2663 if (IDecl->getNumClassMethods() > 0) {
2664 Result += "\t, (struct _objc_method_list *)"
2665 "&_OBJC_CATEGORY_CLASS_METHODS_";
2666 Result += FullCategoryName;
2667 Result += "\n";
2668 }
2669 else
2670 Result += "\t, 0\n";
2671
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002672 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002673 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2674 Result += FullCategoryName;
2675 Result += "\n";
2676 }
2677 else
2678 Result += "\t, 0\n";
2679 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002680}
2681
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002682/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2683/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002684void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002685 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002686 std::string &Result) {
Steve Naroff5df5b762008-05-07 21:23:49 +00002687 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002688 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002689 if (LangOpts.Microsoft)
2690 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002691 Result += ", ";
2692 Result += ivar->getName();
2693 Result += ")";
2694}
2695
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002696//===----------------------------------------------------------------------===//
2697// Meta Data Emission
2698//===----------------------------------------------------------------------===//
2699
Steve Naroffb29b4272008-04-14 22:03:09 +00002700void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002701 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002702 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002703
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002704 // Explictly declared @interface's are already synthesized.
2705 if (CDecl->ImplicitInterfaceDecl()) {
2706 // FIXME: Implementation of a class with no @interface (legacy) doese not
2707 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002708 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002709 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002710
Chris Lattnerbe6df082007-12-12 07:56:42 +00002711 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002712 unsigned NumIvars = !IDecl->ivar_empty()
2713 ? IDecl->ivar_size()
2714 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002715 if (NumIvars > 0) {
2716 static bool objc_ivar = false;
2717 if (!objc_ivar) {
2718 /* struct _objc_ivar {
2719 char *ivar_name;
2720 char *ivar_type;
2721 int ivar_offset;
2722 };
2723 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002724 Result += "\nstruct _objc_ivar {\n";
2725 Result += "\tchar *ivar_name;\n";
2726 Result += "\tchar *ivar_type;\n";
2727 Result += "\tint ivar_offset;\n";
2728 Result += "};\n";
2729
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002730 objc_ivar = true;
2731 }
2732
Steve Naroff946a6932008-03-11 00:12:29 +00002733 /* struct {
2734 int ivar_count;
2735 struct _objc_ivar ivar_list[nIvars];
2736 };
2737 */
2738 Result += "\nstatic struct {\n";
2739 Result += "\tint ivar_count;\n";
2740 Result += "\tstruct _objc_ivar ivar_list[";
2741 Result += utostr(NumIvars);
2742 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002743 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002744 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002745 "{\n\t";
2746 Result += utostr(NumIvars);
2747 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002748
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002749 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002750 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002751 IVI = IDecl->ivar_begin();
2752 IVE = IDecl->ivar_end();
2753 } else {
2754 IVI = CDecl->ivar_begin();
2755 IVE = CDecl->ivar_end();
2756 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002757 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002758 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002759 Result += "\", \"";
2760 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002761 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2762 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002763 Result += StrEncoding;
2764 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002765 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002766 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002767 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002768 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002769 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002770 Result += "\", \"";
2771 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002772 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2773 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002774 Result += StrEncoding;
2775 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002776 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002777 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002778 }
2779
2780 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002781 }
2782
2783 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002784 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002785 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002786
2787 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002788 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002789 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002790
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002791 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002792 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002793 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002794 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002795
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002796
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002797 // Declaration of class/meta-class metadata
2798 /* struct _objc_class {
2799 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002800 const char *super_class_name;
2801 char *name;
2802 long version;
2803 long info;
2804 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002805 struct _objc_ivar_list *ivars;
2806 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002807 struct objc_cache *cache;
2808 struct objc_protocol_list *protocols;
2809 const char *ivar_layout;
2810 struct _objc_class_ext *ext;
2811 };
2812 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002813 static bool objc_class = false;
2814 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002815 Result += "\nstruct _objc_class {\n";
2816 Result += "\tstruct _objc_class *isa;\n";
2817 Result += "\tconst char *super_class_name;\n";
2818 Result += "\tchar *name;\n";
2819 Result += "\tlong version;\n";
2820 Result += "\tlong info;\n";
2821 Result += "\tlong instance_size;\n";
2822 Result += "\tstruct _objc_ivar_list *ivars;\n";
2823 Result += "\tstruct _objc_method_list *methods;\n";
2824 Result += "\tstruct objc_cache *cache;\n";
2825 Result += "\tstruct _objc_protocol_list *protocols;\n";
2826 Result += "\tconst char *ivar_layout;\n";
2827 Result += "\tstruct _objc_class_ext *ext;\n";
2828 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002829 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002830 }
2831
2832 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002833 ObjCInterfaceDecl *RootClass = 0;
2834 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002835 while (SuperClass) {
2836 RootClass = SuperClass;
2837 SuperClass = SuperClass->getSuperClass();
2838 }
2839 SuperClass = CDecl->getSuperClass();
2840
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002841 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2842 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002843 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002844 "{\n\t(struct _objc_class *)\"";
2845 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2846 Result += "\"";
2847
2848 if (SuperClass) {
2849 Result += ", \"";
2850 Result += SuperClass->getName();
2851 Result += "\", \"";
2852 Result += CDecl->getName();
2853 Result += "\"";
2854 }
2855 else {
2856 Result += ", 0, \"";
2857 Result += CDecl->getName();
2858 Result += "\"";
2859 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002860 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002861 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002862 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002863 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002864 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002865 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002866 Result += "\n";
2867 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002868 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002869 Result += ", 0\n";
2870 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002871 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002872 Result += CDecl->getName();
2873 Result += ",0,0\n";
2874 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002875 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002876 Result += "\t,0,0,0,0\n";
2877 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002878
2879 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002880 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2881 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002882 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002883 "{\n\t&_OBJC_METACLASS_";
2884 Result += CDecl->getName();
2885 if (SuperClass) {
2886 Result += ", \"";
2887 Result += SuperClass->getName();
2888 Result += "\", \"";
2889 Result += CDecl->getName();
2890 Result += "\"";
2891 }
2892 else {
2893 Result += ", 0, \"";
2894 Result += CDecl->getName();
2895 Result += "\"";
2896 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002897 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002898 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002899 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002900 Result += ",0";
2901 else {
2902 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002903 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002904 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002905 if (LangOpts.Microsoft)
2906 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002907 Result += ")";
2908 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002909 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002910 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002911 Result += CDecl->getName();
2912 Result += "\n\t";
2913 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002914 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002915 Result += ",0";
2916 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002917 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002918 Result += CDecl->getName();
2919 Result += ", 0\n\t";
2920 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002921 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002922 Result += ",0,0";
2923 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002924 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002925 Result += CDecl->getName();
2926 Result += ", 0,0\n";
2927 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002928 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002929 Result += ",0,0,0\n";
2930 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002931}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002932
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002933/// RewriteImplementations - This routine rewrites all method implementations
2934/// and emits meta-data.
2935
Steve Naroffb29b4272008-04-14 22:03:09 +00002936void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002937 int ClsDefCount = ClassImplementation.size();
2938 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002939
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002940 if (ClsDefCount == 0 && CatDefCount == 0)
2941 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002942 // Rewrite implemented methods
2943 for (int i = 0; i < ClsDefCount; i++)
2944 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002945
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002946 for (int i = 0; i < CatDefCount; i++)
2947 RewriteImplementationDecl(CategoryImplementation[i]);
2948
Steve Naroff5df5b762008-05-07 21:23:49 +00002949 // This is needed for determining instance variable offsets.
2950 Result += "#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002951 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002952 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002953 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002954
2955 // For each implemented category, write out all its meta data.
2956 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002957 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002958
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002959 // Write objc_symtab metadata
2960 /*
2961 struct _objc_symtab
2962 {
2963 long sel_ref_cnt;
2964 SEL *refs;
2965 short cls_def_cnt;
2966 short cat_def_cnt;
2967 void *defs[cls_def_cnt + cat_def_cnt];
2968 };
2969 */
2970
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002971 Result += "\nstruct _objc_symtab {\n";
2972 Result += "\tlong sel_ref_cnt;\n";
2973 Result += "\tSEL *refs;\n";
2974 Result += "\tshort cls_def_cnt;\n";
2975 Result += "\tshort cat_def_cnt;\n";
2976 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2977 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002978
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002979 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002980 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002981 Result += "\t0, 0, " + utostr(ClsDefCount)
2982 + ", " + utostr(CatDefCount) + "\n";
2983 for (int i = 0; i < ClsDefCount; i++) {
2984 Result += "\t,&_OBJC_CLASS_";
2985 Result += ClassImplementation[i]->getName();
2986 Result += "\n";
2987 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002988
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002989 for (int i = 0; i < CatDefCount; i++) {
2990 Result += "\t,&_OBJC_CATEGORY_";
2991 Result += CategoryImplementation[i]->getClassInterface()->getName();
2992 Result += "_";
2993 Result += CategoryImplementation[i]->getName();
2994 Result += "\n";
2995 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002996
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002997 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002998
2999 // Write objc_module metadata
3000
3001 /*
3002 struct _objc_module {
3003 long version;
3004 long size;
3005 const char *name;
3006 struct _objc_symtab *symtab;
3007 }
3008 */
3009
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003010 Result += "\nstruct _objc_module {\n";
3011 Result += "\tlong version;\n";
3012 Result += "\tlong size;\n";
3013 Result += "\tconst char *name;\n";
3014 Result += "\tstruct _objc_symtab *symtab;\n";
3015 Result += "};\n\n";
3016 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003017 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003018 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3019 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003020 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003021
3022 if (LangOpts.Microsoft) {
3023 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003024 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003025 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3026 Result += "&_OBJC_MODULES;\n";
3027 Result += "#pragma data_seg(pop)\n\n";
3028 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003029}
Chris Lattner311ff022007-10-16 22:36:42 +00003030
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003031