blob: 724b16e49a8f399a77ea4ccdb9effb2b87f2a421 [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;
Chris Lattner8a12c272007-10-11 18:38:32 +000045 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000046 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000047 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000048
Ted Kremeneka526c5c2008-01-07 19:49:32 +000049 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
50 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
51 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
52 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
53 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000054 llvm::SmallVector<Stmt *, 32> Stmts;
55 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000056 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000057
Steve Naroffd82a9ab2008-03-15 00:55:56 +000058 unsigned NumObjCStringLiterals;
59
Steve Naroffebf2b562007-10-23 23:50:29 +000060 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000061 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000062 FunctionDecl *MsgSendStretFunctionDecl;
63 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000064 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000065 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000066 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000067 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000068 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000069 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000070 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000071
Steve Naroffbeaf2992007-11-03 11:27:19 +000072 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000073 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000074 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000075
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000076 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000077 int BcLabelCount;
78
Steve Naroff874e2322007-11-15 10:28:18 +000079 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000080 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000081 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000082 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000083
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000084 // Needed for header files being rewritten
85 bool IsHeader;
86
Steve Naroffa7b402d2008-03-28 22:26:09 +000087 std::string InFileName;
88 std::string OutFileName;
89
Steve Naroffba92b2e2008-03-27 22:29:16 +000090 std::string Preamble;
91
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000092 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000093 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000094 void Initialize(ASTContext &context);
95
Chris Lattner8a12c272007-10-11 18:38:32 +000096
Chris Lattnerf04da132007-10-24 17:06:59 +000097 // Top Level Driver code.
98 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000099 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000100 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000101 Diagnostic &D, const LangOptions &LOpts);
Steve Naroffb29b4272008-04-14 22:03:09 +0000102 ~RewriteObjC();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000103
104 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000105 // If replacement succeeded or warning disabled return with no warning.
106 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000107 return;
108
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000109 SourceRange Range = Old->getSourceRange();
110 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
111 0, 0, &Range, 1);
112 }
113
Steve Naroffba92b2e2008-03-27 22:29:16 +0000114 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
115 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000116 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000117 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000118 SilenceRewriteMacroWarning)
119 return;
120
121 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
122 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000123
Chris Lattneraadaf782008-01-31 19:51:04 +0000124 void RemoveText(SourceLocation Loc, unsigned StrLen) {
125 // If removal succeeded or warning disabled return with no warning.
126 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
127 return;
128
129 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
130 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000131
Chris Lattneraadaf782008-01-31 19:51:04 +0000132 void ReplaceText(SourceLocation Start, unsigned OrigLength,
133 const char *NewStr, unsigned NewLength) {
134 // If removal succeeded or warning disabled return with no warning.
135 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
136 SilenceRewriteMacroWarning)
137 return;
138
139 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
140 }
141
Chris Lattnerf04da132007-10-24 17:06:59 +0000142 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000143 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000144 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000145 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000146 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
147 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000148 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000149 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
150 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
151 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
152 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
153 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000154 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000155 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000156 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000157 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000158 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000159 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000160 QualType getConstantStringStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000163 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000164 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000165 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000166 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000167 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000168 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000169 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000170 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000171 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000172 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
173 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
174 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000175 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
176 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000177 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
178 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000179 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000180 Stmt *RewriteBreakStmt(BreakStmt *S);
181 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000182 void SynthCountByEnumWithState(std::string &buf);
183
Steve Naroff09b266e2007-10-30 23:14:51 +0000184 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000185 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000186 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000187 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000188 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000189 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000190 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000191 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000192 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000193 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000194
Chris Lattnerf04da132007-10-24 17:06:59 +0000195 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000196 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000197 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000198
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000199 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000200 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000201
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000202 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
203 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000204 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000205 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000206 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000207 const char *ClassName,
208 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000209
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000210 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000211 int NumProtocols,
212 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000213 const char *ClassName,
214 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000215 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000216 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000217 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
218 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000219 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000220 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000221 };
222}
223
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000224static bool IsHeaderFile(const std::string &Filename) {
225 std::string::size_type DotPos = Filename.rfind('.');
226
227 if (DotPos == std::string::npos) {
228 // no file extension
229 return false;
230 }
231
232 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
233 // C header: .h
234 // C++ header: .hh or .H;
235 return Ext == "h" || Ext == "hh" || Ext == "H";
236}
237
Steve Naroffb29b4272008-04-14 22:03:09 +0000238RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000239 Diagnostic &D, const LangOptions &LOpts)
240 : Diags(D), LangOpts(LOpts) {
241 IsHeader = IsHeaderFile(inFile);
242 InFileName = inFile;
243 OutFileName = outFile;
244 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
245 "rewriting sub-expression within a macro (may not be correct)");
246}
247
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000248ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000249 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000250 Diagnostic &Diags,
251 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000252 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000253}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000254
Steve Naroffb29b4272008-04-14 22:03:09 +0000255void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000256 Context = &context;
257 SM = &Context->getSourceManager();
258 MsgSendFunctionDecl = 0;
259 MsgSendSuperFunctionDecl = 0;
260 MsgSendStretFunctionDecl = 0;
261 MsgSendSuperStretFunctionDecl = 0;
262 MsgSendFpretFunctionDecl = 0;
263 GetClassFunctionDecl = 0;
264 GetMetaClassFunctionDecl = 0;
265 SelGetUidFunctionDecl = 0;
266 CFStringFunctionDecl = 0;
267 GetProtocolFunctionDecl = 0;
268 ConstantStringClassReference = 0;
269 NSStringRecord = 0;
270 CurMethodDecl = 0;
271 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000272 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000273 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000274 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000275 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000276
277 // Get the ID and start/end of the main file.
278 MainFileID = SM->getMainFileID();
279 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
280 MainFileStart = MainBuf->getBufferStart();
281 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000282
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000283 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000284
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000285 // declaring objc_selector outside the parameter list removes a silly
286 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000287 if (IsHeader)
288 Preamble = "#pragma once\n";
289 Preamble += "struct objc_selector; struct objc_class;\n";
290 Preamble += "#ifndef OBJC_SUPER\n";
291 Preamble += "struct objc_super { struct objc_object *object; ";
292 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000293 if (LangOpts.Microsoft) {
294 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000295 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
296 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000297 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000298 Preamble += "};\n";
299 Preamble += "#define OBJC_SUPER\n";
300 Preamble += "#endif\n";
301 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
302 Preamble += "typedef struct objc_object Protocol;\n";
303 Preamble += "#define _REWRITER_typedef_Protocol\n";
304 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000305 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000306 Preamble += "extern \"C\" {\n";
307 Preamble += "struct objc_object *objc_msgSend";
308 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
309 Preamble += "extern struct objc_object *objc_msgSendSuper";
310 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
311 Preamble += "extern struct objc_object *objc_msgSend_stret";
312 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
313 Preamble += "extern struct objc_object *objc_msgSendSuper_stret";
314 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
315 Preamble += "extern struct objc_object *objc_msgSend_fpret";
316 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
317 Preamble += "struct objc_object *objc_getClass";
318 Preamble += "(const char *);\n";
319 Preamble += "extern struct objc_object *objc_getMetaClass";
320 Preamble += "(const char *);\n";
321 Preamble += "extern void objc_exception_throw(struct objc_object *);\n";
322 Preamble += "extern void objc_exception_try_enter(void *);\n";
323 Preamble += "extern void objc_exception_try_exit(void *);\n";
324 Preamble += "extern struct objc_object *objc_exception_extract(void *);\n";
325 Preamble += "extern int objc_exception_match";
326 Preamble += "(struct objc_class *, struct objc_object *, ...);\n";
327 Preamble += "extern Protocol *objc_getProtocol(const char *);\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000328 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000329 Preamble += "} // end extern \"C\"\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000330 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
331 Preamble += "struct __objcFastEnumerationState {\n\t";
332 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000333 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000334 Preamble += "unsigned long *mutationsPtr;\n\t";
335 Preamble += "unsigned long extra[5];\n};\n";
336 Preamble += "#define __FASTENUMERATIONSTATE\n";
337 Preamble += "#endif\n";
338 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
339 Preamble += "struct __NSConstantStringImpl {\n";
340 Preamble += " int *isa;\n";
341 Preamble += " int flags;\n";
342 Preamble += " char *str;\n";
343 Preamble += " long length;\n";
344 Preamble += "};\n";
345 Preamble += "extern int __CFConstantStringClassReference[];\n";
346 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
347 Preamble += "#endif\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000348 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000349 Preamble += "#define __attribute__(X)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000350}
351
352
Chris Lattnerf04da132007-10-24 17:06:59 +0000353//===----------------------------------------------------------------------===//
354// Top Level Driver Code
355//===----------------------------------------------------------------------===//
356
Steve Naroffb29b4272008-04-14 22:03:09 +0000357void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000358 // Two cases: either the decl could be in the main file, or it could be in a
359 // #included file. If the former, rewrite it now. If the later, check to see
360 // if we rewrote the #include/#import.
361 SourceLocation Loc = D->getLocation();
362 Loc = SM->getLogicalLoc(Loc);
363
364 // If this is for a builtin, ignore it.
365 if (Loc.isInvalid()) return;
366
Steve Naroffebf2b562007-10-23 23:50:29 +0000367 // Look for built-in declarations that we need to refer during the rewrite.
368 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000369 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000370 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000371 // declared in <Foundation/NSString.h>
372 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
373 ConstantStringClassReference = FVD;
374 return;
375 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000376 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000377 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000378 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000379 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000380 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000381 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000382 } else if (ObjCForwardProtocolDecl *FP =
383 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000384 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000385 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000386 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000387 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000388 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000389}
390
Chris Lattnerf04da132007-10-24 17:06:59 +0000391/// HandleDeclInMainFile - This is called for each top-level decl defined in the
392/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000393void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000394 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
395 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000396 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000397
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000398 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000399 if (Stmt *Body = MD->getBody()) {
400 //Body->dump();
401 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000402 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000403 CurMethodDecl = 0;
404 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000405 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000406 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000407 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000408 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000409 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000410 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000411 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000412 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000413 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000414 if (VD->getInit())
415 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
416 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000417 // Nothing yet.
418}
419
Steve Naroffb29b4272008-04-14 22:03:09 +0000420RewriteObjC::~RewriteObjC() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000421 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000422
423 // Rewrite tabs if we care.
424 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000425
Steve Naroffa7b402d2008-03-28 22:26:09 +0000426 if (Diags.hasErrorOccurred())
427 return;
428
429 // Create the output file.
430
431 std::ostream *OutFile;
432 if (OutFileName == "-") {
433 OutFile = llvm::cout.stream();
434 } else if (!OutFileName.empty()) {
435 OutFile = new std::ofstream(OutFileName.c_str(),
436 std::ios_base::binary|std::ios_base::out);
437 } else if (InFileName == "-") {
438 OutFile = llvm::cout.stream();
439 } else {
440 llvm::sys::Path Path(InFileName);
441 Path.eraseSuffix();
442 Path.appendSuffix("cpp");
443 OutFile = new std::ofstream(Path.toString().c_str(),
444 std::ios_base::binary|std::ios_base::out);
445 }
446
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000447 RewriteInclude();
448
Steve Naroffba92b2e2008-03-27 22:29:16 +0000449 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
450 Preamble.c_str(), Preamble.size(), false);
451
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000452 // Rewrite Objective-c meta data*
453 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000454 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000455
Chris Lattnerf04da132007-10-24 17:06:59 +0000456 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
457 // we are done.
458 if (const RewriteBuffer *RewriteBuf =
459 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000460 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000461 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000462 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000463 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000464 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000465 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000466 *OutFile << ResultStr;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000467}
468
Chris Lattnerf04da132007-10-24 17:06:59 +0000469//===----------------------------------------------------------------------===//
470// Syntactic (non-AST) Rewriting Code
471//===----------------------------------------------------------------------===//
472
Steve Naroffb29b4272008-04-14 22:03:09 +0000473void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000474 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
475 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
476 const char *MainBufStart = MainBuf.first;
477 const char *MainBufEnd = MainBuf.second;
478 size_t ImportLen = strlen("import");
479 size_t IncludeLen = strlen("include");
480
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000481 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000482 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
483 if (*BufPtr == '#') {
484 if (++BufPtr == MainBufEnd)
485 return;
486 while (*BufPtr == ' ' || *BufPtr == '\t')
487 if (++BufPtr == MainBufEnd)
488 return;
489 if (!strncmp(BufPtr, "import", ImportLen)) {
490 // replace import with include
491 SourceLocation ImportLoc =
492 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000493 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000494 BufPtr += ImportLen;
495 }
496 }
497 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000498}
499
Steve Naroffb29b4272008-04-14 22:03:09 +0000500void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000501 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
502 const char *MainBufStart = MainBuf.first;
503 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000504
Chris Lattnerf04da132007-10-24 17:06:59 +0000505 // Loop over the whole file, looking for tabs.
506 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
507 if (*BufPtr != '\t')
508 continue;
509
510 // Okay, we found a tab. This tab will turn into at least one character,
511 // but it depends on which 'virtual column' it is in. Compute that now.
512 unsigned VCol = 0;
513 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
514 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
515 ++VCol;
516
517 // Okay, now that we know the virtual column, we know how many spaces to
518 // insert. We assume 8-character tab-stops.
519 unsigned Spaces = 8-(VCol & 7);
520
521 // Get the location of the tab.
522 SourceLocation TabLoc =
523 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
524
525 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000526 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000527 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000528}
529
530
Steve Naroffb29b4272008-04-14 22:03:09 +0000531void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000532 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000533 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000534
535 // Get the start location and compute the semi location.
536 SourceLocation startLoc = ClassDecl->getLocation();
537 const char *startBuf = SM->getCharacterData(startLoc);
538 const char *semiPtr = strchr(startBuf, ';');
539
540 // Translate to typedef's that forward reference structs with the same name
541 // as the class. As a convenience, we include the original declaration
542 // as a comment.
543 std::string typedefString;
544 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000545 typedefString.append(startBuf, semiPtr-startBuf+1);
546 typedefString += "\n";
547 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000548 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000549 typedefString += "#ifndef _REWRITER_typedef_";
550 typedefString += ForwardDecl->getName();
551 typedefString += "\n";
552 typedefString += "#define _REWRITER_typedef_";
553 typedefString += ForwardDecl->getName();
554 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000555 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000556 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000557 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000558 }
559
560 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000561 ReplaceText(startLoc, semiPtr-startBuf+1,
562 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000563}
564
Steve Naroffb29b4272008-04-14 22:03:09 +0000565void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000566 SourceLocation LocStart = Method->getLocStart();
567 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000568
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000569 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000570 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000571 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000572 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000573 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000574 }
575}
576
Steve Naroffb29b4272008-04-14 22:03:09 +0000577void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000578{
Chris Lattner55d13b42008-03-16 21:23:50 +0000579 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000580 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000581 SourceLocation Loc = Property->getLocation();
582
Chris Lattneraadaf782008-01-31 19:51:04 +0000583 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000584
585 // FIXME: handle properties that are declared across multiple lines.
586 }
587}
588
Steve Naroffb29b4272008-04-14 22:03:09 +0000589void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000590 SourceLocation LocStart = CatDecl->getLocStart();
591
592 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000593 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000594
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000595 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000596 E = CatDecl->instmeth_end(); I != E; ++I)
597 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000598 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000599 E = CatDecl->classmeth_end(); I != E; ++I)
600 RewriteMethodDeclaration(*I);
601
Steve Naroff423cb562007-10-30 13:30:57 +0000602 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000603 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000604}
605
Steve Naroffb29b4272008-04-14 22:03:09 +0000606void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000607 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000608
Steve Naroff752d6ef2007-10-30 16:42:30 +0000609 SourceLocation LocStart = PDecl->getLocStart();
610
611 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000612 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000613
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000614 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000615 E = PDecl->instmeth_end(); I != E; ++I)
616 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000617 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000618 E = PDecl->classmeth_end(); I != E; ++I)
619 RewriteMethodDeclaration(*I);
620
Steve Naroff752d6ef2007-10-30 16:42:30 +0000621 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000622 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000623 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000624
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000625 // Must comment out @optional/@required
626 const char *startBuf = SM->getCharacterData(LocStart);
627 const char *endBuf = SM->getCharacterData(LocEnd);
628 for (const char *p = startBuf; p < endBuf; p++) {
629 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
630 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000631 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000632 ReplaceText(OptionalLoc, strlen("@optional"),
633 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000634
635 }
636 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
637 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000638 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000639 ReplaceText(OptionalLoc, strlen("@required"),
640 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000641
642 }
643 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000644}
645
Steve Naroffb29b4272008-04-14 22:03:09 +0000646void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000647 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000648 if (LocStart.isInvalid())
649 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000650 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000651 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000652}
653
Steve Naroffb29b4272008-04-14 22:03:09 +0000654void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000655 std::string &ResultStr) {
656 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000657 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000658 ResultStr += "id";
659 else
660 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000661 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000662
663 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000664 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000665
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000666 if (OMD->isInstance())
667 NameStr += "_I_";
668 else
669 NameStr += "_C_";
670
671 NameStr += OMD->getClassInterface()->getName();
672 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000673
674 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000675 if (ObjCCategoryImplDecl *CID =
676 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000677 NameStr += CID->getName();
678 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000679 }
Steve Naroff563b8282008-04-04 22:23:44 +0000680 // Append selector names, replacing ':' with '_'
681 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000682 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000683 else {
684 std::string selString = OMD->getSelector().getName();
685 int len = selString.size();
686 for (int i = 0; i < len; i++)
687 if (selString[i] == ':')
688 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000689 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000690 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000691 // Remember this name for metadata emission
692 MethodInternalNames[OMD] = NameStr;
693 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000694
695 // Rewrite arguments
696 ResultStr += "(";
697
698 // invisible arguments
699 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000700 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000701 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000702 if (!LangOpts.Microsoft) {
703 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
704 ResultStr += "struct ";
705 }
706 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000707 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000708 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000709 }
710 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000711 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000712
713 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000714 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000715 ResultStr += " _cmd";
716
717 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000718 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000719 ParmVarDecl *PDecl = OMD->getParamDecl(i);
720 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000721 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000722 ResultStr += "id";
723 else
724 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000725 ResultStr += " ";
726 ResultStr += PDecl->getName();
727 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000728 if (OMD->isVariadic())
729 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000730 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000731
732}
Steve Naroffb29b4272008-04-14 22:03:09 +0000733void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000734 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
735 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000736
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000737 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000738 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000739 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000740 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000741
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000742 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000743 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
744 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000745 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000746 ObjCMethodDecl *OMD = *I;
747 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000748 SourceLocation LocStart = OMD->getLocStart();
749 SourceLocation LocEnd = OMD->getBody()->getLocStart();
750
751 const char *startBuf = SM->getCharacterData(LocStart);
752 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000753 ReplaceText(LocStart, endBuf-startBuf,
754 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000755 }
756
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000757 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000758 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
759 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000760 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000761 ObjCMethodDecl *OMD = *I;
762 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000763 SourceLocation LocStart = OMD->getLocStart();
764 SourceLocation LocEnd = OMD->getBody()->getLocStart();
765
766 const char *startBuf = SM->getCharacterData(LocStart);
767 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000768 ReplaceText(LocStart, endBuf-startBuf,
769 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000770 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000771 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000772 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000773 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000774 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000775}
776
Steve Naroffb29b4272008-04-14 22:03:09 +0000777void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000778 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000779 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000780 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000781 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000782 ResultStr += ClassDecl->getName();
783 ResultStr += "\n";
784 ResultStr += "#define _REWRITER_typedef_";
785 ResultStr += ClassDecl->getName();
786 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000787 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000788 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000789 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000790 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000791 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000792 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000793 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000794
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000795 RewriteProperties(ClassDecl->getNumPropertyDecl(),
796 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000797 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000798 E = ClassDecl->instmeth_end(); I != E; ++I)
799 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000800 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000801 E = ClassDecl->classmeth_end(); I != E; ++I)
802 RewriteMethodDeclaration(*I);
803
Steve Naroff2feac5e2007-10-30 03:43:13 +0000804 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000805 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000806}
807
Steve Naroffb29b4272008-04-14 22:03:09 +0000808Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000809 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000810 if (CurMethodDecl) {
811 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
812 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
813 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000814 // lookup which class implements the instance variable.
815 ObjCInterfaceDecl *clsDeclared = 0;
816 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
817 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5518e7c2008-03-12 23:15:19 +0000818
819 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000820 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff05b8c782008-03-12 00:25:36 +0000821 RecName += "_IMPL";
822 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Chris Lattner0ed844b2008-04-04 06:12:32 +0000823 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, NULL,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000824 SourceLocation(), II, 0);
Steve Naroff05b8c782008-03-12 00:25:36 +0000825 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
826 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
827 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
828 // Don't forget the parens to enforce the proper binding.
829 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
830 if (IV->isFreeIvar()) {
831 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
832 ReplaceStmt(IV, ME);
833 delete IV;
834 return ME;
835 } else {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000836 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5518e7c2008-03-12 23:15:19 +0000837 // Cannot delete IV->getBase(), since PE points to it.
838 // Replace the old base with the cast. This is important when doing
839 // embedded rewrites. For example, [newInv->_container addObject:0].
840 IV->setBase(PE);
841 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000842 }
843 }
844 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000845 }
Steve Naroff5518e7c2008-03-12 23:15:19 +0000846 // FIXME: Implement public ivar access from a function.
Steve Naroff05b8c782008-03-12 00:25:36 +0000847 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
848 IV->getLocation(), D->getType());
849 ReplaceStmt(IV, Replacement);
850 delete IV;
851 return Replacement;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000852}
853
Chris Lattnerf04da132007-10-24 17:06:59 +0000854//===----------------------------------------------------------------------===//
855// Function Body / Expression rewriting
856//===----------------------------------------------------------------------===//
857
Steve Naroffb29b4272008-04-14 22:03:09 +0000858Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000859 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
860 isa<DoStmt>(S) || isa<ForStmt>(S))
861 Stmts.push_back(S);
862 else if (isa<ObjCForCollectionStmt>(S)) {
863 Stmts.push_back(S);
864 ObjCBcLabelNo.push_back(++BcLabelCount);
865 }
866
Chris Lattner338d1e22008-01-31 05:10:40 +0000867 SourceLocation OrigStmtEnd = S->getLocEnd();
868
869 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000870 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
871 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000872 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000873 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000874 if (newStmt)
875 *CI = newStmt;
876 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000877
878 // Handle specific things.
879 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
880 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000881
882 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
883 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000884
885 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
886 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000887
Steve Naroffbeaf2992007-11-03 11:27:19 +0000888 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
889 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000890
Steve Naroff934f2762007-10-24 22:48:43 +0000891 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
892 // Before we rewrite it, put the original message expression in a comment.
893 SourceLocation startLoc = MessExpr->getLocStart();
894 SourceLocation endLoc = MessExpr->getLocEnd();
895
896 const char *startBuf = SM->getCharacterData(startLoc);
897 const char *endBuf = SM->getCharacterData(endLoc);
898
899 std::string messString;
900 messString += "// ";
901 messString.append(startBuf, endBuf-startBuf+1);
902 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000903
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000904 // FIXME: Missing definition of
905 // InsertText(clang::SourceLocation, char const*, unsigned int).
906 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000907 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000908 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000909 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000910 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000911
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000912 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
913 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000914
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000915 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
916 return RewriteObjCSynchronizedStmt(StmtTry);
917
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000918 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
919 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000920
921 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
922 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000923
924 if (ObjCForCollectionStmt *StmtForCollection =
925 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000926 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000927 if (BreakStmt *StmtBreakStmt =
928 dyn_cast<BreakStmt>(S))
929 return RewriteBreakStmt(StmtBreakStmt);
930 if (ContinueStmt *StmtContinueStmt =
931 dyn_cast<ContinueStmt>(S))
932 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000933
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000934 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
935 isa<DoStmt>(S) || isa<ForStmt>(S)) {
936 assert(!Stmts.empty() && "Statement stack is empty");
937 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
938 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
939 && "Statement stack mismatch");
940 Stmts.pop_back();
941 }
Steve Naroff874e2322007-11-15 10:28:18 +0000942#if 0
943 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
944 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
945 // Get the new text.
946 std::ostringstream Buf;
947 Replacement->printPretty(Buf);
948 const std::string &Str = Buf.str();
949
950 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000951 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000952 delete S;
953 return Replacement;
954 }
955#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000956 // Return this stmt unmodified.
957 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000958}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000959
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000960/// SynthCountByEnumWithState - To print:
961/// ((unsigned int (*)
962/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
963/// (void *)objc_msgSend)((id)l_collection,
964/// sel_registerName(
965/// "countByEnumeratingWithState:objects:count:"),
966/// &enumState,
967/// (id *)items, (unsigned int)16)
968///
Steve Naroffb29b4272008-04-14 22:03:09 +0000969void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000970 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
971 "id *, unsigned int))(void *)objc_msgSend)";
972 buf += "\n\t\t";
973 buf += "((id)l_collection,\n\t\t";
974 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
975 buf += "\n\t\t";
976 buf += "&enumState, "
977 "(id *)items, (unsigned int)16)";
978}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000979
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000980/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
981/// statement to exit to its outer synthesized loop.
982///
Steve Naroffb29b4272008-04-14 22:03:09 +0000983Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000984 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
985 return S;
986 // replace break with goto __break_label
987 std::string buf;
988
989 SourceLocation startLoc = S->getLocStart();
990 buf = "goto __break_label_";
991 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000992 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000993
994 return 0;
995}
996
997/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
998/// statement to continue with its inner synthesized loop.
999///
Steve Naroffb29b4272008-04-14 22:03:09 +00001000Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001001 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1002 return S;
1003 // replace continue with goto __continue_label
1004 std::string buf;
1005
1006 SourceLocation startLoc = S->getLocStart();
1007 buf = "goto __continue_label_";
1008 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001009 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001010
1011 return 0;
1012}
1013
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001014/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001015/// It rewrites:
1016/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001017
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001018/// Into:
1019/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001020/// type elem;
1021/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001022/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001023/// id l_collection = (id)collection;
1024/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1025/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001026/// if (limit) {
1027/// unsigned long startMutations = *enumState.mutationsPtr;
1028/// do {
1029/// unsigned long counter = 0;
1030/// do {
1031/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001032/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001033/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001034/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001035/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001036/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001037/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1038/// objects:items count:16]);
1039/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001040/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001041/// }
1042/// else
1043/// elem = nil;
1044/// }
1045///
Steve Naroffb29b4272008-04-14 22:03:09 +00001046Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001047 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001048 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1049 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1050 "ObjCForCollectionStmt Statement stack mismatch");
1051 assert(!ObjCBcLabelNo.empty() &&
1052 "ObjCForCollectionStmt - Label No stack empty");
1053
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001054 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001055 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001056 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001057 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001058 std::string buf;
1059 buf = "\n{\n\t";
1060 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1061 // type elem;
1062 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001063 elementTypeAsString = ElementType.getAsString();
1064 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001065 buf += " ";
1066 elementName = DS->getDecl()->getName();
1067 buf += elementName;
1068 buf += ";\n\t";
1069 }
Chris Lattner06767512008-04-08 05:52:18 +00001070 else {
1071 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001072 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001073 elementTypeAsString = DR->getDecl()->getType().getAsString();
1074 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001075
1076 // struct __objcFastEnumerationState enumState = { 0 };
1077 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1078 // id items[16];
1079 buf += "id items[16];\n\t";
1080 // id l_collection = (id)
1081 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001082 // Find start location of 'collection' the hard way!
1083 const char *startCollectionBuf = startBuf;
1084 startCollectionBuf += 3; // skip 'for'
1085 startCollectionBuf = strchr(startCollectionBuf, '(');
1086 startCollectionBuf++; // skip '('
1087 // find 'in' and skip it.
1088 while (*startCollectionBuf != ' ' ||
1089 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1090 (*(startCollectionBuf+3) != ' ' &&
1091 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1092 startCollectionBuf++;
1093 startCollectionBuf += 3;
1094
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001095 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001096 ReplaceText(startLoc, startCollectionBuf - startBuf,
1097 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001098 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001099 SourceLocation rightParenLoc = S->getRParenLoc();
1100 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1101 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001102 buf = ";\n\t";
1103
1104 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1105 // objects:items count:16];
1106 // which is synthesized into:
1107 // unsigned int limit =
1108 // ((unsigned int (*)
1109 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1110 // (void *)objc_msgSend)((id)l_collection,
1111 // sel_registerName(
1112 // "countByEnumeratingWithState:objects:count:"),
1113 // (struct __objcFastEnumerationState *)&state,
1114 // (id *)items, (unsigned int)16);
1115 buf += "unsigned long limit =\n\t\t";
1116 SynthCountByEnumWithState(buf);
1117 buf += ";\n\t";
1118 /// if (limit) {
1119 /// unsigned long startMutations = *enumState.mutationsPtr;
1120 /// do {
1121 /// unsigned long counter = 0;
1122 /// do {
1123 /// if (startMutations != *enumState.mutationsPtr)
1124 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001125 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001126 buf += "if (limit) {\n\t";
1127 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1128 buf += "do {\n\t\t";
1129 buf += "unsigned long counter = 0;\n\t\t";
1130 buf += "do {\n\t\t\t";
1131 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1132 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1133 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001134 buf += " = (";
1135 buf += elementTypeAsString;
1136 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001137 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001138 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001139
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001140 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001141 /// } while (counter < limit);
1142 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1143 /// objects:items count:16]);
1144 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001145 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001146 /// }
1147 /// else
1148 /// elem = nil;
1149 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001150 ///
1151 buf = ";\n\t";
1152 buf += "__continue_label_";
1153 buf += utostr(ObjCBcLabelNo.back());
1154 buf += ": ;";
1155 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001156 buf += "} while (counter < limit);\n\t";
1157 buf += "} while (limit = ";
1158 SynthCountByEnumWithState(buf);
1159 buf += ");\n\t";
1160 buf += elementName;
1161 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001162 buf += "__break_label_";
1163 buf += utostr(ObjCBcLabelNo.back());
1164 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001165 buf += "}\n\t";
1166 buf += "else\n\t\t";
1167 buf += elementName;
1168 buf += " = nil;\n";
1169 buf += "}\n";
1170 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001171 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001172 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001173 Stmts.pop_back();
1174 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001175 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001176}
1177
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001178/// RewriteObjCSynchronizedStmt -
1179/// This routine rewrites @synchronized(expr) stmt;
1180/// into:
1181/// objc_sync_enter(expr);
1182/// @try stmt @finally { objc_sync_exit(expr); }
1183///
Steve Naroffb29b4272008-04-14 22:03:09 +00001184Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001185 // Get the start location and compute the semi location.
1186 SourceLocation startLoc = S->getLocStart();
1187 const char *startBuf = SM->getCharacterData(startLoc);
1188
1189 assert((*startBuf == '@') && "bogus @synchronized location");
1190
1191 std::string buf;
1192 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001193 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001194 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1195 const char *endBuf = SM->getCharacterData(endLoc);
1196 endBuf++;
1197 const char *rparenBuf = strchr(endBuf, ')');
1198 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1199 buf = ");\n";
1200 // declare a new scope with two variables, _stack and _rethrow.
1201 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1202 buf += "int buf[18/*32-bit i386*/];\n";
1203 buf += "char *pointers[4];} _stack;\n";
1204 buf += "id volatile _rethrow = 0;\n";
1205 buf += "objc_exception_try_enter(&_stack);\n";
1206 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001207 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001208 startLoc = S->getSynchBody()->getLocEnd();
1209 startBuf = SM->getCharacterData(startLoc);
1210
1211 assert((*startBuf == '}') && "bogus @try block");
1212 SourceLocation lastCurlyLoc = startLoc;
1213 buf = "}\nelse {\n";
1214 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1215 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1216 // FIXME: This must be objc_sync_exit(syncExpr);
1217 buf += " objc_sync_exit();\n";
1218 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1219 buf += "}\n";
1220 buf += "}";
1221
Chris Lattneraadaf782008-01-31 19:51:04 +00001222 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001223 return 0;
1224}
1225
Steve Naroffb29b4272008-04-14 22:03:09 +00001226Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001227 // Get the start location and compute the semi location.
1228 SourceLocation startLoc = S->getLocStart();
1229 const char *startBuf = SM->getCharacterData(startLoc);
1230
1231 assert((*startBuf == '@') && "bogus @try location");
1232
1233 std::string buf;
1234 // declare a new scope with two variables, _stack and _rethrow.
1235 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1236 buf += "int buf[18/*32-bit i386*/];\n";
1237 buf += "char *pointers[4];} _stack;\n";
1238 buf += "id volatile _rethrow = 0;\n";
1239 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001240 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001241
Chris Lattneraadaf782008-01-31 19:51:04 +00001242 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001243
1244 startLoc = S->getTryBody()->getLocEnd();
1245 startBuf = SM->getCharacterData(startLoc);
1246
1247 assert((*startBuf == '}') && "bogus @try block");
1248
1249 SourceLocation lastCurlyLoc = startLoc;
1250
1251 startLoc = startLoc.getFileLocWithOffset(1);
1252 buf = " /* @catch begin */ else {\n";
1253 buf += " id _caught = objc_exception_extract(&_stack);\n";
1254 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001255 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001256 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1257 buf += " else { /* @catch continue */";
1258
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001259 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001260
1261 bool sawIdTypedCatch = false;
1262 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001263 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001264 while (catchList) {
1265 Stmt *catchStmt = catchList->getCatchParamStmt();
1266
1267 if (catchList == S->getCatchStmts())
1268 buf = "if ("; // we are generating code for the first catch clause
1269 else
1270 buf = "else if (";
1271 startLoc = catchList->getLocStart();
1272 startBuf = SM->getCharacterData(startLoc);
1273
1274 assert((*startBuf == '@') && "bogus @catch location");
1275
1276 const char *lParenLoc = strchr(startBuf, '(');
1277
Steve Naroffbe4b3332008-02-01 22:08:12 +00001278 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001279 // Now rewrite the body...
1280 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001281 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1282 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001283 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1284 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001285 assert((*bodyBuf == '{') && "bogus @catch body location");
1286
1287 buf += "1) { id _tmp = _caught;";
1288 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1289 buf.c_str(), buf.size());
1290 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001291 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001292 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001293 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001294 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001295 sawIdTypedCatch = true;
1296 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001297 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001298
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001299 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001300 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001301 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001302 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001303 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001304 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001305 }
1306 }
1307 // Now rewrite the body...
1308 lastCatchBody = catchList->getCatchBody();
1309 SourceLocation rParenLoc = catchList->getRParenLoc();
1310 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1311 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1312 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1313 assert((*rParenBuf == ')') && "bogus @catch paren location");
1314 assert((*bodyBuf == '{') && "bogus @catch body location");
1315
1316 buf = " = _caught;";
1317 // Here we replace ") {" with "= _caught;" (which initializes and
1318 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001319 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001320 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001321 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001322 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001323 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001324 catchList = catchList->getNextCatchStmt();
1325 }
1326 // Complete the catch list...
1327 if (lastCatchBody) {
1328 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001329 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1330 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001331 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1332 buf = " } } /* @catch end */\n";
1333
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001334 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001335
1336 // Set lastCurlyLoc
1337 lastCurlyLoc = lastCatchBody->getLocEnd();
1338 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001339 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001340 startLoc = finalStmt->getLocStart();
1341 startBuf = SM->getCharacterData(startLoc);
1342 assert((*startBuf == '@') && "bogus @finally start");
1343
1344 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001345 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001346
1347 Stmt *body = finalStmt->getFinallyBody();
1348 SourceLocation startLoc = body->getLocStart();
1349 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001350 assert(*SM->getCharacterData(startLoc) == '{' &&
1351 "bogus @finally body location");
1352 assert(*SM->getCharacterData(endLoc) == '}' &&
1353 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001354
1355 startLoc = startLoc.getFileLocWithOffset(1);
1356 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001357 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001358 endLoc = endLoc.getFileLocWithOffset(-1);
1359 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001360 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001361
1362 // Set lastCurlyLoc
1363 lastCurlyLoc = body->getLocEnd();
1364 }
1365 // Now emit the final closing curly brace...
1366 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1367 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001368 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001369 return 0;
1370}
1371
Steve Naroffb29b4272008-04-14 22:03:09 +00001372Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001373 return 0;
1374}
1375
Steve Naroffb29b4272008-04-14 22:03:09 +00001376Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001377 return 0;
1378}
1379
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001380// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001381// the throw expression is typically a message expression that's already
1382// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001383Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001384 // Get the start location and compute the semi location.
1385 SourceLocation startLoc = S->getLocStart();
1386 const char *startBuf = SM->getCharacterData(startLoc);
1387
1388 assert((*startBuf == '@') && "bogus @throw location");
1389
1390 std::string buf;
1391 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001392 if (S->getThrowExpr())
1393 buf = "objc_exception_throw(";
1394 else // add an implicit argument
1395 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001396 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001397 const char *semiBuf = strchr(startBuf, ';');
1398 assert((*semiBuf == ';') && "@throw: can't find ';'");
1399 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1400 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001401 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001402 return 0;
1403}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001404
Steve Naroffb29b4272008-04-14 22:03:09 +00001405Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001406 // Create a new string expression.
1407 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001408 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001409 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1410 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001411 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1412 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001413 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001414 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001415
Chris Lattner07506182007-11-30 22:53:43 +00001416 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001417 delete Exp;
1418 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001419}
1420
Steve Naroffb29b4272008-04-14 22:03:09 +00001421Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001422 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1423 // Create a call to sel_registerName("selName").
1424 llvm::SmallVector<Expr*, 8> SelExprs;
1425 QualType argType = Context->getPointerType(Context->CharTy);
1426 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1427 Exp->getSelector().getName().size(),
1428 false, argType, SourceLocation(),
1429 SourceLocation()));
1430 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1431 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001432 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001433 delete Exp;
1434 return SelExp;
1435}
1436
Steve Naroffb29b4272008-04-14 22:03:09 +00001437CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001438 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001439 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001440 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001441
1442 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001443 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001444
1445 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001446 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001447 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1448
1449 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001450
Steve Naroff934f2762007-10-24 22:48:43 +00001451 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1452}
1453
Steve Naroffd5255f52007-11-01 13:24:47 +00001454static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1455 const char *&startRef, const char *&endRef) {
1456 while (startBuf < endBuf) {
1457 if (*startBuf == '<')
1458 startRef = startBuf; // mark the start.
1459 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001460 if (startRef && *startRef == '<') {
1461 endRef = startBuf; // mark the end.
1462 return true;
1463 }
1464 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001465 }
1466 startBuf++;
1467 }
1468 return false;
1469}
1470
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001471static void scanToNextArgument(const char *&argRef) {
1472 int angle = 0;
1473 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1474 if (*argRef == '<')
1475 angle++;
1476 else if (*argRef == '>')
1477 angle--;
1478 argRef++;
1479 }
1480 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1481}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001482
Steve Naroffb29b4272008-04-14 22:03:09 +00001483bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001484
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001485 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001486 return true;
1487
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001488 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001489 return true;
1490
Steve Naroffd5255f52007-11-01 13:24:47 +00001491 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001492 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001493 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001494 return true; // we have "Class <Protocol> *".
1495 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001496 return false;
1497}
1498
Steve Naroffb29b4272008-04-14 22:03:09 +00001499void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001500 SourceLocation Loc;
1501 QualType Type;
1502 const FunctionTypeProto *proto = 0;
1503 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1504 Loc = VD->getLocation();
1505 Type = VD->getType();
1506 }
1507 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1508 Loc = FD->getLocation();
1509 // Check for ObjC 'id' and class types that have been adorned with protocol
1510 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1511 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1512 assert(funcType && "missing function type");
1513 proto = dyn_cast<FunctionTypeProto>(funcType);
1514 if (!proto)
1515 return;
1516 Type = proto->getResultType();
1517 }
1518 else
1519 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001520
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001521 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001522 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001523
1524 const char *endBuf = SM->getCharacterData(Loc);
1525 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001526 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001527 startBuf--; // scan backward (from the decl location) for return type.
1528 const char *startRef = 0, *endRef = 0;
1529 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1530 // Get the locations of the startRef, endRef.
1531 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1532 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1533 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001534 InsertText(LessLoc, "/*", 2);
1535 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001536 }
1537 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001538 if (!proto)
1539 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001540 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001541 const char *startBuf = SM->getCharacterData(Loc);
1542 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001543 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1544 if (needToScanForQualifiers(proto->getArgType(i))) {
1545 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001546
Steve Naroffd5255f52007-11-01 13:24:47 +00001547 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001548 // scan forward (from the decl location) for argument types.
1549 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001550 const char *startRef = 0, *endRef = 0;
1551 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1552 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001553 SourceLocation LessLoc =
1554 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1555 SourceLocation GreaterLoc =
1556 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001557 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001558 InsertText(LessLoc, "/*", 2);
1559 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001560 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001561 startBuf = ++endBuf;
1562 }
1563 else {
1564 while (*startBuf != ')' && *startBuf != ',')
1565 startBuf++; // scan forward (from the decl location) for argument types.
1566 startBuf++;
1567 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001568 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001569}
1570
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001571// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001572void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001573 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1574 llvm::SmallVector<QualType, 16> ArgTys;
1575 ArgTys.push_back(Context->getPointerType(
1576 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001577 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001578 &ArgTys[0], ArgTys.size(),
1579 false /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001580 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, NULL,
1581 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001582 SelGetUidIdent, getFuncType,
1583 FunctionDecl::Extern, false, 0);
1584}
1585
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001586// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001587void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001588 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1589 llvm::SmallVector<QualType, 16> ArgTys;
1590 ArgTys.push_back(Context->getPointerType(
1591 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001592 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001593 &ArgTys[0], ArgTys.size(),
1594 false /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001595 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, NULL,
1596 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001597 SelGetProtoIdent, getFuncType,
1598 FunctionDecl::Extern, false, 0);
1599}
1600
Steve Naroffb29b4272008-04-14 22:03:09 +00001601void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001602 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001603 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001604 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001605 return;
1606 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001607 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001608}
1609
Steve Naroffc0a123c2008-03-11 17:37:02 +00001610// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001611void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001612 if (SuperContructorFunctionDecl)
1613 return;
1614 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1615 llvm::SmallVector<QualType, 16> ArgTys;
1616 QualType argT = Context->getObjCIdType();
1617 assert(!argT.isNull() && "Can't find 'id' type");
1618 ArgTys.push_back(argT);
1619 ArgTys.push_back(argT);
1620 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1621 &ArgTys[0], ArgTys.size(),
1622 false);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001623 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, NULL,
1624 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001625 msgSendIdent, msgSendType,
1626 FunctionDecl::Extern, false, 0);
1627}
1628
Steve Naroff09b266e2007-10-30 23:14:51 +00001629// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001630void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001631 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1632 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001633 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001634 assert(!argT.isNull() && "Can't find 'id' type");
1635 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001636 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001637 assert(!argT.isNull() && "Can't find 'SEL' type");
1638 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001639 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001640 &ArgTys[0], ArgTys.size(),
1641 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001642 MsgSendFunctionDecl = FunctionDecl::Create(*Context, NULL,
1643 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001644 msgSendIdent, msgSendType,
1645 FunctionDecl::Extern, false, 0);
1646}
1647
Steve Naroff874e2322007-11-15 10:28:18 +00001648// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001649void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001650 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1651 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattner0ed844b2008-04-04 06:12:32 +00001652 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, NULL,
1653 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001654 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001655 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1656 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1657 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001658 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001659 assert(!argT.isNull() && "Can't find 'SEL' type");
1660 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001661 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001662 &ArgTys[0], ArgTys.size(),
1663 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001664 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, NULL,
1665 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001666 msgSendIdent, msgSendType,
1667 FunctionDecl::Extern, false, 0);
1668}
1669
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001670// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001671void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001672 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1673 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001674 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001675 assert(!argT.isNull() && "Can't find 'id' type");
1676 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001677 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001678 assert(!argT.isNull() && "Can't find 'SEL' type");
1679 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001680 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001681 &ArgTys[0], ArgTys.size(),
1682 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001683 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, NULL,
1684 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001685 msgSendIdent, msgSendType,
1686 FunctionDecl::Extern, false, 0);
1687}
1688
1689// SynthMsgSendSuperStretFunctionDecl -
1690// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001691void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001692 IdentifierInfo *msgSendIdent =
1693 &Context->Idents.get("objc_msgSendSuper_stret");
1694 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattner0ed844b2008-04-04 06:12:32 +00001695 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, NULL,
1696 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001697 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001698 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1699 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1700 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001701 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001702 assert(!argT.isNull() && "Can't find 'SEL' type");
1703 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001704 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001705 &ArgTys[0], ArgTys.size(),
1706 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001707 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, NULL,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001708 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001709 msgSendIdent, msgSendType,
1710 FunctionDecl::Extern, false, 0);
1711}
1712
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001713// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001714void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001715 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1716 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001717 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001718 assert(!argT.isNull() && "Can't find 'id' type");
1719 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001720 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001721 assert(!argT.isNull() && "Can't find 'SEL' type");
1722 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001723 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001724 &ArgTys[0], ArgTys.size(),
1725 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001726 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, NULL,
1727 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001728 msgSendIdent, msgSendType,
1729 FunctionDecl::Extern, false, 0);
1730}
1731
Steve Naroff09b266e2007-10-30 23:14:51 +00001732// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001733void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001734 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1735 llvm::SmallVector<QualType, 16> ArgTys;
1736 ArgTys.push_back(Context->getPointerType(
1737 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001738 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001739 &ArgTys[0], ArgTys.size(),
1740 false /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001741 GetClassFunctionDecl = FunctionDecl::Create(*Context, NULL,
1742 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001743 getClassIdent, getClassType,
1744 FunctionDecl::Extern, false, 0);
1745}
1746
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001747// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001748void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001749 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1750 llvm::SmallVector<QualType, 16> ArgTys;
1751 ArgTys.push_back(Context->getPointerType(
1752 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001753 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001754 &ArgTys[0], ArgTys.size(),
1755 false /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001756 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, NULL,
1757 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001758 getClassIdent, getClassType,
1759 FunctionDecl::Extern, false, 0);
1760}
1761
Steve Naroffb29b4272008-04-14 22:03:09 +00001762Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001763 QualType strType = getConstantStringStructType();
1764
1765 std::string S = "__NSConstantStringImpl_";
1766 S += utostr(NumObjCStringLiterals++);
1767
Steve Naroffba92b2e2008-03-27 22:29:16 +00001768 Preamble += "static __NSConstantStringImpl " + S;
1769 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1770 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001771 // The pretty printer for StringLiteral handles escape characters properly.
1772 std::ostringstream prettyBuf;
1773 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001774 Preamble += prettyBuf.str();
1775 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001776 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001777 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001778
Steve Naroff248a7532008-04-15 22:42:06 +00001779 VarDecl *NewVD = VarDecl::Create(*Context, NULL, SourceLocation(),
1780 &Context->Idents.get(S.c_str()), strType,
1781 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001782 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1783 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1784 Context->getPointerType(DRE->getType()),
1785 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001786 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001787 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001788 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001789 delete Exp;
1790 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001791}
1792
Steve Naroffb29b4272008-04-14 22:03:09 +00001793ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001794 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001795 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1796
1797 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1798 if (!CE) return 0;
1799
1800 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1801 if (!DRE) return 0;
1802
1803 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1804 if (!PVD) return 0;
1805
1806 if (strcmp(PVD->getName(), "self") != 0)
1807 return 0;
1808
1809 // is this id<P1..> type?
1810 if (CE->getType()->isObjCQualifiedIdType())
1811 return 0;
1812 const PointerType *PT = CE->getType()->getAsPointerType();
1813 if (!PT) return 0;
1814
1815 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1816 if (!IT) return 0;
1817
1818 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1819 return 0;
1820
1821 return IT->getDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001822}
1823
1824// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001825QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001826 if (!SuperStructDecl) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001827 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct, NULL,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001828 SourceLocation(),
1829 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001830 QualType FieldTypes[2];
1831
1832 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001833 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001834 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001835 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001836 // Create fields
1837 FieldDecl *FieldDecls[2];
1838
1839 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001840 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001841 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001842
1843 SuperStructDecl->defineBody(FieldDecls, 4);
1844 }
1845 return Context->getTagDeclType(SuperStructDecl);
1846}
1847
Steve Naroffb29b4272008-04-14 22:03:09 +00001848QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001849 if (!ConstantStringDecl) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001850 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct, NULL,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001851 SourceLocation(),
1852 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001853 QualType FieldTypes[4];
1854
1855 // struct objc_object *receiver;
1856 FieldTypes[0] = Context->getObjCIdType();
1857 // int flags;
1858 FieldTypes[1] = Context->IntTy;
1859 // char *str;
1860 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1861 // long length;
1862 FieldTypes[3] = Context->LongTy;
1863 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001864 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001865
1866 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001867 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001868 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001869
1870 ConstantStringDecl->defineBody(FieldDecls, 4);
1871 }
1872 return Context->getTagDeclType(ConstantStringDecl);
1873}
1874
Steve Naroffb29b4272008-04-14 22:03:09 +00001875Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001876 if (!SelGetUidFunctionDecl)
1877 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001878 if (!MsgSendFunctionDecl)
1879 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001880 if (!MsgSendSuperFunctionDecl)
1881 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001882 if (!MsgSendStretFunctionDecl)
1883 SynthMsgSendStretFunctionDecl();
1884 if (!MsgSendSuperStretFunctionDecl)
1885 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001886 if (!MsgSendFpretFunctionDecl)
1887 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001888 if (!GetClassFunctionDecl)
1889 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001890 if (!GetMetaClassFunctionDecl)
1891 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001892
Steve Naroff874e2322007-11-15 10:28:18 +00001893 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001894 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1895 // May need to use objc_msgSend_stret() as well.
1896 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001897 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001898 QualType resultType = mDecl->getResultType();
1899 if (resultType.getCanonicalType()->isStructureType()
1900 || resultType.getCanonicalType()->isUnionType())
1901 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001902 else if (resultType.getCanonicalType()->isRealFloatingType())
1903 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001904 }
Steve Naroff874e2322007-11-15 10:28:18 +00001905
Steve Naroff934f2762007-10-24 22:48:43 +00001906 // Synthesize a call to objc_msgSend().
1907 llvm::SmallVector<Expr*, 8> MsgExprs;
1908 IdentifierInfo *clsName = Exp->getClassName();
1909
1910 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1911 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001912 if (!strcmp(clsName->getName(), "super")) {
1913 MsgSendFlavor = MsgSendSuperFunctionDecl;
1914 if (MsgSendStretFlavor)
1915 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1916 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1917
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001918 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001919 CurMethodDecl->getClassInterface()->getSuperClass();
1920
1921 llvm::SmallVector<Expr*, 4> InitExprs;
1922
1923 // set the receiver to self, the first argument to all methods.
1924 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001925 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001926 SourceLocation()));
1927 llvm::SmallVector<Expr*, 8> ClsExprs;
1928 QualType argType = Context->getPointerType(Context->CharTy);
1929 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1930 SuperDecl->getIdentifier()->getLength(),
1931 false, argType, SourceLocation(),
1932 SourceLocation()));
1933 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1934 &ClsExprs[0],
1935 ClsExprs.size());
1936 // To turn off a warning, type-cast to 'id'
1937 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001938 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001939 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1940 // struct objc_super
1941 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001942 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001943
Steve Naroff23f41272008-03-11 18:14:26 +00001944 if (LangOpts.Microsoft) {
1945 SynthSuperContructorFunctionDecl();
1946 // Simulate a contructor call...
1947 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1948 superType, SourceLocation());
1949 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1950 superType, SourceLocation());
1951 } else {
1952 // (struct objc_super) { <exprs from above> }
1953 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1954 &InitExprs[0], InitExprs.size(),
1955 SourceLocation());
1956 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1957 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001958 // struct objc_super *
1959 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1960 Context->getPointerType(SuperRep->getType()),
1961 SourceLocation());
1962 MsgExprs.push_back(Unop);
1963 } else {
1964 llvm::SmallVector<Expr*, 8> ClsExprs;
1965 QualType argType = Context->getPointerType(Context->CharTy);
1966 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1967 clsName->getLength(),
1968 false, argType, SourceLocation(),
1969 SourceLocation()));
1970 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1971 &ClsExprs[0],
1972 ClsExprs.size());
1973 MsgExprs.push_back(Cls);
1974 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001975 } else { // instance message.
1976 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001977
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001978 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001979 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001980 if (MsgSendStretFlavor)
1981 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001982 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1983
1984 llvm::SmallVector<Expr*, 4> InitExprs;
1985
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001986 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001987 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001988 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001989
1990 llvm::SmallVector<Expr*, 8> ClsExprs;
1991 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001992 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1993 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001994 false, argType, SourceLocation(),
1995 SourceLocation()));
1996 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001997 &ClsExprs[0],
1998 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001999 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002000 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002001 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002002 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002003 // struct objc_super
2004 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002005 Expr *SuperRep;
2006
2007 if (LangOpts.Microsoft) {
2008 SynthSuperContructorFunctionDecl();
2009 // Simulate a contructor call...
2010 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2011 superType, SourceLocation());
2012 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2013 superType, SourceLocation());
2014 } else {
2015 // (struct objc_super) { <exprs from above> }
2016 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2017 &InitExprs[0], InitExprs.size(),
2018 SourceLocation());
2019 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2020 }
Steve Naroff874e2322007-11-15 10:28:18 +00002021 // struct objc_super *
2022 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2023 Context->getPointerType(SuperRep->getType()),
2024 SourceLocation());
2025 MsgExprs.push_back(Unop);
2026 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002027 // Remove all type-casts because it may contain objc-style types; e.g.
2028 // Foo<Proto> *.
2029 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2030 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002031 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002032 MsgExprs.push_back(recExpr);
2033 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002034 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002035 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002036 llvm::SmallVector<Expr*, 8> SelExprs;
2037 QualType argType = Context->getPointerType(Context->CharTy);
2038 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2039 Exp->getSelector().getName().size(),
2040 false, argType, SourceLocation(),
2041 SourceLocation()));
2042 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2043 &SelExprs[0], SelExprs.size());
2044 MsgExprs.push_back(SelExp);
2045
2046 // Now push any user supplied arguments.
2047 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002048 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002049 // Make all implicit casts explicit...ICE comes in handy:-)
2050 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2051 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002052 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2053 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002054 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002055 }
2056 // Make id<P...> cast into an 'id' cast.
2057 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002058 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002059 while ((CE = dyn_cast<CastExpr>(userExpr)))
2060 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002061 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002062 userExpr, SourceLocation());
2063 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002064 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002065 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002066 // We've transferred the ownership to MsgExprs. Null out the argument in
2067 // the original expression, since we will delete it below.
2068 Exp->setArg(i, 0);
2069 }
Steve Naroffab972d32007-11-04 22:37:50 +00002070 // Generate the funky cast.
2071 CastExpr *cast;
2072 llvm::SmallVector<QualType, 8> ArgTypes;
2073 QualType returnType;
2074
2075 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002076 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2077 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2078 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002079 ArgTypes.push_back(Context->getObjCIdType());
2080 ArgTypes.push_back(Context->getObjCSelType());
2081 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002082 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002083 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002084 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2085 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002086 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002087 ArgTypes.push_back(t);
2088 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002089 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2090 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002091 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002092 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002093 }
2094 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002095 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002096
2097 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002098 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2099 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002100
2101 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2102 // If we don't do this cast, we get the following bizarre warning/note:
2103 // xx.m:13: warning: function called through a non-compatible type
2104 // xx.m:13: note: if this code is reached, the program will abort
2105 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2106 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002107
Steve Naroffab972d32007-11-04 22:37:50 +00002108 // Now do the "normal" pointer to function cast.
2109 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002110 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002111 // If we don't have a method decl, force a variadic cast.
2112 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002113 castType = Context->getPointerType(castType);
2114 cast = new CastExpr(castType, cast, SourceLocation());
2115
2116 // Don't forget the parens to enforce the proper binding.
2117 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2118
2119 const FunctionType *FT = msgSendType->getAsFunctionType();
2120 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2121 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002122 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002123 if (MsgSendStretFlavor) {
2124 // We have the method which returns a struct/union. Must also generate
2125 // call to objc_msgSend_stret and hang both varieties on a conditional
2126 // expression which dictate which one to envoke depending on size of
2127 // method's return type.
2128
2129 // Create a reference to the objc_msgSend_stret() declaration.
2130 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2131 SourceLocation());
2132 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2133 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2134 SourceLocation());
2135 // Now do the "normal" pointer to function cast.
2136 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002137 &ArgTypes[0], ArgTypes.size(),
2138 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002139 castType = Context->getPointerType(castType);
2140 cast = new CastExpr(castType, cast, SourceLocation());
2141
2142 // Don't forget the parens to enforce the proper binding.
2143 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2144
2145 FT = msgSendType->getAsFunctionType();
2146 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2147 FT->getResultType(), SourceLocation());
2148
2149 // Build sizeof(returnType)
2150 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2151 returnType, Context->getSizeType(),
2152 SourceLocation(), SourceLocation());
2153 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2154 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2155 // For X86 it is more complicated and some kind of target specific routine
2156 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002157 unsigned IntSize =
2158 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002159 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2160 Context->IntTy,
2161 SourceLocation());
2162 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2163 BinaryOperator::LE,
2164 Context->IntTy,
2165 SourceLocation());
2166 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2167 ConditionalOperator *CondExpr =
2168 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002169 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002170 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002171 return ReplacingStmt;
2172}
2173
Steve Naroffb29b4272008-04-14 22:03:09 +00002174Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002175 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002176 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002177 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002178
Chris Lattnere64b7772007-10-24 16:57:36 +00002179 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002180 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002181}
2182
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002183/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2184/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002185Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002186 if (!GetProtocolFunctionDecl)
2187 SynthGetProtocolFunctionDecl();
2188 // Create a call to objc_getProtocol("ProtocolName").
2189 llvm::SmallVector<Expr*, 8> ProtoExprs;
2190 QualType argType = Context->getPointerType(Context->CharTy);
2191 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2192 strlen(Exp->getProtocol()->getName()),
2193 false, argType, SourceLocation(),
2194 SourceLocation()));
2195 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2196 &ProtoExprs[0],
2197 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002198 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002199 delete Exp;
2200 return ProtoExp;
2201
2202}
2203
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002204/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002205/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002206void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002207 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002208 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2209 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002210 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002211 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002212 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002213 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002214 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002215 SourceLocation LocStart = CDecl->getLocStart();
2216 SourceLocation LocEnd = CDecl->getLocEnd();
2217
2218 const char *startBuf = SM->getCharacterData(LocStart);
2219 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002220 // If no ivars and no root or if its root, directly or indirectly,
2221 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002222 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2223 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002224 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002225 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002226 return;
2227 }
2228
2229 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002230 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002231 Result += "\nstruct ";
2232 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002233 if (LangOpts.Microsoft)
2234 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002235
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002236 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002237 const char *cursor = strchr(startBuf, '{');
2238 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002239 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002240
2241 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002242 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002243 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002244 Result = "\n struct ";
2245 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002246 Result += "_IMPL ";
2247 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002248 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002249
2250 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002251 SourceLocation OnePastCurly =
2252 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2253 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002254 }
2255 cursor++; // past '{'
2256
2257 // Now comment out any visibility specifiers.
2258 while (cursor < endBuf) {
2259 if (*cursor == '@') {
2260 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002261 // Skip whitespace.
2262 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2263 /*scan*/;
2264
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002265 // FIXME: presence of @public, etc. inside comment results in
2266 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002267 if (!strncmp(cursor, "public", strlen("public")) ||
2268 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002269 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002270 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002271 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002272 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002273 // FIXME: If there are cases where '<' is used in ivar declaration part
2274 // of user code, then scan the ivar list and use needToScanForQualifiers
2275 // for type checking.
2276 else if (*cursor == '<') {
2277 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002278 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002279 cursor = strchr(cursor, '>');
2280 cursor++;
2281 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002282 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002283 }
Steve Narofffea763e82007-11-14 19:25:57 +00002284 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002285 }
Steve Narofffea763e82007-11-14 19:25:57 +00002286 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002287 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002288 } else { // we don't have any instance variables - insert super struct.
2289 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2290 Result += " {\n struct ";
2291 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002292 Result += "_IMPL ";
2293 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002294 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002295 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002296 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002297 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002298 if (!ObjCSynthesizedStructs.insert(CDecl))
2299 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002300}
2301
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002302// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002303/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002304void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002305 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002306 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002307 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002308 const char *ClassName,
2309 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002310 if (MethodBegin == MethodEnd) return;
2311
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002312 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002313 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002314 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002315 SEL _cmd;
2316 char *method_types;
2317 void *_imp;
2318 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002319 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002320 Result += "\nstruct _objc_method {\n";
2321 Result += "\tSEL _cmd;\n";
2322 Result += "\tchar *method_types;\n";
2323 Result += "\tvoid *_imp;\n";
2324 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002325
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002326 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002327 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002328
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002329 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002330
2331 /* struct {
2332 struct _objc_method_list *next_method;
2333 int method_count;
2334 struct _objc_method method_list[];
2335 }
2336 */
2337 Result += "\nstatic struct {\n";
2338 Result += "\tstruct _objc_method_list *next_method;\n";
2339 Result += "\tint method_count;\n";
2340 Result += "\tstruct _objc_method method_list[";
2341 Result += utostr(MethodEnd-MethodBegin);
2342 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002343 Result += prefix;
2344 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2345 Result += "_METHODS_";
2346 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002347 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002348 Result += IsInstanceMethod ? "inst" : "cls";
2349 Result += "_meth\")))= ";
2350 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002351
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002352 Result += "\t,{{(SEL)\"";
2353 Result += (*MethodBegin)->getSelector().getName().c_str();
2354 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002355 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002356 Result += "\", \"";
2357 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002358 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002359 Result += MethodInternalNames[*MethodBegin];
2360 Result += "}\n";
2361 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2362 Result += "\t ,{(SEL)\"";
2363 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002364 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002365 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002366 Result += "\", \"";
2367 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002368 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002369 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002370 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002371 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002372 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002373}
2374
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002375/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Steve Naroffb29b4272008-04-14 22:03:09 +00002376void RewriteObjC::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002377 int NumProtocols,
2378 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002379 const char *ClassName,
2380 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002381 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002382 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002383 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002384 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002385 // Output struct protocol_methods holder of method selector and type.
Chris Lattnerc8581052008-03-16 20:19:15 +00002386 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002387 /* struct protocol_methods {
2388 SEL _cmd;
2389 char *method_types;
2390 }
2391 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002392 Result += "\nstruct protocol_methods {\n";
2393 Result += "\tSEL _cmd;\n";
2394 Result += "\tchar *method_types;\n";
2395 Result += "};\n";
2396
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002397 objc_protocol_methods = true;
2398 }
Chris Lattnerc8581052008-03-16 20:19:15 +00002399 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2400 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002401 /* struct _objc_protocol_method_list {
2402 int protocol_method_count;
2403 struct protocol_methods protocols[];
2404 }
2405 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002406 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002407 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002408 Result += "\tstruct protocol_methods protocols[";
2409 Result += utostr(NumMethods);
2410 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002411 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002412 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002413 "{\n\t" + utostr(NumMethods) + "\n";
2414
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002415 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002416 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002417 E = PDecl->instmeth_end(); I != E; ++I) {
2418 if (I == PDecl->instmeth_begin())
2419 Result += "\t ,{{(SEL)\"";
2420 else
2421 Result += "\t ,{(SEL)\"";
2422 Result += (*I)->getSelector().getName().c_str();
2423 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002424 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002425 Result += "\", \"";
2426 Result += MethodTypeString;
2427 Result += "\"}\n";
2428 }
2429 Result += "\t }\n};\n";
2430 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002431
2432 // Output class methods declared in this protocol.
Chris Lattnerc8581052008-03-16 20:19:15 +00002433 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002434 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002435 /* struct _objc_protocol_method_list {
2436 int protocol_method_count;
2437 struct protocol_methods protocols[];
2438 }
2439 */
2440 Result += "\nstatic struct {\n";
2441 Result += "\tint protocol_method_count;\n";
2442 Result += "\tstruct protocol_methods protocols[";
2443 Result += utostr(NumMethods);
2444 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002445 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002446 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002447 "{\n\t";
2448 Result += utostr(NumMethods);
2449 Result += "\n";
2450
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002451 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002452 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002453 E = PDecl->classmeth_end(); I != E; ++I) {
2454 if (I == PDecl->classmeth_begin())
2455 Result += "\t ,{{(SEL)\"";
2456 else
2457 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002458 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002459 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002460 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002461 Result += "\", \"";
2462 Result += MethodTypeString;
2463 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002464 }
2465 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002466 }
2467 // Output:
2468 /* struct _objc_protocol {
2469 // Objective-C 1.0 extensions
2470 struct _objc_protocol_extension *isa;
2471 char *protocol_name;
2472 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002473 struct _objc_protocol_method_list *instance_methods;
2474 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002475 };
2476 */
2477 static bool objc_protocol = false;
2478 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002479 Result += "\nstruct _objc_protocol {\n";
2480 Result += "\tstruct _objc_protocol_extension *isa;\n";
2481 Result += "\tchar *protocol_name;\n";
2482 Result += "\tstruct _objc_protocol **protocol_list;\n";
2483 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2484 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2485 Result += "};\n";
2486
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002487 objc_protocol = true;
2488 }
2489
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002490 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2491 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002492 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002493 "{\n\t0, \"";
2494 Result += PDecl->getName();
2495 Result += "\", 0, ";
Chris Lattnerc8581052008-03-16 20:19:15 +00002496 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002497 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002498 Result += PDecl->getName();
2499 Result += ", ";
2500 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002501 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002502 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002503 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002504 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002505 Result += PDecl->getName();
2506 Result += "\n";
2507 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002508 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002509 Result += "0\n";
2510 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002511 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002512 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002513 /* struct _objc_protocol_list {
2514 struct _objc_protocol_list *next;
2515 int protocol_count;
2516 struct _objc_protocol *class_protocols[];
2517 }
2518 */
2519 Result += "\nstatic struct {\n";
2520 Result += "\tstruct _objc_protocol_list *next;\n";
2521 Result += "\tint protocol_count;\n";
2522 Result += "\tstruct _objc_protocol *class_protocols[";
2523 Result += utostr(NumProtocols);
2524 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002525 Result += prefix;
2526 Result += "_PROTOCOLS_";
2527 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002528 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002529 "{\n\t0, ";
2530 Result += utostr(NumProtocols);
2531 Result += "\n";
2532
2533 Result += "\t,{&_OBJC_PROTOCOL_";
2534 Result += Protocols[0]->getName();
2535 Result += " \n";
2536
2537 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002538 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002539 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002540 Result += PDecl->getName();
2541 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002542 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002543 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002544 }
2545}
2546
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002547/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002548/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002549void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002550 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002551 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002552 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002553 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002554 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2555 CDecl = CDecl->getNextClassCategory())
2556 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2557 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002558
Chris Lattnereb44eee2007-12-23 01:40:15 +00002559 std::string FullCategoryName = ClassDecl->getName();
2560 FullCategoryName += '_';
2561 FullCategoryName += IDecl->getName();
2562
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002563 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002564 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002565 true, "CATEGORY_", FullCategoryName.c_str(),
2566 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002567
2568 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002569 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002570 false, "CATEGORY_", FullCategoryName.c_str(),
2571 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002572
2573 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002574 // Null CDecl is case of a category implementation with no category interface
2575 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002576 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002577 CDecl->getNumReferencedProtocols(),
2578 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002579 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002580
2581 /* struct _objc_category {
2582 char *category_name;
2583 char *class_name;
2584 struct _objc_method_list *instance_methods;
2585 struct _objc_method_list *class_methods;
2586 struct _objc_protocol_list *protocols;
2587 // Objective-C 1.0 extensions
2588 uint32_t size; // sizeof (struct _objc_category)
2589 struct _objc_property_list *instance_properties; // category's own
2590 // @property decl.
2591 };
2592 */
2593
2594 static bool objc_category = false;
2595 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002596 Result += "\nstruct _objc_category {\n";
2597 Result += "\tchar *category_name;\n";
2598 Result += "\tchar *class_name;\n";
2599 Result += "\tstruct _objc_method_list *instance_methods;\n";
2600 Result += "\tstruct _objc_method_list *class_methods;\n";
2601 Result += "\tstruct _objc_protocol_list *protocols;\n";
2602 Result += "\tunsigned int size;\n";
2603 Result += "\tstruct _objc_property_list *instance_properties;\n";
2604 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002605 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002606 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002607 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2608 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002609 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002610 Result += IDecl->getName();
2611 Result += "\"\n\t, \"";
2612 Result += ClassDecl->getName();
2613 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002614
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002615 if (IDecl->getNumInstanceMethods() > 0) {
2616 Result += "\t, (struct _objc_method_list *)"
2617 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2618 Result += FullCategoryName;
2619 Result += "\n";
2620 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002621 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002622 Result += "\t, 0\n";
2623 if (IDecl->getNumClassMethods() > 0) {
2624 Result += "\t, (struct _objc_method_list *)"
2625 "&_OBJC_CATEGORY_CLASS_METHODS_";
2626 Result += FullCategoryName;
2627 Result += "\n";
2628 }
2629 else
2630 Result += "\t, 0\n";
2631
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002632 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002633 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2634 Result += FullCategoryName;
2635 Result += "\n";
2636 }
2637 else
2638 Result += "\t, 0\n";
2639 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002640}
2641
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002642/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2643/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002644void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002645 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002646 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002647 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002648 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002649 if (LangOpts.Microsoft)
2650 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002651 Result += ", ";
2652 Result += ivar->getName();
2653 Result += ")";
2654}
2655
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002656//===----------------------------------------------------------------------===//
2657// Meta Data Emission
2658//===----------------------------------------------------------------------===//
2659
Steve Naroffb29b4272008-04-14 22:03:09 +00002660void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002661 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002662 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002663
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002664 // Explictly declared @interface's are already synthesized.
2665 if (CDecl->ImplicitInterfaceDecl()) {
2666 // FIXME: Implementation of a class with no @interface (legacy) doese not
2667 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002668 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002669 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002670
Chris Lattnerbe6df082007-12-12 07:56:42 +00002671 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002672 unsigned NumIvars = !IDecl->ivar_empty()
2673 ? IDecl->ivar_size()
2674 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002675 if (NumIvars > 0) {
2676 static bool objc_ivar = false;
2677 if (!objc_ivar) {
2678 /* struct _objc_ivar {
2679 char *ivar_name;
2680 char *ivar_type;
2681 int ivar_offset;
2682 };
2683 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002684 Result += "\nstruct _objc_ivar {\n";
2685 Result += "\tchar *ivar_name;\n";
2686 Result += "\tchar *ivar_type;\n";
2687 Result += "\tint ivar_offset;\n";
2688 Result += "};\n";
2689
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002690 objc_ivar = true;
2691 }
2692
Steve Naroff946a6932008-03-11 00:12:29 +00002693 /* struct {
2694 int ivar_count;
2695 struct _objc_ivar ivar_list[nIvars];
2696 };
2697 */
2698 Result += "\nstatic struct {\n";
2699 Result += "\tint ivar_count;\n";
2700 Result += "\tstruct _objc_ivar ivar_list[";
2701 Result += utostr(NumIvars);
2702 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002703 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002704 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002705 "{\n\t";
2706 Result += utostr(NumIvars);
2707 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002708
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002709 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002710 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002711 IVI = IDecl->ivar_begin();
2712 IVE = IDecl->ivar_end();
2713 } else {
2714 IVI = CDecl->ivar_begin();
2715 IVE = CDecl->ivar_end();
2716 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002717 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002718 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002719 Result += "\", \"";
2720 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002721 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2722 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002723 Result += StrEncoding;
2724 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002725 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002726 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002727 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002728 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002729 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002730 Result += "\", \"";
2731 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002732 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2733 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002734 Result += StrEncoding;
2735 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002736 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002737 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002738 }
2739
2740 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002741 }
2742
2743 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002744 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002745 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002746
2747 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002748 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002749 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002750
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002751 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002752 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002753 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002754 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002755
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002756
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002757 // Declaration of class/meta-class metadata
2758 /* struct _objc_class {
2759 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002760 const char *super_class_name;
2761 char *name;
2762 long version;
2763 long info;
2764 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002765 struct _objc_ivar_list *ivars;
2766 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002767 struct objc_cache *cache;
2768 struct objc_protocol_list *protocols;
2769 const char *ivar_layout;
2770 struct _objc_class_ext *ext;
2771 };
2772 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002773 static bool objc_class = false;
2774 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002775 Result += "\nstruct _objc_class {\n";
2776 Result += "\tstruct _objc_class *isa;\n";
2777 Result += "\tconst char *super_class_name;\n";
2778 Result += "\tchar *name;\n";
2779 Result += "\tlong version;\n";
2780 Result += "\tlong info;\n";
2781 Result += "\tlong instance_size;\n";
2782 Result += "\tstruct _objc_ivar_list *ivars;\n";
2783 Result += "\tstruct _objc_method_list *methods;\n";
2784 Result += "\tstruct objc_cache *cache;\n";
2785 Result += "\tstruct _objc_protocol_list *protocols;\n";
2786 Result += "\tconst char *ivar_layout;\n";
2787 Result += "\tstruct _objc_class_ext *ext;\n";
2788 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002789 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002790 }
2791
2792 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002793 ObjCInterfaceDecl *RootClass = 0;
2794 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002795 while (SuperClass) {
2796 RootClass = SuperClass;
2797 SuperClass = SuperClass->getSuperClass();
2798 }
2799 SuperClass = CDecl->getSuperClass();
2800
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002801 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2802 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002803 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002804 "{\n\t(struct _objc_class *)\"";
2805 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2806 Result += "\"";
2807
2808 if (SuperClass) {
2809 Result += ", \"";
2810 Result += SuperClass->getName();
2811 Result += "\", \"";
2812 Result += CDecl->getName();
2813 Result += "\"";
2814 }
2815 else {
2816 Result += ", 0, \"";
2817 Result += CDecl->getName();
2818 Result += "\"";
2819 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002820 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002821 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002822 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002823 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002824 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002825 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002826 Result += "\n";
2827 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002828 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002829 Result += ", 0\n";
2830 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002831 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002832 Result += CDecl->getName();
2833 Result += ",0,0\n";
2834 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002835 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002836 Result += "\t,0,0,0,0\n";
2837 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002838
2839 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002840 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2841 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002842 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002843 "{\n\t&_OBJC_METACLASS_";
2844 Result += CDecl->getName();
2845 if (SuperClass) {
2846 Result += ", \"";
2847 Result += SuperClass->getName();
2848 Result += "\", \"";
2849 Result += CDecl->getName();
2850 Result += "\"";
2851 }
2852 else {
2853 Result += ", 0, \"";
2854 Result += CDecl->getName();
2855 Result += "\"";
2856 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002857 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002858 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002859 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002860 Result += ",0";
2861 else {
2862 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002863 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002864 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002865 if (LangOpts.Microsoft)
2866 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002867 Result += ")";
2868 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002869 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002870 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002871 Result += CDecl->getName();
2872 Result += "\n\t";
2873 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002874 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002875 Result += ",0";
2876 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002877 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002878 Result += CDecl->getName();
2879 Result += ", 0\n\t";
2880 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002881 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002882 Result += ",0,0";
2883 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002884 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002885 Result += CDecl->getName();
2886 Result += ", 0,0\n";
2887 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002888 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002889 Result += ",0,0,0\n";
2890 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002891}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002892
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002893/// RewriteImplementations - This routine rewrites all method implementations
2894/// and emits meta-data.
2895
Steve Naroffb29b4272008-04-14 22:03:09 +00002896void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002897 int ClsDefCount = ClassImplementation.size();
2898 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002899
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002900 if (ClsDefCount == 0 && CatDefCount == 0)
2901 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002902 // Rewrite implemented methods
2903 for (int i = 0; i < ClsDefCount; i++)
2904 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002905
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002906 for (int i = 0; i < CatDefCount; i++)
2907 RewriteImplementationDecl(CategoryImplementation[i]);
2908
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002909 // This is needed for use of offsetof
Steve Naroffb10f2732008-04-04 22:58:22 +00002910 Result += "#define offsetof(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002911 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002912 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002913 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002914
2915 // For each implemented category, write out all its meta data.
2916 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002917 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002918
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002919 // Write objc_symtab metadata
2920 /*
2921 struct _objc_symtab
2922 {
2923 long sel_ref_cnt;
2924 SEL *refs;
2925 short cls_def_cnt;
2926 short cat_def_cnt;
2927 void *defs[cls_def_cnt + cat_def_cnt];
2928 };
2929 */
2930
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002931 Result += "\nstruct _objc_symtab {\n";
2932 Result += "\tlong sel_ref_cnt;\n";
2933 Result += "\tSEL *refs;\n";
2934 Result += "\tshort cls_def_cnt;\n";
2935 Result += "\tshort cat_def_cnt;\n";
2936 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2937 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002938
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002939 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002940 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002941 Result += "\t0, 0, " + utostr(ClsDefCount)
2942 + ", " + utostr(CatDefCount) + "\n";
2943 for (int i = 0; i < ClsDefCount; i++) {
2944 Result += "\t,&_OBJC_CLASS_";
2945 Result += ClassImplementation[i]->getName();
2946 Result += "\n";
2947 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002948
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002949 for (int i = 0; i < CatDefCount; i++) {
2950 Result += "\t,&_OBJC_CATEGORY_";
2951 Result += CategoryImplementation[i]->getClassInterface()->getName();
2952 Result += "_";
2953 Result += CategoryImplementation[i]->getName();
2954 Result += "\n";
2955 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002956
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002957 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002958
2959 // Write objc_module metadata
2960
2961 /*
2962 struct _objc_module {
2963 long version;
2964 long size;
2965 const char *name;
2966 struct _objc_symtab *symtab;
2967 }
2968 */
2969
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002970 Result += "\nstruct _objc_module {\n";
2971 Result += "\tlong version;\n";
2972 Result += "\tlong size;\n";
2973 Result += "\tconst char *name;\n";
2974 Result += "\tstruct _objc_symtab *symtab;\n";
2975 Result += "};\n\n";
2976 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00002977 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002978 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2979 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002980 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002981
2982 if (LangOpts.Microsoft) {
2983 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2984 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2985 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2986 Result += "&_OBJC_MODULES;\n";
2987 Result += "#pragma data_seg(pop)\n\n";
2988 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002989}
Chris Lattner311ff022007-10-16 22:36:42 +00002990