blob: c78e51963012f00f267890503ef8e6e365bfc536 [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;
53 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
54 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000055 llvm::SmallVector<Stmt *, 32> Stmts;
56 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000057 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000058
Steve Naroffd82a9ab2008-03-15 00:55:56 +000059 unsigned NumObjCStringLiterals;
60
Steve Naroffebf2b562007-10-23 23:50:29 +000061 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000062 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000063 FunctionDecl *MsgSendStretFunctionDecl;
64 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000065 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000066 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000067 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000068 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000069 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000070 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000071 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000072
Steve Naroffbeaf2992007-11-03 11:27:19 +000073 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000074 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000076
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000077 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000078 int BcLabelCount;
79
Steve Naroff874e2322007-11-15 10:28:18 +000080 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000081 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000082 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000084
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000085 // Needed for header files being rewritten
86 bool IsHeader;
87
Steve Naroffa7b402d2008-03-28 22:26:09 +000088 std::string InFileName;
89 std::string OutFileName;
90
Steve Naroffba92b2e2008-03-27 22:29:16 +000091 std::string Preamble;
92
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000093 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000094 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000095 void Initialize(ASTContext &context);
96
Chris Lattner8a12c272007-10-11 18:38:32 +000097
Chris Lattnerf04da132007-10-24 17:06:59 +000098 // Top Level Driver code.
99 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000100 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000101 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000102 Diagnostic &D, const LangOptions &LOpts);
Steve Naroffb29b4272008-04-14 22:03:09 +0000103 ~RewriteObjC();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000104
105 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000106 // If replacement succeeded or warning disabled return with no warning.
107 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000108 return;
109
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000110 SourceRange Range = Old->getSourceRange();
111 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
112 0, 0, &Range, 1);
113 }
114
Steve Naroffba92b2e2008-03-27 22:29:16 +0000115 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
116 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000117 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000118 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000119 SilenceRewriteMacroWarning)
120 return;
121
122 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
123 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000124
Chris Lattneraadaf782008-01-31 19:51:04 +0000125 void RemoveText(SourceLocation Loc, unsigned StrLen) {
126 // If removal succeeded or warning disabled return with no warning.
127 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
128 return;
129
130 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
131 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000132
Chris Lattneraadaf782008-01-31 19:51:04 +0000133 void ReplaceText(SourceLocation Start, unsigned OrigLength,
134 const char *NewStr, unsigned NewLength) {
135 // If removal succeeded or warning disabled return with no warning.
136 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
137 SilenceRewriteMacroWarning)
138 return;
139
140 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
141 }
142
Chris Lattnerf04da132007-10-24 17:06:59 +0000143 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000144 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000145 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000146 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000147 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
148 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000149 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000150 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
151 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
152 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
153 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
154 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000155 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000156 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000157 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000158 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000159 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000160 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000161 QualType getConstantStringStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000162
Chris Lattnerf04da132007-10-24 17:06:59 +0000163 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000164 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000165 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000166 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000167 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000168 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000169 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000170 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000171 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000172 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000173 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
174 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
175 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000176 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
177 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000178 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
179 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000180 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000181 Stmt *RewriteBreakStmt(BreakStmt *S);
182 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000183 void SynthCountByEnumWithState(std::string &buf);
184
Steve Naroff09b266e2007-10-30 23:14:51 +0000185 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000186 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000187 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000188 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000189 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000190 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000191 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000192 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000193 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000194 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000195
Chris Lattnerf04da132007-10-24 17:06:59 +0000196 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000197 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000198 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000199
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000200 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000201 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000202
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000203 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
204 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000205 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000206 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000207 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000208 const char *ClassName,
209 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000210
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000211 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000212 int NumProtocols,
213 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000214 const char *ClassName,
215 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000216 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000217 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000218 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
219 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000220 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000221 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000222 };
223}
224
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000225static bool IsHeaderFile(const std::string &Filename) {
226 std::string::size_type DotPos = Filename.rfind('.');
227
228 if (DotPos == std::string::npos) {
229 // no file extension
230 return false;
231 }
232
233 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
234 // C header: .h
235 // C++ header: .hh or .H;
236 return Ext == "h" || Ext == "hh" || Ext == "H";
237}
238
Steve Naroffb29b4272008-04-14 22:03:09 +0000239RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000240 Diagnostic &D, const LangOptions &LOpts)
241 : Diags(D), LangOpts(LOpts) {
242 IsHeader = IsHeaderFile(inFile);
243 InFileName = inFile;
244 OutFileName = outFile;
245 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
246 "rewriting sub-expression within a macro (may not be correct)");
247}
248
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000249ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000250 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000251 Diagnostic &Diags,
252 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000253 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000254}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000255
Steve Naroffb29b4272008-04-14 22:03:09 +0000256void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000257 Context = &context;
258 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000259 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000260 MsgSendFunctionDecl = 0;
261 MsgSendSuperFunctionDecl = 0;
262 MsgSendStretFunctionDecl = 0;
263 MsgSendSuperStretFunctionDecl = 0;
264 MsgSendFpretFunctionDecl = 0;
265 GetClassFunctionDecl = 0;
266 GetMetaClassFunctionDecl = 0;
267 SelGetUidFunctionDecl = 0;
268 CFStringFunctionDecl = 0;
269 GetProtocolFunctionDecl = 0;
270 ConstantStringClassReference = 0;
271 NSStringRecord = 0;
272 CurMethodDecl = 0;
273 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000274 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000275 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000276 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000277 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000278
279 // Get the ID and start/end of the main file.
280 MainFileID = SM->getMainFileID();
281 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
282 MainFileStart = MainBuf->getBufferStart();
283 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000284
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000285 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000286
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000287 // declaring objc_selector outside the parameter list removes a silly
288 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000289 if (IsHeader)
290 Preamble = "#pragma once\n";
291 Preamble += "struct objc_selector; struct objc_class;\n";
292 Preamble += "#ifndef OBJC_SUPER\n";
293 Preamble += "struct objc_super { struct objc_object *object; ";
294 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000295 if (LangOpts.Microsoft) {
296 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000297 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
298 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000299 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000300 Preamble += "};\n";
301 Preamble += "#define OBJC_SUPER\n";
302 Preamble += "#endif\n";
303 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
304 Preamble += "typedef struct objc_object Protocol;\n";
305 Preamble += "#define _REWRITER_typedef_Protocol\n";
306 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000307 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000308 Preamble += "extern \"C\" {\n";
309 Preamble += "struct objc_object *objc_msgSend";
310 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
311 Preamble += "extern struct objc_object *objc_msgSendSuper";
312 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
313 Preamble += "extern struct objc_object *objc_msgSend_stret";
314 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
315 Preamble += "extern struct objc_object *objc_msgSendSuper_stret";
316 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
317 Preamble += "extern struct objc_object *objc_msgSend_fpret";
318 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
319 Preamble += "struct objc_object *objc_getClass";
320 Preamble += "(const char *);\n";
321 Preamble += "extern struct objc_object *objc_getMetaClass";
322 Preamble += "(const char *);\n";
323 Preamble += "extern void objc_exception_throw(struct objc_object *);\n";
324 Preamble += "extern void objc_exception_try_enter(void *);\n";
325 Preamble += "extern void objc_exception_try_exit(void *);\n";
326 Preamble += "extern struct objc_object *objc_exception_extract(void *);\n";
327 Preamble += "extern int objc_exception_match";
328 Preamble += "(struct objc_class *, struct objc_object *, ...);\n";
329 Preamble += "extern Protocol *objc_getProtocol(const char *);\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000330 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000331 Preamble += "} // end extern \"C\"\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000332 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
333 Preamble += "struct __objcFastEnumerationState {\n\t";
334 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000335 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000336 Preamble += "unsigned long *mutationsPtr;\n\t";
337 Preamble += "unsigned long extra[5];\n};\n";
338 Preamble += "#define __FASTENUMERATIONSTATE\n";
339 Preamble += "#endif\n";
340 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
341 Preamble += "struct __NSConstantStringImpl {\n";
342 Preamble += " int *isa;\n";
343 Preamble += " int flags;\n";
344 Preamble += " char *str;\n";
345 Preamble += " long length;\n";
346 Preamble += "};\n";
347 Preamble += "extern int __CFConstantStringClassReference[];\n";
348 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
349 Preamble += "#endif\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000350 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000351 Preamble += "#define __attribute__(X)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000352}
353
354
Chris Lattnerf04da132007-10-24 17:06:59 +0000355//===----------------------------------------------------------------------===//
356// Top Level Driver Code
357//===----------------------------------------------------------------------===//
358
Steve Naroffb29b4272008-04-14 22:03:09 +0000359void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000360 // Two cases: either the decl could be in the main file, or it could be in a
361 // #included file. If the former, rewrite it now. If the later, check to see
362 // if we rewrote the #include/#import.
363 SourceLocation Loc = D->getLocation();
364 Loc = SM->getLogicalLoc(Loc);
365
366 // If this is for a builtin, ignore it.
367 if (Loc.isInvalid()) return;
368
Steve Naroffebf2b562007-10-23 23:50:29 +0000369 // Look for built-in declarations that we need to refer during the rewrite.
370 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000371 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000372 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000373 // declared in <Foundation/NSString.h>
374 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
375 ConstantStringClassReference = FVD;
376 return;
377 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000378 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000379 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000380 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000381 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000382 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000383 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000384 } else if (ObjCForwardProtocolDecl *FP =
385 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000386 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000387 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000388 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000389 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000390 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000391}
392
Chris Lattnerf04da132007-10-24 17:06:59 +0000393/// HandleDeclInMainFile - This is called for each top-level decl defined in the
394/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000395void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000396 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
397 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000398 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000399
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000400 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000401 if (Stmt *Body = MD->getBody()) {
402 //Body->dump();
403 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000404 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000405 CurMethodDecl = 0;
406 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000407 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000408 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000409 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000410 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000411 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000412 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000413 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000414 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000415 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000416 if (VD->getInit())
417 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
418 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000419 // Nothing yet.
420}
421
Steve Naroffb29b4272008-04-14 22:03:09 +0000422RewriteObjC::~RewriteObjC() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000423 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000424
425 // Rewrite tabs if we care.
426 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000427
Steve Naroffa7b402d2008-03-28 22:26:09 +0000428 if (Diags.hasErrorOccurred())
429 return;
430
431 // Create the output file.
432
433 std::ostream *OutFile;
434 if (OutFileName == "-") {
435 OutFile = llvm::cout.stream();
436 } else if (!OutFileName.empty()) {
437 OutFile = new std::ofstream(OutFileName.c_str(),
438 std::ios_base::binary|std::ios_base::out);
439 } else if (InFileName == "-") {
440 OutFile = llvm::cout.stream();
441 } else {
442 llvm::sys::Path Path(InFileName);
443 Path.eraseSuffix();
444 Path.appendSuffix("cpp");
445 OutFile = new std::ofstream(Path.toString().c_str(),
446 std::ios_base::binary|std::ios_base::out);
447 }
448
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000449 RewriteInclude();
450
Steve Naroffba92b2e2008-03-27 22:29:16 +0000451 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
452 Preamble.c_str(), Preamble.size(), false);
453
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000454 // Rewrite Objective-c meta data*
455 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000456 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000457
Chris Lattnerf04da132007-10-24 17:06:59 +0000458 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
459 // we are done.
460 if (const RewriteBuffer *RewriteBuf =
461 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000462 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000463 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000464 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000465 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000466 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000467 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000468 *OutFile << ResultStr;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000469}
470
Chris Lattnerf04da132007-10-24 17:06:59 +0000471//===----------------------------------------------------------------------===//
472// Syntactic (non-AST) Rewriting Code
473//===----------------------------------------------------------------------===//
474
Steve Naroffb29b4272008-04-14 22:03:09 +0000475void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000476 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
477 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
478 const char *MainBufStart = MainBuf.first;
479 const char *MainBufEnd = MainBuf.second;
480 size_t ImportLen = strlen("import");
481 size_t IncludeLen = strlen("include");
482
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000483 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000484 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
485 if (*BufPtr == '#') {
486 if (++BufPtr == MainBufEnd)
487 return;
488 while (*BufPtr == ' ' || *BufPtr == '\t')
489 if (++BufPtr == MainBufEnd)
490 return;
491 if (!strncmp(BufPtr, "import", ImportLen)) {
492 // replace import with include
493 SourceLocation ImportLoc =
494 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000495 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000496 BufPtr += ImportLen;
497 }
498 }
499 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000500}
501
Steve Naroffb29b4272008-04-14 22:03:09 +0000502void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000503 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
504 const char *MainBufStart = MainBuf.first;
505 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000506
Chris Lattnerf04da132007-10-24 17:06:59 +0000507 // Loop over the whole file, looking for tabs.
508 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
509 if (*BufPtr != '\t')
510 continue;
511
512 // Okay, we found a tab. This tab will turn into at least one character,
513 // but it depends on which 'virtual column' it is in. Compute that now.
514 unsigned VCol = 0;
515 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
516 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
517 ++VCol;
518
519 // Okay, now that we know the virtual column, we know how many spaces to
520 // insert. We assume 8-character tab-stops.
521 unsigned Spaces = 8-(VCol & 7);
522
523 // Get the location of the tab.
524 SourceLocation TabLoc =
525 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
526
527 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000528 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000529 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000530}
531
532
Steve Naroffb29b4272008-04-14 22:03:09 +0000533void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000534 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000535 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000536
537 // Get the start location and compute the semi location.
538 SourceLocation startLoc = ClassDecl->getLocation();
539 const char *startBuf = SM->getCharacterData(startLoc);
540 const char *semiPtr = strchr(startBuf, ';');
541
542 // Translate to typedef's that forward reference structs with the same name
543 // as the class. As a convenience, we include the original declaration
544 // as a comment.
545 std::string typedefString;
546 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000547 typedefString.append(startBuf, semiPtr-startBuf+1);
548 typedefString += "\n";
549 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000550 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000551 typedefString += "#ifndef _REWRITER_typedef_";
552 typedefString += ForwardDecl->getName();
553 typedefString += "\n";
554 typedefString += "#define _REWRITER_typedef_";
555 typedefString += ForwardDecl->getName();
556 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000557 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000558 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000559 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000560 }
561
562 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000563 ReplaceText(startLoc, semiPtr-startBuf+1,
564 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000565}
566
Steve Naroffb29b4272008-04-14 22:03:09 +0000567void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000568 SourceLocation LocStart = Method->getLocStart();
569 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000570
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000571 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000572 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000573 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000574 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000575 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000576 }
577}
578
Steve Naroffb29b4272008-04-14 22:03:09 +0000579void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000580{
Chris Lattner55d13b42008-03-16 21:23:50 +0000581 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000582 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000583 SourceLocation Loc = Property->getLocation();
584
Chris Lattneraadaf782008-01-31 19:51:04 +0000585 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000586
587 // FIXME: handle properties that are declared across multiple lines.
588 }
589}
590
Steve Naroffb29b4272008-04-14 22:03:09 +0000591void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000592 SourceLocation LocStart = CatDecl->getLocStart();
593
594 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000595 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000596
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000597 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000598 E = CatDecl->instmeth_end(); I != E; ++I)
599 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000600 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000601 E = CatDecl->classmeth_end(); I != E; ++I)
602 RewriteMethodDeclaration(*I);
603
Steve Naroff423cb562007-10-30 13:30:57 +0000604 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000605 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000606}
607
Steve Naroffb29b4272008-04-14 22:03:09 +0000608void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000609 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000610
Steve Naroff752d6ef2007-10-30 16:42:30 +0000611 SourceLocation LocStart = PDecl->getLocStart();
612
613 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000614 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000615
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000616 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000617 E = PDecl->instmeth_end(); I != E; ++I)
618 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000619 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000620 E = PDecl->classmeth_end(); I != E; ++I)
621 RewriteMethodDeclaration(*I);
622
Steve Naroff752d6ef2007-10-30 16:42:30 +0000623 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000624 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000625 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000626
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000627 // Must comment out @optional/@required
628 const char *startBuf = SM->getCharacterData(LocStart);
629 const char *endBuf = SM->getCharacterData(LocEnd);
630 for (const char *p = startBuf; p < endBuf; p++) {
631 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
632 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000633 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000634 ReplaceText(OptionalLoc, strlen("@optional"),
635 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000636
637 }
638 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
639 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000640 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000641 ReplaceText(OptionalLoc, strlen("@required"),
642 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000643
644 }
645 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000646}
647
Steve Naroffb29b4272008-04-14 22:03:09 +0000648void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000649 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000650 if (LocStart.isInvalid())
651 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000652 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000653 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000654}
655
Steve Naroffb29b4272008-04-14 22:03:09 +0000656void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000657 std::string &ResultStr) {
658 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000659 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000660 ResultStr += "id";
661 else
662 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000663 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000664
665 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000666 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000667
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000668 if (OMD->isInstance())
669 NameStr += "_I_";
670 else
671 NameStr += "_C_";
672
673 NameStr += OMD->getClassInterface()->getName();
674 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000675
676 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000677 if (ObjCCategoryImplDecl *CID =
678 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000679 NameStr += CID->getName();
680 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000681 }
Steve Naroff563b8282008-04-04 22:23:44 +0000682 // Append selector names, replacing ':' with '_'
683 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000684 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000685 else {
686 std::string selString = OMD->getSelector().getName();
687 int len = selString.size();
688 for (int i = 0; i < len; i++)
689 if (selString[i] == ':')
690 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000691 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000692 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000693 // Remember this name for metadata emission
694 MethodInternalNames[OMD] = NameStr;
695 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000696
697 // Rewrite arguments
698 ResultStr += "(";
699
700 // invisible arguments
701 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000702 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000703 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000704 if (!LangOpts.Microsoft) {
705 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
706 ResultStr += "struct ";
707 }
708 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000709 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000710 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000711 }
712 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000713 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000714
715 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000717 ResultStr += " _cmd";
718
719 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000720 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000721 ParmVarDecl *PDecl = OMD->getParamDecl(i);
722 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000723 if (PDecl->getType()->isObjCQualifiedIdType()) {
724 ResultStr += "id ";
725 ResultStr += PDecl->getName();
726 } else {
727 std::string Name = PDecl->getName();
728 PDecl->getType().getAsStringInternal(Name);
729 ResultStr += Name;
730 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000731 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000732 if (OMD->isVariadic())
733 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000734 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000735
736}
Steve Naroffb29b4272008-04-14 22:03:09 +0000737void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000738 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
739 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000740
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000741 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000742 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000743 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000744 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000745
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000746 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000747 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
748 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000749 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000750 ObjCMethodDecl *OMD = *I;
751 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000752 SourceLocation LocStart = OMD->getLocStart();
753 SourceLocation LocEnd = OMD->getBody()->getLocStart();
754
755 const char *startBuf = SM->getCharacterData(LocStart);
756 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000757 ReplaceText(LocStart, endBuf-startBuf,
758 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000759 }
760
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000761 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000762 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
763 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000764 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000765 ObjCMethodDecl *OMD = *I;
766 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000767 SourceLocation LocStart = OMD->getLocStart();
768 SourceLocation LocEnd = OMD->getBody()->getLocStart();
769
770 const char *startBuf = SM->getCharacterData(LocStart);
771 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000772 ReplaceText(LocStart, endBuf-startBuf,
773 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000774 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000775 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000776 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000777 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000778 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000779}
780
Steve Naroffb29b4272008-04-14 22:03:09 +0000781void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000782 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000783 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000784 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000785 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000786 ResultStr += ClassDecl->getName();
787 ResultStr += "\n";
788 ResultStr += "#define _REWRITER_typedef_";
789 ResultStr += ClassDecl->getName();
790 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000791 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000792 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000793 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000794 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000795 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000796 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000797 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000798
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000799 RewriteProperties(ClassDecl->getNumPropertyDecl(),
800 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000801 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000802 E = ClassDecl->instmeth_end(); I != E; ++I)
803 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000804 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000805 E = ClassDecl->classmeth_end(); I != E; ++I)
806 RewriteMethodDeclaration(*I);
807
Steve Naroff2feac5e2007-10-30 03:43:13 +0000808 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000809 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000810}
811
Steve Naroffb29b4272008-04-14 22:03:09 +0000812Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000813 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000814 if (CurMethodDecl) {
815 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
816 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
817 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000818 // lookup which class implements the instance variable.
819 ObjCInterfaceDecl *clsDeclared = 0;
820 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
821 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5518e7c2008-03-12 23:15:19 +0000822
823 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000824 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff05b8c782008-03-12 00:25:36 +0000825 RecName += "_IMPL";
826 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000827 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000828 SourceLocation(), II, 0);
Steve Naroff05b8c782008-03-12 00:25:36 +0000829 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
830 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
831 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
832 // Don't forget the parens to enforce the proper binding.
833 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
834 if (IV->isFreeIvar()) {
835 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
836 ReplaceStmt(IV, ME);
837 delete IV;
838 return ME;
839 } else {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000840 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5518e7c2008-03-12 23:15:19 +0000841 // Cannot delete IV->getBase(), since PE points to it.
842 // Replace the old base with the cast. This is important when doing
843 // embedded rewrites. For example, [newInv->_container addObject:0].
844 IV->setBase(PE);
845 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000846 }
847 }
848 }
Steve Naroff84472a82008-04-18 21:55:08 +0000849 } else { // we are outside a method.
850 if (IV->isFreeIvar())
851 assert(1 && "Cannot have a free standing ivar outside a method");
852 // Explicit ivar refs do not need to be rewritten. Do nothing.
Steve Naroffc2a689b2007-11-15 11:33:00 +0000853 }
Steve Naroff84472a82008-04-18 21:55:08 +0000854 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000855}
856
Chris Lattnerf04da132007-10-24 17:06:59 +0000857//===----------------------------------------------------------------------===//
858// Function Body / Expression rewriting
859//===----------------------------------------------------------------------===//
860
Steve Naroffb29b4272008-04-14 22:03:09 +0000861Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000862 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
863 isa<DoStmt>(S) || isa<ForStmt>(S))
864 Stmts.push_back(S);
865 else if (isa<ObjCForCollectionStmt>(S)) {
866 Stmts.push_back(S);
867 ObjCBcLabelNo.push_back(++BcLabelCount);
868 }
869
Chris Lattner338d1e22008-01-31 05:10:40 +0000870 SourceLocation OrigStmtEnd = S->getLocEnd();
871
872 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000873 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
874 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000875 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000876 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000877 if (newStmt)
878 *CI = newStmt;
879 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000880
881 // Handle specific things.
882 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
883 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000884
885 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
886 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000887
888 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
889 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000890
Steve Naroffbeaf2992007-11-03 11:27:19 +0000891 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
892 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000893
Steve Naroff934f2762007-10-24 22:48:43 +0000894 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
895 // Before we rewrite it, put the original message expression in a comment.
896 SourceLocation startLoc = MessExpr->getLocStart();
897 SourceLocation endLoc = MessExpr->getLocEnd();
898
899 const char *startBuf = SM->getCharacterData(startLoc);
900 const char *endBuf = SM->getCharacterData(endLoc);
901
902 std::string messString;
903 messString += "// ";
904 messString.append(startBuf, endBuf-startBuf+1);
905 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000906
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000907 // FIXME: Missing definition of
908 // InsertText(clang::SourceLocation, char const*, unsigned int).
909 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000910 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000911 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000912 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000913 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000914
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000915 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
916 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000917
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000918 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
919 return RewriteObjCSynchronizedStmt(StmtTry);
920
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000921 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
922 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000923
924 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
925 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000926
927 if (ObjCForCollectionStmt *StmtForCollection =
928 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000929 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000930 if (BreakStmt *StmtBreakStmt =
931 dyn_cast<BreakStmt>(S))
932 return RewriteBreakStmt(StmtBreakStmt);
933 if (ContinueStmt *StmtContinueStmt =
934 dyn_cast<ContinueStmt>(S))
935 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000936
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000937 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
938 isa<DoStmt>(S) || isa<ForStmt>(S)) {
939 assert(!Stmts.empty() && "Statement stack is empty");
940 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
941 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
942 && "Statement stack mismatch");
943 Stmts.pop_back();
944 }
Steve Naroff874e2322007-11-15 10:28:18 +0000945#if 0
946 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
947 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
948 // Get the new text.
949 std::ostringstream Buf;
950 Replacement->printPretty(Buf);
951 const std::string &Str = Buf.str();
952
953 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000954 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000955 delete S;
956 return Replacement;
957 }
958#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000959 // Return this stmt unmodified.
960 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000961}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000962
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000963/// SynthCountByEnumWithState - To print:
964/// ((unsigned int (*)
965/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
966/// (void *)objc_msgSend)((id)l_collection,
967/// sel_registerName(
968/// "countByEnumeratingWithState:objects:count:"),
969/// &enumState,
970/// (id *)items, (unsigned int)16)
971///
Steve Naroffb29b4272008-04-14 22:03:09 +0000972void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000973 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
974 "id *, unsigned int))(void *)objc_msgSend)";
975 buf += "\n\t\t";
976 buf += "((id)l_collection,\n\t\t";
977 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
978 buf += "\n\t\t";
979 buf += "&enumState, "
980 "(id *)items, (unsigned int)16)";
981}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000982
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000983/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
984/// statement to exit to its outer synthesized loop.
985///
Steve Naroffb29b4272008-04-14 22:03:09 +0000986Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000987 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
988 return S;
989 // replace break with goto __break_label
990 std::string buf;
991
992 SourceLocation startLoc = S->getLocStart();
993 buf = "goto __break_label_";
994 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000995 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000996
997 return 0;
998}
999
1000/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1001/// statement to continue with its inner synthesized loop.
1002///
Steve Naroffb29b4272008-04-14 22:03:09 +00001003Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001004 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1005 return S;
1006 // replace continue with goto __continue_label
1007 std::string buf;
1008
1009 SourceLocation startLoc = S->getLocStart();
1010 buf = "goto __continue_label_";
1011 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001012 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001013
1014 return 0;
1015}
1016
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001017/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001018/// It rewrites:
1019/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001020
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001021/// Into:
1022/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001023/// type elem;
1024/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001025/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001026/// id l_collection = (id)collection;
1027/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1028/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001029/// if (limit) {
1030/// unsigned long startMutations = *enumState.mutationsPtr;
1031/// do {
1032/// unsigned long counter = 0;
1033/// do {
1034/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001035/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001036/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001037/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001038/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001039/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001040/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1041/// objects:items count:16]);
1042/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001043/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001044/// }
1045/// else
1046/// elem = nil;
1047/// }
1048///
Steve Naroffb29b4272008-04-14 22:03:09 +00001049Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001050 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001051 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1052 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1053 "ObjCForCollectionStmt Statement stack mismatch");
1054 assert(!ObjCBcLabelNo.empty() &&
1055 "ObjCForCollectionStmt - Label No stack empty");
1056
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001057 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001058 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001059 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001060 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001061 std::string buf;
1062 buf = "\n{\n\t";
1063 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1064 // type elem;
1065 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001066 elementTypeAsString = ElementType.getAsString();
1067 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001068 buf += " ";
1069 elementName = DS->getDecl()->getName();
1070 buf += elementName;
1071 buf += ";\n\t";
1072 }
Chris Lattner06767512008-04-08 05:52:18 +00001073 else {
1074 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001075 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001076 elementTypeAsString = DR->getDecl()->getType().getAsString();
1077 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001078
1079 // struct __objcFastEnumerationState enumState = { 0 };
1080 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1081 // id items[16];
1082 buf += "id items[16];\n\t";
1083 // id l_collection = (id)
1084 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001085 // Find start location of 'collection' the hard way!
1086 const char *startCollectionBuf = startBuf;
1087 startCollectionBuf += 3; // skip 'for'
1088 startCollectionBuf = strchr(startCollectionBuf, '(');
1089 startCollectionBuf++; // skip '('
1090 // find 'in' and skip it.
1091 while (*startCollectionBuf != ' ' ||
1092 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1093 (*(startCollectionBuf+3) != ' ' &&
1094 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1095 startCollectionBuf++;
1096 startCollectionBuf += 3;
1097
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001098 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001099 ReplaceText(startLoc, startCollectionBuf - startBuf,
1100 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001101 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001102 SourceLocation rightParenLoc = S->getRParenLoc();
1103 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1104 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001105 buf = ";\n\t";
1106
1107 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1108 // objects:items count:16];
1109 // which is synthesized into:
1110 // unsigned int limit =
1111 // ((unsigned int (*)
1112 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1113 // (void *)objc_msgSend)((id)l_collection,
1114 // sel_registerName(
1115 // "countByEnumeratingWithState:objects:count:"),
1116 // (struct __objcFastEnumerationState *)&state,
1117 // (id *)items, (unsigned int)16);
1118 buf += "unsigned long limit =\n\t\t";
1119 SynthCountByEnumWithState(buf);
1120 buf += ";\n\t";
1121 /// if (limit) {
1122 /// unsigned long startMutations = *enumState.mutationsPtr;
1123 /// do {
1124 /// unsigned long counter = 0;
1125 /// do {
1126 /// if (startMutations != *enumState.mutationsPtr)
1127 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001128 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001129 buf += "if (limit) {\n\t";
1130 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1131 buf += "do {\n\t\t";
1132 buf += "unsigned long counter = 0;\n\t\t";
1133 buf += "do {\n\t\t\t";
1134 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1135 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1136 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001137 buf += " = (";
1138 buf += elementTypeAsString;
1139 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001140 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001141 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001142
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001143 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001144 /// } while (counter < limit);
1145 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1146 /// objects:items count:16]);
1147 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001148 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001149 /// }
1150 /// else
1151 /// elem = nil;
1152 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001153 ///
1154 buf = ";\n\t";
1155 buf += "__continue_label_";
1156 buf += utostr(ObjCBcLabelNo.back());
1157 buf += ": ;";
1158 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001159 buf += "} while (counter < limit);\n\t";
1160 buf += "} while (limit = ";
1161 SynthCountByEnumWithState(buf);
1162 buf += ");\n\t";
1163 buf += elementName;
1164 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001165 buf += "__break_label_";
1166 buf += utostr(ObjCBcLabelNo.back());
1167 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001168 buf += "}\n\t";
1169 buf += "else\n\t\t";
1170 buf += elementName;
1171 buf += " = nil;\n";
1172 buf += "}\n";
1173 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001174 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001175 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001176 Stmts.pop_back();
1177 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001178 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001179}
1180
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001181/// RewriteObjCSynchronizedStmt -
1182/// This routine rewrites @synchronized(expr) stmt;
1183/// into:
1184/// objc_sync_enter(expr);
1185/// @try stmt @finally { objc_sync_exit(expr); }
1186///
Steve Naroffb29b4272008-04-14 22:03:09 +00001187Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001188 // Get the start location and compute the semi location.
1189 SourceLocation startLoc = S->getLocStart();
1190 const char *startBuf = SM->getCharacterData(startLoc);
1191
1192 assert((*startBuf == '@') && "bogus @synchronized location");
1193
1194 std::string buf;
1195 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001196 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001197 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1198 const char *endBuf = SM->getCharacterData(endLoc);
1199 endBuf++;
1200 const char *rparenBuf = strchr(endBuf, ')');
1201 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1202 buf = ");\n";
1203 // declare a new scope with two variables, _stack and _rethrow.
1204 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1205 buf += "int buf[18/*32-bit i386*/];\n";
1206 buf += "char *pointers[4];} _stack;\n";
1207 buf += "id volatile _rethrow = 0;\n";
1208 buf += "objc_exception_try_enter(&_stack);\n";
1209 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001210 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001211 startLoc = S->getSynchBody()->getLocEnd();
1212 startBuf = SM->getCharacterData(startLoc);
1213
1214 assert((*startBuf == '}') && "bogus @try block");
1215 SourceLocation lastCurlyLoc = startLoc;
1216 buf = "}\nelse {\n";
1217 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1218 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1219 // FIXME: This must be objc_sync_exit(syncExpr);
1220 buf += " objc_sync_exit();\n";
1221 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1222 buf += "}\n";
1223 buf += "}";
1224
Chris Lattneraadaf782008-01-31 19:51:04 +00001225 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001226 return 0;
1227}
1228
Steve Naroffb29b4272008-04-14 22:03:09 +00001229Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001230 // Get the start location and compute the semi location.
1231 SourceLocation startLoc = S->getLocStart();
1232 const char *startBuf = SM->getCharacterData(startLoc);
1233
1234 assert((*startBuf == '@') && "bogus @try location");
1235
1236 std::string buf;
1237 // declare a new scope with two variables, _stack and _rethrow.
1238 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1239 buf += "int buf[18/*32-bit i386*/];\n";
1240 buf += "char *pointers[4];} _stack;\n";
1241 buf += "id volatile _rethrow = 0;\n";
1242 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001243 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001244
Chris Lattneraadaf782008-01-31 19:51:04 +00001245 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001246
1247 startLoc = S->getTryBody()->getLocEnd();
1248 startBuf = SM->getCharacterData(startLoc);
1249
1250 assert((*startBuf == '}') && "bogus @try block");
1251
1252 SourceLocation lastCurlyLoc = startLoc;
1253
1254 startLoc = startLoc.getFileLocWithOffset(1);
1255 buf = " /* @catch begin */ else {\n";
1256 buf += " id _caught = objc_exception_extract(&_stack);\n";
1257 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001258 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001259 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1260 buf += " else { /* @catch continue */";
1261
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001262 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001263
1264 bool sawIdTypedCatch = false;
1265 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001266 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001267 while (catchList) {
1268 Stmt *catchStmt = catchList->getCatchParamStmt();
1269
1270 if (catchList == S->getCatchStmts())
1271 buf = "if ("; // we are generating code for the first catch clause
1272 else
1273 buf = "else if (";
1274 startLoc = catchList->getLocStart();
1275 startBuf = SM->getCharacterData(startLoc);
1276
1277 assert((*startBuf == '@') && "bogus @catch location");
1278
1279 const char *lParenLoc = strchr(startBuf, '(');
1280
Steve Naroffbe4b3332008-02-01 22:08:12 +00001281 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001282 // Now rewrite the body...
1283 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001284 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1285 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001286 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1287 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001288 assert((*bodyBuf == '{') && "bogus @catch body location");
1289
1290 buf += "1) { id _tmp = _caught;";
1291 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1292 buf.c_str(), buf.size());
1293 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001294 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001295 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001296 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001297 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001298 sawIdTypedCatch = true;
1299 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001300 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001301
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001302 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001303 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001304 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001305 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001306 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001307 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001308 }
1309 }
1310 // Now rewrite the body...
1311 lastCatchBody = catchList->getCatchBody();
1312 SourceLocation rParenLoc = catchList->getRParenLoc();
1313 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1314 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1315 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1316 assert((*rParenBuf == ')') && "bogus @catch paren location");
1317 assert((*bodyBuf == '{') && "bogus @catch body location");
1318
1319 buf = " = _caught;";
1320 // Here we replace ") {" with "= _caught;" (which initializes and
1321 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001322 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001323 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001324 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001325 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001326 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001327 catchList = catchList->getNextCatchStmt();
1328 }
1329 // Complete the catch list...
1330 if (lastCatchBody) {
1331 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001332 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1333 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001334 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1335 buf = " } } /* @catch end */\n";
1336
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001337 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001338
1339 // Set lastCurlyLoc
1340 lastCurlyLoc = lastCatchBody->getLocEnd();
1341 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001342 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001343 startLoc = finalStmt->getLocStart();
1344 startBuf = SM->getCharacterData(startLoc);
1345 assert((*startBuf == '@') && "bogus @finally start");
1346
1347 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001348 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001349
1350 Stmt *body = finalStmt->getFinallyBody();
1351 SourceLocation startLoc = body->getLocStart();
1352 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001353 assert(*SM->getCharacterData(startLoc) == '{' &&
1354 "bogus @finally body location");
1355 assert(*SM->getCharacterData(endLoc) == '}' &&
1356 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001357
1358 startLoc = startLoc.getFileLocWithOffset(1);
1359 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001360 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001361 endLoc = endLoc.getFileLocWithOffset(-1);
1362 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001363 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001364
1365 // Set lastCurlyLoc
1366 lastCurlyLoc = body->getLocEnd();
1367 }
1368 // Now emit the final closing curly brace...
1369 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1370 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001371 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001372 return 0;
1373}
1374
Steve Naroffb29b4272008-04-14 22:03:09 +00001375Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001376 return 0;
1377}
1378
Steve Naroffb29b4272008-04-14 22:03:09 +00001379Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001380 return 0;
1381}
1382
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001383// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001384// the throw expression is typically a message expression that's already
1385// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001386Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001387 // Get the start location and compute the semi location.
1388 SourceLocation startLoc = S->getLocStart();
1389 const char *startBuf = SM->getCharacterData(startLoc);
1390
1391 assert((*startBuf == '@') && "bogus @throw location");
1392
1393 std::string buf;
1394 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001395 if (S->getThrowExpr())
1396 buf = "objc_exception_throw(";
1397 else // add an implicit argument
1398 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001399 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001400 const char *semiBuf = strchr(startBuf, ';');
1401 assert((*semiBuf == ';') && "@throw: can't find ';'");
1402 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1403 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001404 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001405 return 0;
1406}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001407
Steve Naroffb29b4272008-04-14 22:03:09 +00001408Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001409 // Create a new string expression.
1410 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001411 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001412 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1413 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001414 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1415 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001416 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001417 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001418
Chris Lattner07506182007-11-30 22:53:43 +00001419 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001420 delete Exp;
1421 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001422}
1423
Steve Naroffb29b4272008-04-14 22:03:09 +00001424Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001425 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1426 // Create a call to sel_registerName("selName").
1427 llvm::SmallVector<Expr*, 8> SelExprs;
1428 QualType argType = Context->getPointerType(Context->CharTy);
1429 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1430 Exp->getSelector().getName().size(),
1431 false, argType, SourceLocation(),
1432 SourceLocation()));
1433 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1434 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001435 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001436 delete Exp;
1437 return SelExp;
1438}
1439
Steve Naroffb29b4272008-04-14 22:03:09 +00001440CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001441 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001442 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001443 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001444
1445 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001446 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001447
1448 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001449 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001450 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1451
1452 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001453
Steve Naroff934f2762007-10-24 22:48:43 +00001454 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1455}
1456
Steve Naroffd5255f52007-11-01 13:24:47 +00001457static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1458 const char *&startRef, const char *&endRef) {
1459 while (startBuf < endBuf) {
1460 if (*startBuf == '<')
1461 startRef = startBuf; // mark the start.
1462 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001463 if (startRef && *startRef == '<') {
1464 endRef = startBuf; // mark the end.
1465 return true;
1466 }
1467 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001468 }
1469 startBuf++;
1470 }
1471 return false;
1472}
1473
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001474static void scanToNextArgument(const char *&argRef) {
1475 int angle = 0;
1476 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1477 if (*argRef == '<')
1478 angle++;
1479 else if (*argRef == '>')
1480 angle--;
1481 argRef++;
1482 }
1483 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1484}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001485
Steve Naroffb29b4272008-04-14 22:03:09 +00001486bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001487
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001488 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001489 return true;
1490
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001491 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001492 return true;
1493
Steve Naroffd5255f52007-11-01 13:24:47 +00001494 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001495 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001496 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001497 return true; // we have "Class <Protocol> *".
1498 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001499 return false;
1500}
1501
Steve Naroffb29b4272008-04-14 22:03:09 +00001502void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001503 SourceLocation Loc;
1504 QualType Type;
1505 const FunctionTypeProto *proto = 0;
1506 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1507 Loc = VD->getLocation();
1508 Type = VD->getType();
1509 }
1510 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1511 Loc = FD->getLocation();
1512 // Check for ObjC 'id' and class types that have been adorned with protocol
1513 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1514 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1515 assert(funcType && "missing function type");
1516 proto = dyn_cast<FunctionTypeProto>(funcType);
1517 if (!proto)
1518 return;
1519 Type = proto->getResultType();
1520 }
1521 else
1522 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001523
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001524 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001525 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001526
1527 const char *endBuf = SM->getCharacterData(Loc);
1528 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001529 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001530 startBuf--; // scan backward (from the decl location) for return type.
1531 const char *startRef = 0, *endRef = 0;
1532 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1533 // Get the locations of the startRef, endRef.
1534 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1535 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1536 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001537 InsertText(LessLoc, "/*", 2);
1538 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001539 }
1540 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001541 if (!proto)
1542 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001543 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001544 const char *startBuf = SM->getCharacterData(Loc);
1545 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001546 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1547 if (needToScanForQualifiers(proto->getArgType(i))) {
1548 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001549
Steve Naroffd5255f52007-11-01 13:24:47 +00001550 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001551 // scan forward (from the decl location) for argument types.
1552 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001553 const char *startRef = 0, *endRef = 0;
1554 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1555 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001556 SourceLocation LessLoc =
1557 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1558 SourceLocation GreaterLoc =
1559 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001560 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001561 InsertText(LessLoc, "/*", 2);
1562 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001563 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001564 startBuf = ++endBuf;
1565 }
1566 else {
1567 while (*startBuf != ')' && *startBuf != ',')
1568 startBuf++; // scan forward (from the decl location) for argument types.
1569 startBuf++;
1570 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001571 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001572}
1573
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001574// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001575void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001576 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1577 llvm::SmallVector<QualType, 16> ArgTys;
1578 ArgTys.push_back(Context->getPointerType(
1579 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001580 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001581 &ArgTys[0], ArgTys.size(),
1582 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001583 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001584 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001585 SelGetUidIdent, getFuncType,
1586 FunctionDecl::Extern, false, 0);
1587}
1588
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001589// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001590void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001591 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1592 llvm::SmallVector<QualType, 16> ArgTys;
1593 ArgTys.push_back(Context->getPointerType(
1594 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001595 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001596 &ArgTys[0], ArgTys.size(),
1597 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001598 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001599 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001600 SelGetProtoIdent, getFuncType,
1601 FunctionDecl::Extern, false, 0);
1602}
1603
Steve Naroffb29b4272008-04-14 22:03:09 +00001604void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001605 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001606 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001607 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001608 return;
1609 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001610 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001611}
1612
Steve Naroffc0a123c2008-03-11 17:37:02 +00001613// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001614void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001615 if (SuperContructorFunctionDecl)
1616 return;
1617 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1618 llvm::SmallVector<QualType, 16> ArgTys;
1619 QualType argT = Context->getObjCIdType();
1620 assert(!argT.isNull() && "Can't find 'id' type");
1621 ArgTys.push_back(argT);
1622 ArgTys.push_back(argT);
1623 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1624 &ArgTys[0], ArgTys.size(),
1625 false);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001626 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001627 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001628 msgSendIdent, msgSendType,
1629 FunctionDecl::Extern, false, 0);
1630}
1631
Steve Naroff09b266e2007-10-30 23:14:51 +00001632// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001633void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001634 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1635 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001636 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001637 assert(!argT.isNull() && "Can't find 'id' type");
1638 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001639 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001640 assert(!argT.isNull() && "Can't find 'SEL' type");
1641 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001642 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001643 &ArgTys[0], ArgTys.size(),
1644 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001645 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001646 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001647 msgSendIdent, msgSendType,
1648 FunctionDecl::Extern, false, 0);
1649}
1650
Steve Naroff874e2322007-11-15 10:28:18 +00001651// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001652void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001653 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1654 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001655 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001656 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001657 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001658 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1659 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1660 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001661 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001662 assert(!argT.isNull() && "Can't find 'SEL' type");
1663 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001664 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001665 &ArgTys[0], ArgTys.size(),
1666 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001667 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001668 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001669 msgSendIdent, msgSendType,
1670 FunctionDecl::Extern, false, 0);
1671}
1672
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001673// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001674void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001675 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1676 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001677 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001678 assert(!argT.isNull() && "Can't find 'id' type");
1679 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001680 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001681 assert(!argT.isNull() && "Can't find 'SEL' type");
1682 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001683 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001684 &ArgTys[0], ArgTys.size(),
1685 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001686 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001687 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001688 msgSendIdent, msgSendType,
1689 FunctionDecl::Extern, false, 0);
1690}
1691
1692// SynthMsgSendSuperStretFunctionDecl -
1693// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001694void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001695 IdentifierInfo *msgSendIdent =
1696 &Context->Idents.get("objc_msgSendSuper_stret");
1697 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001698 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001699 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001700 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001701 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1702 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1703 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001704 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001705 assert(!argT.isNull() && "Can't find 'SEL' type");
1706 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001707 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001708 &ArgTys[0], ArgTys.size(),
1709 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001710 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001711 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001712 msgSendIdent, msgSendType,
1713 FunctionDecl::Extern, false, 0);
1714}
1715
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001716// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001717void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001718 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1719 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001720 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001721 assert(!argT.isNull() && "Can't find 'id' type");
1722 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001723 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001724 assert(!argT.isNull() && "Can't find 'SEL' type");
1725 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001726 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001727 &ArgTys[0], ArgTys.size(),
1728 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001729 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001730 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001731 msgSendIdent, msgSendType,
1732 FunctionDecl::Extern, false, 0);
1733}
1734
Steve Naroff09b266e2007-10-30 23:14:51 +00001735// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001736void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001737 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1738 llvm::SmallVector<QualType, 16> ArgTys;
1739 ArgTys.push_back(Context->getPointerType(
1740 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001741 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001742 &ArgTys[0], ArgTys.size(),
1743 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001744 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001745 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001746 getClassIdent, getClassType,
1747 FunctionDecl::Extern, false, 0);
1748}
1749
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001750// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001751void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001752 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1753 llvm::SmallVector<QualType, 16> ArgTys;
1754 ArgTys.push_back(Context->getPointerType(
1755 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001756 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001757 &ArgTys[0], ArgTys.size(),
1758 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001759 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001760 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001761 getClassIdent, getClassType,
1762 FunctionDecl::Extern, false, 0);
1763}
1764
Steve Naroffb29b4272008-04-14 22:03:09 +00001765Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001766 QualType strType = getConstantStringStructType();
1767
1768 std::string S = "__NSConstantStringImpl_";
1769 S += utostr(NumObjCStringLiterals++);
1770
Steve Naroffba92b2e2008-03-27 22:29:16 +00001771 Preamble += "static __NSConstantStringImpl " + S;
1772 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1773 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001774 // The pretty printer for StringLiteral handles escape characters properly.
1775 std::ostringstream prettyBuf;
1776 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001777 Preamble += prettyBuf.str();
1778 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001779 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001780 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001781
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001782 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001783 &Context->Idents.get(S.c_str()), strType,
1784 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001785 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1786 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1787 Context->getPointerType(DRE->getType()),
1788 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001789 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001790 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001791 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001792 delete Exp;
1793 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001794}
1795
Steve Naroffb29b4272008-04-14 22:03:09 +00001796ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001797 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001798 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1799
1800 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1801 if (!CE) return 0;
1802
1803 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1804 if (!DRE) return 0;
1805
1806 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1807 if (!PVD) return 0;
1808
1809 if (strcmp(PVD->getName(), "self") != 0)
1810 return 0;
1811
1812 // is this id<P1..> type?
1813 if (CE->getType()->isObjCQualifiedIdType())
1814 return 0;
1815 const PointerType *PT = CE->getType()->getAsPointerType();
1816 if (!PT) return 0;
1817
1818 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1819 if (!IT) return 0;
1820
1821 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1822 return 0;
1823
1824 return IT->getDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001825}
1826
1827// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001828QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001829 if (!SuperStructDecl) {
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001830 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001831 SourceLocation(),
1832 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001833 QualType FieldTypes[2];
1834
1835 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001836 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001837 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001838 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001839 // Create fields
1840 FieldDecl *FieldDecls[2];
1841
1842 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001843 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001844 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001845
1846 SuperStructDecl->defineBody(FieldDecls, 4);
1847 }
1848 return Context->getTagDeclType(SuperStructDecl);
1849}
1850
Steve Naroffb29b4272008-04-14 22:03:09 +00001851QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001852 if (!ConstantStringDecl) {
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001853 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001854 SourceLocation(),
1855 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001856 QualType FieldTypes[4];
1857
1858 // struct objc_object *receiver;
1859 FieldTypes[0] = Context->getObjCIdType();
1860 // int flags;
1861 FieldTypes[1] = Context->IntTy;
1862 // char *str;
1863 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1864 // long length;
1865 FieldTypes[3] = Context->LongTy;
1866 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001867 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001868
1869 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001870 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001871 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001872
1873 ConstantStringDecl->defineBody(FieldDecls, 4);
1874 }
1875 return Context->getTagDeclType(ConstantStringDecl);
1876}
1877
Steve Naroffb29b4272008-04-14 22:03:09 +00001878Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001879 if (!SelGetUidFunctionDecl)
1880 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001881 if (!MsgSendFunctionDecl)
1882 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001883 if (!MsgSendSuperFunctionDecl)
1884 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001885 if (!MsgSendStretFunctionDecl)
1886 SynthMsgSendStretFunctionDecl();
1887 if (!MsgSendSuperStretFunctionDecl)
1888 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001889 if (!MsgSendFpretFunctionDecl)
1890 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001891 if (!GetClassFunctionDecl)
1892 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001893 if (!GetMetaClassFunctionDecl)
1894 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001895
Steve Naroff874e2322007-11-15 10:28:18 +00001896 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001897 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1898 // May need to use objc_msgSend_stret() as well.
1899 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001900 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001901 QualType resultType = mDecl->getResultType();
1902 if (resultType.getCanonicalType()->isStructureType()
1903 || resultType.getCanonicalType()->isUnionType())
1904 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001905 else if (resultType.getCanonicalType()->isRealFloatingType())
1906 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001907 }
Steve Naroff874e2322007-11-15 10:28:18 +00001908
Steve Naroff934f2762007-10-24 22:48:43 +00001909 // Synthesize a call to objc_msgSend().
1910 llvm::SmallVector<Expr*, 8> MsgExprs;
1911 IdentifierInfo *clsName = Exp->getClassName();
1912
1913 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1914 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001915 if (!strcmp(clsName->getName(), "super")) {
1916 MsgSendFlavor = MsgSendSuperFunctionDecl;
1917 if (MsgSendStretFlavor)
1918 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1919 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1920
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001921 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001922 CurMethodDecl->getClassInterface()->getSuperClass();
1923
1924 llvm::SmallVector<Expr*, 4> InitExprs;
1925
1926 // set the receiver to self, the first argument to all methods.
1927 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001928 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001929 SourceLocation()));
1930 llvm::SmallVector<Expr*, 8> ClsExprs;
1931 QualType argType = Context->getPointerType(Context->CharTy);
1932 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1933 SuperDecl->getIdentifier()->getLength(),
1934 false, argType, SourceLocation(),
1935 SourceLocation()));
1936 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1937 &ClsExprs[0],
1938 ClsExprs.size());
1939 // To turn off a warning, type-cast to 'id'
1940 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001941 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001942 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1943 // struct objc_super
1944 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001945 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001946
Steve Naroff23f41272008-03-11 18:14:26 +00001947 if (LangOpts.Microsoft) {
1948 SynthSuperContructorFunctionDecl();
1949 // Simulate a contructor call...
1950 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1951 superType, SourceLocation());
1952 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1953 superType, SourceLocation());
1954 } else {
1955 // (struct objc_super) { <exprs from above> }
1956 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1957 &InitExprs[0], InitExprs.size(),
1958 SourceLocation());
1959 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1960 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001961 // struct objc_super *
1962 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1963 Context->getPointerType(SuperRep->getType()),
1964 SourceLocation());
1965 MsgExprs.push_back(Unop);
1966 } else {
1967 llvm::SmallVector<Expr*, 8> ClsExprs;
1968 QualType argType = Context->getPointerType(Context->CharTy);
1969 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1970 clsName->getLength(),
1971 false, argType, SourceLocation(),
1972 SourceLocation()));
1973 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1974 &ClsExprs[0],
1975 ClsExprs.size());
1976 MsgExprs.push_back(Cls);
1977 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001978 } else { // instance message.
1979 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001980
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001981 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001982 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001983 if (MsgSendStretFlavor)
1984 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001985 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1986
1987 llvm::SmallVector<Expr*, 4> InitExprs;
1988
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001989 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001990 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001991 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001992
1993 llvm::SmallVector<Expr*, 8> ClsExprs;
1994 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001995 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1996 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001997 false, argType, SourceLocation(),
1998 SourceLocation()));
1999 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002000 &ClsExprs[0],
2001 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002002 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002003 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002004 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002005 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002006 // struct objc_super
2007 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002008 Expr *SuperRep;
2009
2010 if (LangOpts.Microsoft) {
2011 SynthSuperContructorFunctionDecl();
2012 // Simulate a contructor call...
2013 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2014 superType, SourceLocation());
2015 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2016 superType, SourceLocation());
2017 } else {
2018 // (struct objc_super) { <exprs from above> }
2019 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2020 &InitExprs[0], InitExprs.size(),
2021 SourceLocation());
2022 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2023 }
Steve Naroff874e2322007-11-15 10:28:18 +00002024 // struct objc_super *
2025 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2026 Context->getPointerType(SuperRep->getType()),
2027 SourceLocation());
2028 MsgExprs.push_back(Unop);
2029 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002030 // Remove all type-casts because it may contain objc-style types; e.g.
2031 // Foo<Proto> *.
2032 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2033 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002034 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002035 MsgExprs.push_back(recExpr);
2036 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002037 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002038 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002039 llvm::SmallVector<Expr*, 8> SelExprs;
2040 QualType argType = Context->getPointerType(Context->CharTy);
2041 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2042 Exp->getSelector().getName().size(),
2043 false, argType, SourceLocation(),
2044 SourceLocation()));
2045 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2046 &SelExprs[0], SelExprs.size());
2047 MsgExprs.push_back(SelExp);
2048
2049 // Now push any user supplied arguments.
2050 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002051 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002052 // Make all implicit casts explicit...ICE comes in handy:-)
2053 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2054 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002055 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2056 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002057 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002058 }
2059 // Make id<P...> cast into an 'id' cast.
2060 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002061 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002062 while ((CE = dyn_cast<CastExpr>(userExpr)))
2063 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002064 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002065 userExpr, SourceLocation());
2066 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002067 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002068 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002069 // We've transferred the ownership to MsgExprs. Null out the argument in
2070 // the original expression, since we will delete it below.
2071 Exp->setArg(i, 0);
2072 }
Steve Naroffab972d32007-11-04 22:37:50 +00002073 // Generate the funky cast.
2074 CastExpr *cast;
2075 llvm::SmallVector<QualType, 8> ArgTypes;
2076 QualType returnType;
2077
2078 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002079 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2080 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2081 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002082 ArgTypes.push_back(Context->getObjCIdType());
2083 ArgTypes.push_back(Context->getObjCSelType());
2084 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002085 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002086 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002087 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2088 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002089 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002090 ArgTypes.push_back(t);
2091 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002092 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2093 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002094 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002095 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002096 }
2097 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002098 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002099
2100 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002101 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2102 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002103
2104 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2105 // If we don't do this cast, we get the following bizarre warning/note:
2106 // xx.m:13: warning: function called through a non-compatible type
2107 // xx.m:13: note: if this code is reached, the program will abort
2108 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2109 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002110
Steve Naroffab972d32007-11-04 22:37:50 +00002111 // Now do the "normal" pointer to function cast.
2112 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002113 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002114 // If we don't have a method decl, force a variadic cast.
2115 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002116 castType = Context->getPointerType(castType);
2117 cast = new CastExpr(castType, cast, SourceLocation());
2118
2119 // Don't forget the parens to enforce the proper binding.
2120 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2121
2122 const FunctionType *FT = msgSendType->getAsFunctionType();
2123 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2124 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002125 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002126 if (MsgSendStretFlavor) {
2127 // We have the method which returns a struct/union. Must also generate
2128 // call to objc_msgSend_stret and hang both varieties on a conditional
2129 // expression which dictate which one to envoke depending on size of
2130 // method's return type.
2131
2132 // Create a reference to the objc_msgSend_stret() declaration.
2133 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2134 SourceLocation());
2135 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2136 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2137 SourceLocation());
2138 // Now do the "normal" pointer to function cast.
2139 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002140 &ArgTypes[0], ArgTypes.size(),
2141 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002142 castType = Context->getPointerType(castType);
2143 cast = new CastExpr(castType, cast, SourceLocation());
2144
2145 // Don't forget the parens to enforce the proper binding.
2146 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2147
2148 FT = msgSendType->getAsFunctionType();
2149 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2150 FT->getResultType(), SourceLocation());
2151
2152 // Build sizeof(returnType)
2153 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2154 returnType, Context->getSizeType(),
2155 SourceLocation(), SourceLocation());
2156 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2157 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2158 // For X86 it is more complicated and some kind of target specific routine
2159 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002160 unsigned IntSize =
2161 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002162 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2163 Context->IntTy,
2164 SourceLocation());
2165 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2166 BinaryOperator::LE,
2167 Context->IntTy,
2168 SourceLocation());
2169 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2170 ConditionalOperator *CondExpr =
2171 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002172 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002173 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002174 return ReplacingStmt;
2175}
2176
Steve Naroffb29b4272008-04-14 22:03:09 +00002177Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002178 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002179 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002180 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002181
Chris Lattnere64b7772007-10-24 16:57:36 +00002182 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002183 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002184}
2185
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002186/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2187/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002188Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002189 if (!GetProtocolFunctionDecl)
2190 SynthGetProtocolFunctionDecl();
2191 // Create a call to objc_getProtocol("ProtocolName").
2192 llvm::SmallVector<Expr*, 8> ProtoExprs;
2193 QualType argType = Context->getPointerType(Context->CharTy);
2194 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2195 strlen(Exp->getProtocol()->getName()),
2196 false, argType, SourceLocation(),
2197 SourceLocation()));
2198 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2199 &ProtoExprs[0],
2200 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002201 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002202 delete Exp;
2203 return ProtoExp;
2204
2205}
2206
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002207/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002208/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002209void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002210 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002211 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2212 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002213 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002214 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002215 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002216 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002217 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002218 SourceLocation LocStart = CDecl->getLocStart();
2219 SourceLocation LocEnd = CDecl->getLocEnd();
2220
2221 const char *startBuf = SM->getCharacterData(LocStart);
2222 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002223 // If no ivars and no root or if its root, directly or indirectly,
2224 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002225 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2226 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002227 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002228 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002229 return;
2230 }
2231
2232 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002233 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002234 Result += "\nstruct ";
2235 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002236 if (LangOpts.Microsoft)
2237 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002238
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002239 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002240 const char *cursor = strchr(startBuf, '{');
2241 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002242 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002243
2244 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002245 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002246 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002247 Result = "\n struct ";
2248 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002249 Result += "_IMPL ";
2250 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002251 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002252
2253 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002254 SourceLocation OnePastCurly =
2255 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2256 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002257 }
2258 cursor++; // past '{'
2259
2260 // Now comment out any visibility specifiers.
2261 while (cursor < endBuf) {
2262 if (*cursor == '@') {
2263 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002264 // Skip whitespace.
2265 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2266 /*scan*/;
2267
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002268 // FIXME: presence of @public, etc. inside comment results in
2269 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002270 if (!strncmp(cursor, "public", strlen("public")) ||
2271 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002272 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002273 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002274 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002275 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002276 // FIXME: If there are cases where '<' is used in ivar declaration part
2277 // of user code, then scan the ivar list and use needToScanForQualifiers
2278 // for type checking.
2279 else if (*cursor == '<') {
2280 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002281 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002282 cursor = strchr(cursor, '>');
2283 cursor++;
2284 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002285 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002286 }
Steve Narofffea763e82007-11-14 19:25:57 +00002287 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002288 }
Steve Narofffea763e82007-11-14 19:25:57 +00002289 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002290 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002291 } else { // we don't have any instance variables - insert super struct.
2292 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2293 Result += " {\n struct ";
2294 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002295 Result += "_IMPL ";
2296 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002297 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002298 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002299 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002300 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002301 if (!ObjCSynthesizedStructs.insert(CDecl))
2302 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002303}
2304
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002305// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002306/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002307void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002308 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002309 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002310 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002311 const char *ClassName,
2312 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002313 if (MethodBegin == MethodEnd) return;
2314
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002315 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002316 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002317 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002318 SEL _cmd;
2319 char *method_types;
2320 void *_imp;
2321 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002322 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002323 Result += "\nstruct _objc_method {\n";
2324 Result += "\tSEL _cmd;\n";
2325 Result += "\tchar *method_types;\n";
2326 Result += "\tvoid *_imp;\n";
2327 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002328
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002329 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002330 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002331
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002332 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002333
2334 /* struct {
2335 struct _objc_method_list *next_method;
2336 int method_count;
2337 struct _objc_method method_list[];
2338 }
2339 */
2340 Result += "\nstatic struct {\n";
2341 Result += "\tstruct _objc_method_list *next_method;\n";
2342 Result += "\tint method_count;\n";
2343 Result += "\tstruct _objc_method method_list[";
2344 Result += utostr(MethodEnd-MethodBegin);
2345 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002346 Result += prefix;
2347 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2348 Result += "_METHODS_";
2349 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002350 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002351 Result += IsInstanceMethod ? "inst" : "cls";
2352 Result += "_meth\")))= ";
2353 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002354
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002355 Result += "\t,{{(SEL)\"";
2356 Result += (*MethodBegin)->getSelector().getName().c_str();
2357 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002358 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002359 Result += "\", \"";
2360 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002361 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002362 Result += MethodInternalNames[*MethodBegin];
2363 Result += "}\n";
2364 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2365 Result += "\t ,{(SEL)\"";
2366 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002367 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002368 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002369 Result += "\", \"";
2370 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002371 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002372 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002373 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002374 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002375 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002376}
2377
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002378/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Steve Naroffb29b4272008-04-14 22:03:09 +00002379void RewriteObjC::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002380 int NumProtocols,
2381 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002382 const char *ClassName,
2383 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002384 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002385 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002386 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002387 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002388 // Output struct protocol_methods holder of method selector and type.
Chris Lattnerc8581052008-03-16 20:19:15 +00002389 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002390 /* struct protocol_methods {
2391 SEL _cmd;
2392 char *method_types;
2393 }
2394 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002395 Result += "\nstruct protocol_methods {\n";
2396 Result += "\tSEL _cmd;\n";
2397 Result += "\tchar *method_types;\n";
2398 Result += "};\n";
2399
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002400 objc_protocol_methods = true;
2401 }
Chris Lattnerc8581052008-03-16 20:19:15 +00002402 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2403 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002404 /* struct _objc_protocol_method_list {
2405 int protocol_method_count;
2406 struct protocol_methods protocols[];
2407 }
2408 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002409 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002410 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002411 Result += "\tstruct protocol_methods protocols[";
2412 Result += utostr(NumMethods);
2413 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002414 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002415 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002416 "{\n\t" + utostr(NumMethods) + "\n";
2417
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002418 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002419 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002420 E = PDecl->instmeth_end(); I != E; ++I) {
2421 if (I == PDecl->instmeth_begin())
2422 Result += "\t ,{{(SEL)\"";
2423 else
2424 Result += "\t ,{(SEL)\"";
2425 Result += (*I)->getSelector().getName().c_str();
2426 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002427 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002428 Result += "\", \"";
2429 Result += MethodTypeString;
2430 Result += "\"}\n";
2431 }
2432 Result += "\t }\n};\n";
2433 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002434
2435 // Output class methods declared in this protocol.
Chris Lattnerc8581052008-03-16 20:19:15 +00002436 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002437 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002438 /* struct _objc_protocol_method_list {
2439 int protocol_method_count;
2440 struct protocol_methods protocols[];
2441 }
2442 */
2443 Result += "\nstatic struct {\n";
2444 Result += "\tint protocol_method_count;\n";
2445 Result += "\tstruct protocol_methods protocols[";
2446 Result += utostr(NumMethods);
2447 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002448 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002449 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002450 "{\n\t";
2451 Result += utostr(NumMethods);
2452 Result += "\n";
2453
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002454 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002455 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002456 E = PDecl->classmeth_end(); I != E; ++I) {
2457 if (I == PDecl->classmeth_begin())
2458 Result += "\t ,{{(SEL)\"";
2459 else
2460 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002461 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002462 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002463 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002464 Result += "\", \"";
2465 Result += MethodTypeString;
2466 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002467 }
2468 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002469 }
2470 // Output:
2471 /* struct _objc_protocol {
2472 // Objective-C 1.0 extensions
2473 struct _objc_protocol_extension *isa;
2474 char *protocol_name;
2475 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002476 struct _objc_protocol_method_list *instance_methods;
2477 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002478 };
2479 */
2480 static bool objc_protocol = false;
2481 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002482 Result += "\nstruct _objc_protocol {\n";
2483 Result += "\tstruct _objc_protocol_extension *isa;\n";
2484 Result += "\tchar *protocol_name;\n";
2485 Result += "\tstruct _objc_protocol **protocol_list;\n";
2486 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2487 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2488 Result += "};\n";
2489
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002490 objc_protocol = true;
2491 }
2492
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002493 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2494 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002495 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002496 "{\n\t0, \"";
2497 Result += PDecl->getName();
2498 Result += "\", 0, ";
Chris Lattnerc8581052008-03-16 20:19:15 +00002499 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002500 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002501 Result += PDecl->getName();
2502 Result += ", ";
2503 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002504 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002505 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002506 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002507 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002508 Result += PDecl->getName();
2509 Result += "\n";
2510 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002511 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002512 Result += "0\n";
2513 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002514 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002515 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002516 /* struct _objc_protocol_list {
2517 struct _objc_protocol_list *next;
2518 int protocol_count;
2519 struct _objc_protocol *class_protocols[];
2520 }
2521 */
2522 Result += "\nstatic struct {\n";
2523 Result += "\tstruct _objc_protocol_list *next;\n";
2524 Result += "\tint protocol_count;\n";
2525 Result += "\tstruct _objc_protocol *class_protocols[";
2526 Result += utostr(NumProtocols);
2527 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002528 Result += prefix;
2529 Result += "_PROTOCOLS_";
2530 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002531 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002532 "{\n\t0, ";
2533 Result += utostr(NumProtocols);
2534 Result += "\n";
2535
2536 Result += "\t,{&_OBJC_PROTOCOL_";
2537 Result += Protocols[0]->getName();
2538 Result += " \n";
2539
2540 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002541 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002542 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002543 Result += PDecl->getName();
2544 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002545 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002546 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002547 }
2548}
2549
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002550/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002551/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002552void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002553 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002554 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002555 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002556 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002557 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2558 CDecl = CDecl->getNextClassCategory())
2559 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2560 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002561
Chris Lattnereb44eee2007-12-23 01:40:15 +00002562 std::string FullCategoryName = ClassDecl->getName();
2563 FullCategoryName += '_';
2564 FullCategoryName += IDecl->getName();
2565
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002566 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002567 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002568 true, "CATEGORY_", FullCategoryName.c_str(),
2569 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002570
2571 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002572 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002573 false, "CATEGORY_", FullCategoryName.c_str(),
2574 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002575
2576 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002577 // Null CDecl is case of a category implementation with no category interface
2578 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002579 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002580 CDecl->getNumReferencedProtocols(),
2581 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002582 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002583
2584 /* struct _objc_category {
2585 char *category_name;
2586 char *class_name;
2587 struct _objc_method_list *instance_methods;
2588 struct _objc_method_list *class_methods;
2589 struct _objc_protocol_list *protocols;
2590 // Objective-C 1.0 extensions
2591 uint32_t size; // sizeof (struct _objc_category)
2592 struct _objc_property_list *instance_properties; // category's own
2593 // @property decl.
2594 };
2595 */
2596
2597 static bool objc_category = false;
2598 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002599 Result += "\nstruct _objc_category {\n";
2600 Result += "\tchar *category_name;\n";
2601 Result += "\tchar *class_name;\n";
2602 Result += "\tstruct _objc_method_list *instance_methods;\n";
2603 Result += "\tstruct _objc_method_list *class_methods;\n";
2604 Result += "\tstruct _objc_protocol_list *protocols;\n";
2605 Result += "\tunsigned int size;\n";
2606 Result += "\tstruct _objc_property_list *instance_properties;\n";
2607 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002608 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002609 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002610 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2611 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002612 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002613 Result += IDecl->getName();
2614 Result += "\"\n\t, \"";
2615 Result += ClassDecl->getName();
2616 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002617
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002618 if (IDecl->getNumInstanceMethods() > 0) {
2619 Result += "\t, (struct _objc_method_list *)"
2620 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2621 Result += FullCategoryName;
2622 Result += "\n";
2623 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002624 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002625 Result += "\t, 0\n";
2626 if (IDecl->getNumClassMethods() > 0) {
2627 Result += "\t, (struct _objc_method_list *)"
2628 "&_OBJC_CATEGORY_CLASS_METHODS_";
2629 Result += FullCategoryName;
2630 Result += "\n";
2631 }
2632 else
2633 Result += "\t, 0\n";
2634
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002635 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002636 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2637 Result += FullCategoryName;
2638 Result += "\n";
2639 }
2640 else
2641 Result += "\t, 0\n";
2642 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002643}
2644
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002645/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2646/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002647void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002648 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002649 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002650 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002651 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002652 if (LangOpts.Microsoft)
2653 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002654 Result += ", ";
2655 Result += ivar->getName();
2656 Result += ")";
2657}
2658
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002659//===----------------------------------------------------------------------===//
2660// Meta Data Emission
2661//===----------------------------------------------------------------------===//
2662
Steve Naroffb29b4272008-04-14 22:03:09 +00002663void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002664 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002665 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002666
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002667 // Explictly declared @interface's are already synthesized.
2668 if (CDecl->ImplicitInterfaceDecl()) {
2669 // FIXME: Implementation of a class with no @interface (legacy) doese not
2670 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002671 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002672 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002673
Chris Lattnerbe6df082007-12-12 07:56:42 +00002674 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002675 unsigned NumIvars = !IDecl->ivar_empty()
2676 ? IDecl->ivar_size()
2677 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002678 if (NumIvars > 0) {
2679 static bool objc_ivar = false;
2680 if (!objc_ivar) {
2681 /* struct _objc_ivar {
2682 char *ivar_name;
2683 char *ivar_type;
2684 int ivar_offset;
2685 };
2686 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002687 Result += "\nstruct _objc_ivar {\n";
2688 Result += "\tchar *ivar_name;\n";
2689 Result += "\tchar *ivar_type;\n";
2690 Result += "\tint ivar_offset;\n";
2691 Result += "};\n";
2692
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002693 objc_ivar = true;
2694 }
2695
Steve Naroff946a6932008-03-11 00:12:29 +00002696 /* struct {
2697 int ivar_count;
2698 struct _objc_ivar ivar_list[nIvars];
2699 };
2700 */
2701 Result += "\nstatic struct {\n";
2702 Result += "\tint ivar_count;\n";
2703 Result += "\tstruct _objc_ivar ivar_list[";
2704 Result += utostr(NumIvars);
2705 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002706 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002707 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002708 "{\n\t";
2709 Result += utostr(NumIvars);
2710 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002711
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002712 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002713 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002714 IVI = IDecl->ivar_begin();
2715 IVE = IDecl->ivar_end();
2716 } else {
2717 IVI = CDecl->ivar_begin();
2718 IVE = CDecl->ivar_end();
2719 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002720 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002721 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002722 Result += "\", \"";
2723 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002724 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2725 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002726 Result += StrEncoding;
2727 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002728 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002729 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002730 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002731 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002732 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002733 Result += "\", \"";
2734 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002735 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2736 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002737 Result += StrEncoding;
2738 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002739 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002740 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002741 }
2742
2743 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002744 }
2745
2746 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002747 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002748 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002749
2750 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002751 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002752 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002753
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002754 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002755 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002756 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002757 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002758
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002759
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002760 // Declaration of class/meta-class metadata
2761 /* struct _objc_class {
2762 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002763 const char *super_class_name;
2764 char *name;
2765 long version;
2766 long info;
2767 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002768 struct _objc_ivar_list *ivars;
2769 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002770 struct objc_cache *cache;
2771 struct objc_protocol_list *protocols;
2772 const char *ivar_layout;
2773 struct _objc_class_ext *ext;
2774 };
2775 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002776 static bool objc_class = false;
2777 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002778 Result += "\nstruct _objc_class {\n";
2779 Result += "\tstruct _objc_class *isa;\n";
2780 Result += "\tconst char *super_class_name;\n";
2781 Result += "\tchar *name;\n";
2782 Result += "\tlong version;\n";
2783 Result += "\tlong info;\n";
2784 Result += "\tlong instance_size;\n";
2785 Result += "\tstruct _objc_ivar_list *ivars;\n";
2786 Result += "\tstruct _objc_method_list *methods;\n";
2787 Result += "\tstruct objc_cache *cache;\n";
2788 Result += "\tstruct _objc_protocol_list *protocols;\n";
2789 Result += "\tconst char *ivar_layout;\n";
2790 Result += "\tstruct _objc_class_ext *ext;\n";
2791 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002792 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002793 }
2794
2795 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002796 ObjCInterfaceDecl *RootClass = 0;
2797 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002798 while (SuperClass) {
2799 RootClass = SuperClass;
2800 SuperClass = SuperClass->getSuperClass();
2801 }
2802 SuperClass = CDecl->getSuperClass();
2803
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002804 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2805 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002806 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002807 "{\n\t(struct _objc_class *)\"";
2808 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2809 Result += "\"";
2810
2811 if (SuperClass) {
2812 Result += ", \"";
2813 Result += SuperClass->getName();
2814 Result += "\", \"";
2815 Result += CDecl->getName();
2816 Result += "\"";
2817 }
2818 else {
2819 Result += ", 0, \"";
2820 Result += CDecl->getName();
2821 Result += "\"";
2822 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002823 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002824 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002825 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002826 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002827 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002828 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002829 Result += "\n";
2830 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002831 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002832 Result += ", 0\n";
2833 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002834 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002835 Result += CDecl->getName();
2836 Result += ",0,0\n";
2837 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002838 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002839 Result += "\t,0,0,0,0\n";
2840 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002841
2842 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002843 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2844 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002845 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002846 "{\n\t&_OBJC_METACLASS_";
2847 Result += CDecl->getName();
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 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002860 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002861 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002862 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002863 Result += ",0";
2864 else {
2865 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002866 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002867 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002868 if (LangOpts.Microsoft)
2869 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002870 Result += ")";
2871 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002872 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002873 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002874 Result += CDecl->getName();
2875 Result += "\n\t";
2876 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002877 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002878 Result += ",0";
2879 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002880 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002881 Result += CDecl->getName();
2882 Result += ", 0\n\t";
2883 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002884 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002885 Result += ",0,0";
2886 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002887 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002888 Result += CDecl->getName();
2889 Result += ", 0,0\n";
2890 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002891 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002892 Result += ",0,0,0\n";
2893 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002894}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002895
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002896/// RewriteImplementations - This routine rewrites all method implementations
2897/// and emits meta-data.
2898
Steve Naroffb29b4272008-04-14 22:03:09 +00002899void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002900 int ClsDefCount = ClassImplementation.size();
2901 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002902
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002903 if (ClsDefCount == 0 && CatDefCount == 0)
2904 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002905 // Rewrite implemented methods
2906 for (int i = 0; i < ClsDefCount; i++)
2907 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002908
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002909 for (int i = 0; i < CatDefCount; i++)
2910 RewriteImplementationDecl(CategoryImplementation[i]);
2911
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002912 // This is needed for use of offsetof
Steve Naroffb10f2732008-04-04 22:58:22 +00002913 Result += "#define offsetof(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002914 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002915 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002916 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002917
2918 // For each implemented category, write out all its meta data.
2919 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002920 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002921
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002922 // Write objc_symtab metadata
2923 /*
2924 struct _objc_symtab
2925 {
2926 long sel_ref_cnt;
2927 SEL *refs;
2928 short cls_def_cnt;
2929 short cat_def_cnt;
2930 void *defs[cls_def_cnt + cat_def_cnt];
2931 };
2932 */
2933
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002934 Result += "\nstruct _objc_symtab {\n";
2935 Result += "\tlong sel_ref_cnt;\n";
2936 Result += "\tSEL *refs;\n";
2937 Result += "\tshort cls_def_cnt;\n";
2938 Result += "\tshort cat_def_cnt;\n";
2939 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2940 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002941
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002942 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002943 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002944 Result += "\t0, 0, " + utostr(ClsDefCount)
2945 + ", " + utostr(CatDefCount) + "\n";
2946 for (int i = 0; i < ClsDefCount; i++) {
2947 Result += "\t,&_OBJC_CLASS_";
2948 Result += ClassImplementation[i]->getName();
2949 Result += "\n";
2950 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002951
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002952 for (int i = 0; i < CatDefCount; i++) {
2953 Result += "\t,&_OBJC_CATEGORY_";
2954 Result += CategoryImplementation[i]->getClassInterface()->getName();
2955 Result += "_";
2956 Result += CategoryImplementation[i]->getName();
2957 Result += "\n";
2958 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002959
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002960 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002961
2962 // Write objc_module metadata
2963
2964 /*
2965 struct _objc_module {
2966 long version;
2967 long size;
2968 const char *name;
2969 struct _objc_symtab *symtab;
2970 }
2971 */
2972
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002973 Result += "\nstruct _objc_module {\n";
2974 Result += "\tlong version;\n";
2975 Result += "\tlong size;\n";
2976 Result += "\tconst char *name;\n";
2977 Result += "\tstruct _objc_symtab *symtab;\n";
2978 Result += "};\n\n";
2979 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00002980 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002981 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2982 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002983 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002984
2985 if (LangOpts.Microsoft) {
2986 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2987 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2988 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2989 Result += "&_OBJC_MODULES;\n";
2990 Result += "#pragma data_seg(pop)\n\n";
2991 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002992}
Chris Lattner311ff022007-10-16 22:36:42 +00002993
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002994