blob: f02dd922a41d4d3c9ee426a4287511f4a5ed416a [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
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"
Steve Naroff874e2322007-11-15 10:28:18 +000026#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000027using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000028using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000029
Steve Naroff0113c9d2008-01-28 21:34:52 +000030static llvm::cl::opt<bool>
31SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
32 llvm::cl::desc("Silence ObjC rewriting warnings"));
33
Chris Lattner77cd2a02007-10-11 00:43:27 +000034namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000035 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000036 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000037 Diagnostic &Diags;
Steve Narofff69cc5d2008-01-30 19:17:43 +000038 unsigned RewriteFailedDiag;
39
Chris Lattner01c57482007-10-17 22:35:30 +000040 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000041 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000042 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000043 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000044 SourceLocation LastIncLoc;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000045 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
46 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
47 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
49 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000050 llvm::SmallVector<Stmt *, 32> Stmts;
51 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000052 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000053
54 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000055 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000056 FunctionDecl *MsgSendStretFunctionDecl;
57 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000058 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000059 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000060 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000061 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000062 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000063 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000064
Steve Naroffbeaf2992007-11-03 11:27:19 +000065 // ObjC string constant support.
66 FileVarDecl *ConstantStringClassReference;
67 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000068
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000069 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000070 int BcLabelCount;
71
Steve Naroff874e2322007-11-15 10:28:18 +000072 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000073 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000074 RecordDecl *SuperStructDecl;
75
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000076 // Needed for header files being rewritten
77 bool IsHeader;
78
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000079 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000080 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000081 void Initialize(ASTContext &context);
82
Chris Lattner8a12c272007-10-11 18:38:32 +000083
Chris Lattnerf04da132007-10-24 17:06:59 +000084 // Top Level Driver code.
85 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000086 void HandleDeclInMainFile(Decl *D);
Steve Naroff0113c9d2008-01-28 21:34:52 +000087 RewriteTest(bool isHeader, Diagnostic &D) : Diags(D) {
Steve Narofff69cc5d2008-01-30 19:17:43 +000088 IsHeader = isHeader;
Steve Naroff0113c9d2008-01-28 21:34:52 +000089 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
90 "rewriting sub-expression within a macro (may not be correct)");
Steve Narofff69cc5d2008-01-30 19:17:43 +000091 }
Chris Lattnerf04da132007-10-24 17:06:59 +000092 ~RewriteTest();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000093
94 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +000095 // If replacement succeeded or warning disabled return with no warning.
96 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000097 return;
98
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000099 SourceRange Range = Old->getSourceRange();
100 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
101 0, 0, &Range, 1);
102 }
103
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000104 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) {
105 // If replacement succeeded or warning disabled return with no warning.
106 if (!Rewrite.InsertText(Loc, StrData, StrLen) ||
107 SilenceRewriteMacroWarning)
108 return;
109
110 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
111 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000112
Chris Lattnerf04da132007-10-24 17:06:59 +0000113
114 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000115 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000116 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000117 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000118 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
119 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000120 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000121 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
122 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
123 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
124 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
125 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
126 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000127 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000128 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000129 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000130 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000131 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000132
Chris Lattnerf04da132007-10-24 17:06:59 +0000133 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000134 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000135 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000136 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000137 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000138 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000139 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000140 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000141 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000142 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000143 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
144 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
145 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000146 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
147 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000148 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
149 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000150 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000151 Stmt *RewriteBreakStmt(BreakStmt *S);
152 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000153 void SynthCountByEnumWithState(std::string &buf);
154
Steve Naroff09b266e2007-10-30 23:14:51 +0000155 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000156 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000157 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000158 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000159 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000160 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000161 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000162 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000163 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000164 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000165
Chris Lattnerf04da132007-10-24 17:06:59 +0000166 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000167 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000168 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000169
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000170 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000171 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000172
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000173 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
174 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000175 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000176 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000177 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000178 const char *ClassName,
179 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000180
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000181 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000182 int NumProtocols,
183 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000184 const char *ClassName,
185 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000186 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000187 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000188 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
189 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000190 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000191 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000192 };
193}
194
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000195static bool IsHeaderFile(const std::string &Filename) {
196 std::string::size_type DotPos = Filename.rfind('.');
197
198 if (DotPos == std::string::npos) {
199 // no file extension
200 return false;
201 }
202
203 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
204 // C header: .h
205 // C++ header: .hh or .H;
206 return Ext == "h" || Ext == "hh" || Ext == "H";
207}
208
209ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
210 Diagnostic &Diags) {
211 return new RewriteTest(IsHeaderFile(InFile), Diags);
Chris Lattnere365c502007-11-30 22:25:36 +0000212}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000213
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000214void RewriteTest::Initialize(ASTContext &context) {
215 Context = &context;
216 SM = &Context->getSourceManager();
217 MsgSendFunctionDecl = 0;
218 MsgSendSuperFunctionDecl = 0;
219 MsgSendStretFunctionDecl = 0;
220 MsgSendSuperStretFunctionDecl = 0;
221 MsgSendFpretFunctionDecl = 0;
222 GetClassFunctionDecl = 0;
223 GetMetaClassFunctionDecl = 0;
224 SelGetUidFunctionDecl = 0;
225 CFStringFunctionDecl = 0;
226 GetProtocolFunctionDecl = 0;
227 ConstantStringClassReference = 0;
228 NSStringRecord = 0;
229 CurMethodDecl = 0;
230 SuperStructDecl = 0;
231 BcLabelCount = 0;
232
233 // Get the ID and start/end of the main file.
234 MainFileID = SM->getMainFileID();
235 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
236 MainFileStart = MainBuf->getBufferStart();
237 MainFileEnd = MainBuf->getBufferEnd();
238
239
240 Rewrite.setSourceMgr(Context->getSourceManager());
241 // declaring objc_selector outside the parameter list removes a silly
242 // scope related warning...
243 const char *s = "#pragma once\n"
244 "struct objc_selector; struct objc_class;\n"
245 "#ifndef OBJC_SUPER\n"
246 "struct objc_super { struct objc_object *o; "
247 "struct objc_object *superClass; };\n"
248 "#define OBJC_SUPER\n"
249 "#endif\n"
250 "#ifndef _REWRITER_typedef_Protocol\n"
251 "typedef struct objc_object Protocol;\n"
252 "#define _REWRITER_typedef_Protocol\n"
253 "#endif\n"
254 "extern struct objc_object *objc_msgSend"
255 "(struct objc_object *, struct objc_selector *, ...);\n"
256 "extern struct objc_object *objc_msgSendSuper"
257 "(struct objc_super *, struct objc_selector *, ...);\n"
258 "extern struct objc_object *objc_msgSend_stret"
259 "(struct objc_object *, struct objc_selector *, ...);\n"
260 "extern struct objc_object *objc_msgSendSuper_stret"
261 "(struct objc_super *, struct objc_selector *, ...);\n"
262 "extern struct objc_object *objc_msgSend_fpret"
263 "(struct objc_object *, struct objc_selector *, ...);\n"
264 "extern struct objc_object *objc_getClass"
265 "(const char *);\n"
266 "extern struct objc_object *objc_getMetaClass"
267 "(const char *);\n"
268 "extern void objc_exception_throw(struct objc_object *);\n"
269 "extern void objc_exception_try_enter(void *);\n"
270 "extern void objc_exception_try_exit(void *);\n"
271 "extern struct objc_object *objc_exception_extract(void *);\n"
272 "extern int objc_exception_match"
273 "(struct objc_class *, struct objc_object *, ...);\n"
274 "extern Protocol *objc_getProtocol(const char *);\n"
275 "#include <objc/objc.h>\n"
276 "#ifndef __FASTENUMERATIONSTATE\n"
277 "struct __objcFastEnumerationState {\n\t"
278 "unsigned long state;\n\t"
279 "id *itemsPtr;\n\t"
280 "unsigned long *mutationsPtr;\n\t"
281 "unsigned long extra[5];\n};\n"
282 "#define __FASTENUMERATIONSTATE\n"
283 "#endif\n";
284 if (IsHeader) {
285 // insert the whole string when rewriting a header file
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000286 InsertText(SourceLocation::getFileLoc(MainFileID, 0), s, strlen(s));
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000287 }
288 else {
289 // Not rewriting header, exclude the #pragma once pragma
290 const char *p = s + strlen("#pragma once\n");
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000291 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000292 }
293}
294
295
Chris Lattnerf04da132007-10-24 17:06:59 +0000296//===----------------------------------------------------------------------===//
297// Top Level Driver Code
298//===----------------------------------------------------------------------===//
299
Chris Lattner8a12c272007-10-11 18:38:32 +0000300void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000301 // Two cases: either the decl could be in the main file, or it could be in a
302 // #included file. If the former, rewrite it now. If the later, check to see
303 // if we rewrote the #include/#import.
304 SourceLocation Loc = D->getLocation();
305 Loc = SM->getLogicalLoc(Loc);
306
307 // If this is for a builtin, ignore it.
308 if (Loc.isInvalid()) return;
309
Steve Naroffebf2b562007-10-23 23:50:29 +0000310 // Look for built-in declarations that we need to refer during the rewrite.
311 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000312 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000313 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
314 // declared in <Foundation/NSString.h>
315 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
316 ConstantStringClassReference = FVD;
317 return;
318 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000319 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000320 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000321 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000322 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000323 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000324 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000325 } else if (ObjCForwardProtocolDecl *FP =
326 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000327 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000328 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000329 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000330 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
331 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000332}
333
Chris Lattnerf04da132007-10-24 17:06:59 +0000334/// HandleDeclInMainFile - This is called for each top-level decl defined in the
335/// main file of the input.
336void RewriteTest::HandleDeclInMainFile(Decl *D) {
337 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
338 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000339 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000340
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000341 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000342 if (Stmt *Body = MD->getBody()) {
343 //Body->dump();
344 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000345 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000346 CurMethodDecl = 0;
347 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000348 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000349 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000350 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000351 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000352 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000353 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000354 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000355 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000356 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000357 if (VD->getInit())
358 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
359 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000360 // Nothing yet.
361}
362
363RewriteTest::~RewriteTest() {
364 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000365
366 // Rewrite tabs if we care.
367 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000368
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000369 RewriteInclude();
370
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000371 // Rewrite Objective-c meta data*
372 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000373 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000374
Chris Lattnerf04da132007-10-24 17:06:59 +0000375 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
376 // we are done.
377 if (const RewriteBuffer *RewriteBuf =
378 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000379 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000380 std::string S(RewriteBuf->begin(), RewriteBuf->end());
381 printf("%s\n", S.c_str());
382 } else {
383 printf("No changes\n");
384 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000385 // Emit metadata.
386 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000387}
388
Chris Lattnerf04da132007-10-24 17:06:59 +0000389//===----------------------------------------------------------------------===//
390// Syntactic (non-AST) Rewriting Code
391//===----------------------------------------------------------------------===//
392
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000393void RewriteTest::RewriteInclude() {
394 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
395 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
396 const char *MainBufStart = MainBuf.first;
397 const char *MainBufEnd = MainBuf.second;
398 size_t ImportLen = strlen("import");
399 size_t IncludeLen = strlen("include");
400
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000401 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000402 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
403 if (*BufPtr == '#') {
404 if (++BufPtr == MainBufEnd)
405 return;
406 while (*BufPtr == ' ' || *BufPtr == '\t')
407 if (++BufPtr == MainBufEnd)
408 return;
409 if (!strncmp(BufPtr, "import", ImportLen)) {
410 // replace import with include
411 SourceLocation ImportLoc =
412 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
413 Rewrite.ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
414 BufPtr += ImportLen;
415 }
416 }
417 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000418}
419
Chris Lattnerf04da132007-10-24 17:06:59 +0000420void RewriteTest::RewriteTabs() {
421 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
422 const char *MainBufStart = MainBuf.first;
423 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000424
Chris Lattnerf04da132007-10-24 17:06:59 +0000425 // Loop over the whole file, looking for tabs.
426 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
427 if (*BufPtr != '\t')
428 continue;
429
430 // Okay, we found a tab. This tab will turn into at least one character,
431 // but it depends on which 'virtual column' it is in. Compute that now.
432 unsigned VCol = 0;
433 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
434 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
435 ++VCol;
436
437 // Okay, now that we know the virtual column, we know how many spaces to
438 // insert. We assume 8-character tab-stops.
439 unsigned Spaces = 8-(VCol & 7);
440
441 // Get the location of the tab.
442 SourceLocation TabLoc =
443 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
444
445 // Rewrite the single tab character into a sequence of spaces.
446 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
447 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000448}
449
450
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000451void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000452 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000453 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000454
455 // Get the start location and compute the semi location.
456 SourceLocation startLoc = ClassDecl->getLocation();
457 const char *startBuf = SM->getCharacterData(startLoc);
458 const char *semiPtr = strchr(startBuf, ';');
459
460 // Translate to typedef's that forward reference structs with the same name
461 // as the class. As a convenience, we include the original declaration
462 // as a comment.
463 std::string typedefString;
464 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000465 typedefString.append(startBuf, semiPtr-startBuf+1);
466 typedefString += "\n";
467 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000468 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000469 typedefString += "#ifndef _REWRITER_typedef_";
470 typedefString += ForwardDecl->getName();
471 typedefString += "\n";
472 typedefString += "#define _REWRITER_typedef_";
473 typedefString += ForwardDecl->getName();
474 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000475 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000476 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000477 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000478 }
479
480 // Replace the @class with typedefs corresponding to the classes.
481 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
482 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000483}
484
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000485void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000486 SourceLocation LocStart = Method->getLocStart();
487 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000488
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000489 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000490 InsertText(LocStart, "/* ", 3);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000491 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000492 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000493 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000494 }
495}
496
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000497void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000498{
499 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000500 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000501 SourceLocation Loc = Property->getLocation();
502
503 Rewrite.ReplaceText(Loc, 0, "// ", 3);
504
505 // FIXME: handle properties that are declared across multiple lines.
506 }
507}
508
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000509void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000510 SourceLocation LocStart = CatDecl->getLocStart();
511
512 // FIXME: handle category headers that are declared across multiple lines.
513 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
514
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000515 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000516 E = CatDecl->instmeth_end(); I != E; ++I)
517 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000518 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000519 E = CatDecl->classmeth_end(); I != E; ++I)
520 RewriteMethodDeclaration(*I);
521
Steve Naroff423cb562007-10-30 13:30:57 +0000522 // Lastly, comment out the @end.
523 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
524}
525
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000526void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000527 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000528
Steve Naroff752d6ef2007-10-30 16:42:30 +0000529 SourceLocation LocStart = PDecl->getLocStart();
530
531 // FIXME: handle protocol headers that are declared across multiple lines.
532 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
533
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000534 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000535 E = PDecl->instmeth_end(); I != E; ++I)
536 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000537 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000538 E = PDecl->classmeth_end(); I != E; ++I)
539 RewriteMethodDeclaration(*I);
540
Steve Naroff752d6ef2007-10-30 16:42:30 +0000541 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000542 SourceLocation LocEnd = PDecl->getAtEndLoc();
543 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000544
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000545 // Must comment out @optional/@required
546 const char *startBuf = SM->getCharacterData(LocStart);
547 const char *endBuf = SM->getCharacterData(LocEnd);
548 for (const char *p = startBuf; p < endBuf; p++) {
549 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
550 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000551 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000552 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
553 CommentedOptional.c_str(), CommentedOptional.size());
554
555 }
556 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
557 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000558 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000559 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
560 CommentedRequired.c_str(), CommentedRequired.size());
561
562 }
563 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000564}
565
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000566void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000567 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000568 if (LocStart.isInvalid())
569 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000570 // FIXME: handle forward protocol that are declared across multiple lines.
571 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
572}
573
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000574void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000575 std::string &ResultStr) {
576 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000577 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000578 ResultStr += "id";
579 else
580 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000581 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000582
583 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000584 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000585
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000586 if (OMD->isInstance())
587 NameStr += "_I_";
588 else
589 NameStr += "_C_";
590
591 NameStr += OMD->getClassInterface()->getName();
592 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000593
594 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000595 if (ObjCCategoryImplDecl *CID =
596 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000597 NameStr += CID->getName();
598 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000599 }
600 // Append selector names, replacing ':' with '_'
601 const char *selName = OMD->getSelector().getName().c_str();
602 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000603 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000604 else {
605 std::string selString = OMD->getSelector().getName();
606 int len = selString.size();
607 for (int i = 0; i < len; i++)
608 if (selString[i] == ':')
609 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000610 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000611 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000612 // Remember this name for metadata emission
613 MethodInternalNames[OMD] = NameStr;
614 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000615
616 // Rewrite arguments
617 ResultStr += "(";
618
619 // invisible arguments
620 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000621 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000622 selfTy = Context->getPointerType(selfTy);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000623 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000624 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000625 ResultStr += selfTy.getAsString();
626 }
627 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000628 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000629
630 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000631 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000632 ResultStr += " _cmd";
633
634 // Method arguments.
635 for (int i = 0; i < OMD->getNumParams(); i++) {
636 ParmVarDecl *PDecl = OMD->getParamDecl(i);
637 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000638 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000639 ResultStr += "id";
640 else
641 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000642 ResultStr += " ";
643 ResultStr += PDecl->getName();
644 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000645 if (OMD->isVariadic())
646 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000647 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000648
649}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000650void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000651 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
652 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000653
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000654 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000655 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000656 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000657 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000658
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000659 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000660 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
661 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000662 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000663 ObjCMethodDecl *OMD = *I;
664 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000665 SourceLocation LocStart = OMD->getLocStart();
666 SourceLocation LocEnd = OMD->getBody()->getLocStart();
667
668 const char *startBuf = SM->getCharacterData(LocStart);
669 const char *endBuf = SM->getCharacterData(LocEnd);
670 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
671 ResultStr.c_str(), ResultStr.size());
672 }
673
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000674 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000675 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
676 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000677 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000678 ObjCMethodDecl *OMD = *I;
679 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000680 SourceLocation LocStart = OMD->getLocStart();
681 SourceLocation LocEnd = OMD->getBody()->getLocStart();
682
683 const char *startBuf = SM->getCharacterData(LocStart);
684 const char *endBuf = SM->getCharacterData(LocEnd);
685 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
686 ResultStr.c_str(), ResultStr.size());
687 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000688 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000689 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000690 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000691 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000692}
693
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000694void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000695 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000696 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000697 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000698 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000699 ResultStr += ClassDecl->getName();
700 ResultStr += "\n";
701 ResultStr += "#define _REWRITER_typedef_";
702 ResultStr += ClassDecl->getName();
703 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000704 ResultStr += "typedef struct ";
705 ResultStr += ClassDecl->getName();
706 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000707 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000708 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000709
710 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000711 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000712 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000713 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000714
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000715 RewriteProperties(ClassDecl->getNumPropertyDecl(),
716 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000717 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000718 E = ClassDecl->instmeth_end(); I != E; ++I)
719 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000720 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000721 E = ClassDecl->classmeth_end(); I != E; ++I)
722 RewriteMethodDeclaration(*I);
723
Steve Naroff2feac5e2007-10-30 03:43:13 +0000724 // Lastly, comment out the @end.
725 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000726}
727
Steve Naroff7e3411b2007-11-15 02:58:25 +0000728Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000729 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff7e3411b2007-11-15 02:58:25 +0000730 if (IV->isFreeIvar()) {
731 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
732 IV->getLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000733 ReplaceStmt(IV, Replacement);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000734 delete IV;
735 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000736 } else {
Fariborz Jahanian7da8d942008-01-23 20:34:40 +0000737#if 0
738 /// This code is not right. It seems unnecessary. It breaks use of
739 /// ivar reference used as 'receiver' of an expression; as in:
740 /// [newInv->_container addObject:0];
Steve Naroffc2a689b2007-11-15 11:33:00 +0000741 if (CurMethodDecl) {
742 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000743 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffc2a689b2007-11-15 11:33:00 +0000744 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
745 IdentifierInfo *II = intT->getDecl()->getIdentifier();
746 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
747 II, 0);
748 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
749
750 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
751 // Don't forget the parens to enforce the proper binding.
752 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000753 ReplaceStmt(IV->getBase(), PE);
Steve Naroffc2a689b2007-11-15 11:33:00 +0000754 delete IV->getBase();
755 return PE;
756 }
757 }
758 }
Fariborz Jahanian7da8d942008-01-23 20:34:40 +0000759#endif
Steve Naroff7e3411b2007-11-15 02:58:25 +0000760 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000761 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000762}
763
Chris Lattnerf04da132007-10-24 17:06:59 +0000764//===----------------------------------------------------------------------===//
765// Function Body / Expression rewriting
766//===----------------------------------------------------------------------===//
767
Steve Narofff3473a72007-11-09 15:20:18 +0000768Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000769 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
770 isa<DoStmt>(S) || isa<ForStmt>(S))
771 Stmts.push_back(S);
772 else if (isa<ObjCForCollectionStmt>(S)) {
773 Stmts.push_back(S);
774 ObjCBcLabelNo.push_back(++BcLabelCount);
775 }
776
Chris Lattner338d1e22008-01-31 05:10:40 +0000777 SourceLocation OrigStmtEnd = S->getLocEnd();
778
779 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000780 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
781 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000782 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000783 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000784 if (newStmt)
785 *CI = newStmt;
786 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000787
788 // Handle specific things.
789 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
790 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000791
792 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
793 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000794
795 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
796 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000797
Steve Naroffbeaf2992007-11-03 11:27:19 +0000798 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
799 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000800
Steve Naroff934f2762007-10-24 22:48:43 +0000801 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
802 // Before we rewrite it, put the original message expression in a comment.
803 SourceLocation startLoc = MessExpr->getLocStart();
804 SourceLocation endLoc = MessExpr->getLocEnd();
805
806 const char *startBuf = SM->getCharacterData(startLoc);
807 const char *endBuf = SM->getCharacterData(endLoc);
808
809 std::string messString;
810 messString += "// ";
811 messString.append(startBuf, endBuf-startBuf+1);
812 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000813
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000814 // FIXME: Missing definition of
815 // InsertText(clang::SourceLocation, char const*, unsigned int).
816 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000817 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000818 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000819 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000820 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000821
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000822 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
823 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000824
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000825 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
826 return RewriteObjCSynchronizedStmt(StmtTry);
827
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000828 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
829 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000830
831 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
832 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000833
834 if (ObjCForCollectionStmt *StmtForCollection =
835 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000836 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000837 if (BreakStmt *StmtBreakStmt =
838 dyn_cast<BreakStmt>(S))
839 return RewriteBreakStmt(StmtBreakStmt);
840 if (ContinueStmt *StmtContinueStmt =
841 dyn_cast<ContinueStmt>(S))
842 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000843
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000844 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
845 isa<DoStmt>(S) || isa<ForStmt>(S)) {
846 assert(!Stmts.empty() && "Statement stack is empty");
847 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
848 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
849 && "Statement stack mismatch");
850 Stmts.pop_back();
851 }
Steve Naroff874e2322007-11-15 10:28:18 +0000852#if 0
853 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
854 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
855 // Get the new text.
856 std::ostringstream Buf;
857 Replacement->printPretty(Buf);
858 const std::string &Str = Buf.str();
859
860 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000861 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000862 delete S;
863 return Replacement;
864 }
865#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000866 // Return this stmt unmodified.
867 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000868}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000869
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000870/// SynthCountByEnumWithState - To print:
871/// ((unsigned int (*)
872/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
873/// (void *)objc_msgSend)((id)l_collection,
874/// sel_registerName(
875/// "countByEnumeratingWithState:objects:count:"),
876/// &enumState,
877/// (id *)items, (unsigned int)16)
878///
879void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
880 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
881 "id *, unsigned int))(void *)objc_msgSend)";
882 buf += "\n\t\t";
883 buf += "((id)l_collection,\n\t\t";
884 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
885 buf += "\n\t\t";
886 buf += "&enumState, "
887 "(id *)items, (unsigned int)16)";
888}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000889
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000890/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
891/// statement to exit to its outer synthesized loop.
892///
893Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
894 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
895 return S;
896 // replace break with goto __break_label
897 std::string buf;
898
899 SourceLocation startLoc = S->getLocStart();
900 buf = "goto __break_label_";
901 buf += utostr(ObjCBcLabelNo.back());
902 Rewrite.ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
903
904 return 0;
905}
906
907/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
908/// statement to continue with its inner synthesized loop.
909///
910Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
911 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
912 return S;
913 // replace continue with goto __continue_label
914 std::string buf;
915
916 SourceLocation startLoc = S->getLocStart();
917 buf = "goto __continue_label_";
918 buf += utostr(ObjCBcLabelNo.back());
919 Rewrite.ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
920
921 return 0;
922}
923
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000924/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000925/// It rewrites:
926/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000927
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000928/// Into:
929/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000930/// type elem;
931/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000932/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000933/// id l_collection = (id)collection;
934/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
935/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000936/// if (limit) {
937/// unsigned long startMutations = *enumState.mutationsPtr;
938/// do {
939/// unsigned long counter = 0;
940/// do {
941/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000942/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000943/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000944/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000945/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000946/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000947/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
948/// objects:items count:16]);
949/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000950/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000951/// }
952/// else
953/// elem = nil;
954/// }
955///
Chris Lattner338d1e22008-01-31 05:10:40 +0000956Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
957 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000958 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
959 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
960 "ObjCForCollectionStmt Statement stack mismatch");
961 assert(!ObjCBcLabelNo.empty() &&
962 "ObjCForCollectionStmt - Label No stack empty");
963
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000964 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000965 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000966 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000967 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000968 std::string buf;
969 buf = "\n{\n\t";
970 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
971 // type elem;
972 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000973 elementTypeAsString = ElementType.getAsString();
974 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000975 buf += " ";
976 elementName = DS->getDecl()->getName();
977 buf += elementName;
978 buf += ";\n\t";
979 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000980 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000981 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000982 elementTypeAsString = DR->getDecl()->getType().getAsString();
983 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000984 else
985 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
986
987 // struct __objcFastEnumerationState enumState = { 0 };
988 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
989 // id items[16];
990 buf += "id items[16];\n\t";
991 // id l_collection = (id)
992 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +0000993 // Find start location of 'collection' the hard way!
994 const char *startCollectionBuf = startBuf;
995 startCollectionBuf += 3; // skip 'for'
996 startCollectionBuf = strchr(startCollectionBuf, '(');
997 startCollectionBuf++; // skip '('
998 // find 'in' and skip it.
999 while (*startCollectionBuf != ' ' ||
1000 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1001 (*(startCollectionBuf+3) != ' ' &&
1002 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1003 startCollectionBuf++;
1004 startCollectionBuf += 3;
1005
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001006 // Replace: "for (type element in" with string constructed thus far.
1007 Rewrite.ReplaceText(startLoc, startCollectionBuf - startBuf,
1008 buf.c_str(), buf.size());
1009 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001010 SourceLocation rightParenLoc = S->getRParenLoc();
1011 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1012 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001013 buf = ";\n\t";
1014
1015 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1016 // objects:items count:16];
1017 // which is synthesized into:
1018 // unsigned int limit =
1019 // ((unsigned int (*)
1020 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1021 // (void *)objc_msgSend)((id)l_collection,
1022 // sel_registerName(
1023 // "countByEnumeratingWithState:objects:count:"),
1024 // (struct __objcFastEnumerationState *)&state,
1025 // (id *)items, (unsigned int)16);
1026 buf += "unsigned long limit =\n\t\t";
1027 SynthCountByEnumWithState(buf);
1028 buf += ";\n\t";
1029 /// if (limit) {
1030 /// unsigned long startMutations = *enumState.mutationsPtr;
1031 /// do {
1032 /// unsigned long counter = 0;
1033 /// do {
1034 /// if (startMutations != *enumState.mutationsPtr)
1035 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001036 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001037 buf += "if (limit) {\n\t";
1038 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1039 buf += "do {\n\t\t";
1040 buf += "unsigned long counter = 0;\n\t\t";
1041 buf += "do {\n\t\t\t";
1042 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1043 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1044 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001045 buf += " = (";
1046 buf += elementTypeAsString;
1047 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001048 // Replace ')' in for '(' type elem in collection ')' with all of these.
1049 Rewrite.ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
1050
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001051 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001052 /// } while (counter < limit);
1053 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1054 /// objects:items count:16]);
1055 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001056 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001057 /// }
1058 /// else
1059 /// elem = nil;
1060 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001061 ///
1062 buf = ";\n\t";
1063 buf += "__continue_label_";
1064 buf += utostr(ObjCBcLabelNo.back());
1065 buf += ": ;";
1066 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001067 buf += "} while (counter < limit);\n\t";
1068 buf += "} while (limit = ";
1069 SynthCountByEnumWithState(buf);
1070 buf += ");\n\t";
1071 buf += elementName;
1072 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001073 buf += "__break_label_";
1074 buf += utostr(ObjCBcLabelNo.back());
1075 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001076 buf += "}\n\t";
1077 buf += "else\n\t\t";
1078 buf += elementName;
1079 buf += " = nil;\n";
1080 buf += "}\n";
1081 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001082 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001083 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001084 Stmts.pop_back();
1085 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001086 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001087}
1088
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001089/// RewriteObjCSynchronizedStmt -
1090/// This routine rewrites @synchronized(expr) stmt;
1091/// into:
1092/// objc_sync_enter(expr);
1093/// @try stmt @finally { objc_sync_exit(expr); }
1094///
1095Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1096 // Get the start location and compute the semi location.
1097 SourceLocation startLoc = S->getLocStart();
1098 const char *startBuf = SM->getCharacterData(startLoc);
1099
1100 assert((*startBuf == '@') && "bogus @synchronized location");
1101
1102 std::string buf;
1103 buf = "objc_sync_enter";
1104 Rewrite.ReplaceText(startLoc, 13, buf.c_str(), buf.size());
1105 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1106 const char *endBuf = SM->getCharacterData(endLoc);
1107 endBuf++;
1108 const char *rparenBuf = strchr(endBuf, ')');
1109 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1110 buf = ");\n";
1111 // declare a new scope with two variables, _stack and _rethrow.
1112 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1113 buf += "int buf[18/*32-bit i386*/];\n";
1114 buf += "char *pointers[4];} _stack;\n";
1115 buf += "id volatile _rethrow = 0;\n";
1116 buf += "objc_exception_try_enter(&_stack);\n";
1117 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1118 Rewrite.ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
1119 startLoc = S->getSynchBody()->getLocEnd();
1120 startBuf = SM->getCharacterData(startLoc);
1121
1122 assert((*startBuf == '}') && "bogus @try block");
1123 SourceLocation lastCurlyLoc = startLoc;
1124 buf = "}\nelse {\n";
1125 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1126 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1127 // FIXME: This must be objc_sync_exit(syncExpr);
1128 buf += " objc_sync_exit();\n";
1129 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1130 buf += "}\n";
1131 buf += "}";
1132
1133 Rewrite.ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
1134 return 0;
1135}
1136
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001137Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001138 // Get the start location and compute the semi location.
1139 SourceLocation startLoc = S->getLocStart();
1140 const char *startBuf = SM->getCharacterData(startLoc);
1141
1142 assert((*startBuf == '@') && "bogus @try location");
1143
1144 std::string buf;
1145 // declare a new scope with two variables, _stack and _rethrow.
1146 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1147 buf += "int buf[18/*32-bit i386*/];\n";
1148 buf += "char *pointers[4];} _stack;\n";
1149 buf += "id volatile _rethrow = 0;\n";
1150 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001151 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001152
1153 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
1154
1155 startLoc = S->getTryBody()->getLocEnd();
1156 startBuf = SM->getCharacterData(startLoc);
1157
1158 assert((*startBuf == '}') && "bogus @try block");
1159
1160 SourceLocation lastCurlyLoc = startLoc;
1161
1162 startLoc = startLoc.getFileLocWithOffset(1);
1163 buf = " /* @catch begin */ else {\n";
1164 buf += " id _caught = objc_exception_extract(&_stack);\n";
1165 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001166 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001167 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1168 buf += " else { /* @catch continue */";
1169
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001170 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001171
1172 bool sawIdTypedCatch = false;
1173 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001174 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001175 while (catchList) {
1176 Stmt *catchStmt = catchList->getCatchParamStmt();
1177
1178 if (catchList == S->getCatchStmts())
1179 buf = "if ("; // we are generating code for the first catch clause
1180 else
1181 buf = "else if (";
1182 startLoc = catchList->getLocStart();
1183 startBuf = SM->getCharacterData(startLoc);
1184
1185 assert((*startBuf == '@') && "bogus @catch location");
1186
1187 const char *lParenLoc = strchr(startBuf, '(');
1188
1189 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
1190 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001191 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001192 buf += "1) { ";
1193 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1194 buf.c_str(), buf.size());
1195 sawIdTypedCatch = true;
1196 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001197 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001198
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001199 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001200 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001201 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001202 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001203 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +00001204 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1205 buf.c_str(), buf.size());
1206 }
1207 }
1208 // Now rewrite the body...
1209 lastCatchBody = catchList->getCatchBody();
1210 SourceLocation rParenLoc = catchList->getRParenLoc();
1211 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1212 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1213 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1214 assert((*rParenBuf == ')') && "bogus @catch paren location");
1215 assert((*bodyBuf == '{') && "bogus @catch body location");
1216
1217 buf = " = _caught;";
1218 // Here we replace ") {" with "= _caught;" (which initializes and
1219 // declares the @catch parameter).
1220 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
1221 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001222 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001223 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001224 }
Steve Naroff75730982007-11-07 04:08:17 +00001225 catchList = catchList->getNextCatchStmt();
1226 }
1227 // Complete the catch list...
1228 if (lastCatchBody) {
1229 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1230 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1231 assert((*bodyBuf == '}') && "bogus @catch body location");
1232 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1233 buf = " } } /* @catch end */\n";
1234
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001235 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001236
1237 // Set lastCurlyLoc
1238 lastCurlyLoc = lastCatchBody->getLocEnd();
1239 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001240 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001241 startLoc = finalStmt->getLocStart();
1242 startBuf = SM->getCharacterData(startLoc);
1243 assert((*startBuf == '@') && "bogus @finally start");
1244
1245 buf = "/* @finally */";
1246 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
1247
1248 Stmt *body = finalStmt->getFinallyBody();
1249 SourceLocation startLoc = body->getLocStart();
1250 SourceLocation endLoc = body->getLocEnd();
1251 const char *startBuf = SM->getCharacterData(startLoc);
1252 const char *endBuf = SM->getCharacterData(endLoc);
1253 assert((*startBuf == '{') && "bogus @finally body location");
1254 assert((*endBuf == '}') && "bogus @finally body location");
1255
1256 startLoc = startLoc.getFileLocWithOffset(1);
1257 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001258 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001259 endLoc = endLoc.getFileLocWithOffset(-1);
1260 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001261 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001262
1263 // Set lastCurlyLoc
1264 lastCurlyLoc = body->getLocEnd();
1265 }
1266 // Now emit the final closing curly brace...
1267 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1268 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001269 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001270 return 0;
1271}
1272
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001273Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001274 return 0;
1275}
1276
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001277Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001278 return 0;
1279}
1280
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001281// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001282// the throw expression is typically a message expression that's already
1283// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001284Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001285 // Get the start location and compute the semi location.
1286 SourceLocation startLoc = S->getLocStart();
1287 const char *startBuf = SM->getCharacterData(startLoc);
1288
1289 assert((*startBuf == '@') && "bogus @throw location");
1290
1291 std::string buf;
1292 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001293 if (S->getThrowExpr())
1294 buf = "objc_exception_throw(";
1295 else // add an implicit argument
1296 buf = "objc_exception_throw(_caught";
Steve Naroff2bd03922007-11-07 15:32:26 +00001297 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1298 const char *semiBuf = strchr(startBuf, ';');
1299 assert((*semiBuf == ';') && "@throw: can't find ';'");
1300 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1301 buf = ");";
1302 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
1303 return 0;
1304}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001305
Chris Lattnere64b7772007-10-24 16:57:36 +00001306Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001307 // Create a new string expression.
1308 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001309 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001310 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1311 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001312 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1313 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001314 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001315 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001316
Chris Lattner07506182007-11-30 22:53:43 +00001317 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001318 delete Exp;
1319 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001320}
1321
Steve Naroffb42f8412007-11-05 14:50:49 +00001322Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1323 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1324 // Create a call to sel_registerName("selName").
1325 llvm::SmallVector<Expr*, 8> SelExprs;
1326 QualType argType = Context->getPointerType(Context->CharTy);
1327 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1328 Exp->getSelector().getName().size(),
1329 false, argType, SourceLocation(),
1330 SourceLocation()));
1331 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1332 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001333 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001334 delete Exp;
1335 return SelExp;
1336}
1337
Steve Naroff934f2762007-10-24 22:48:43 +00001338CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1339 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001340 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001341 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001342
1343 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001344 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001345
1346 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001347 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001348 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1349
1350 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001351
Steve Naroff934f2762007-10-24 22:48:43 +00001352 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1353}
1354
Steve Naroffd5255f52007-11-01 13:24:47 +00001355static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1356 const char *&startRef, const char *&endRef) {
1357 while (startBuf < endBuf) {
1358 if (*startBuf == '<')
1359 startRef = startBuf; // mark the start.
1360 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001361 if (startRef && *startRef == '<') {
1362 endRef = startBuf; // mark the end.
1363 return true;
1364 }
1365 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001366 }
1367 startBuf++;
1368 }
1369 return false;
1370}
1371
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001372static void scanToNextArgument(const char *&argRef) {
1373 int angle = 0;
1374 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1375 if (*argRef == '<')
1376 angle++;
1377 else if (*argRef == '>')
1378 angle--;
1379 argRef++;
1380 }
1381 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1382}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001383
Steve Naroffd5255f52007-11-01 13:24:47 +00001384bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001385
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001386 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001387 return true;
1388
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001389 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001390 return true;
1391
Steve Naroffd5255f52007-11-01 13:24:47 +00001392 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001393 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001394 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001395 return true; // we have "Class <Protocol> *".
1396 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001397 return false;
1398}
1399
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001400void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001401 SourceLocation Loc;
1402 QualType Type;
1403 const FunctionTypeProto *proto = 0;
1404 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1405 Loc = VD->getLocation();
1406 Type = VD->getType();
1407 }
1408 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1409 Loc = FD->getLocation();
1410 // Check for ObjC 'id' and class types that have been adorned with protocol
1411 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1412 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1413 assert(funcType && "missing function type");
1414 proto = dyn_cast<FunctionTypeProto>(funcType);
1415 if (!proto)
1416 return;
1417 Type = proto->getResultType();
1418 }
1419 else
1420 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001421
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001422 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001423 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001424
1425 const char *endBuf = SM->getCharacterData(Loc);
1426 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001427 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001428 startBuf--; // scan backward (from the decl location) for return type.
1429 const char *startRef = 0, *endRef = 0;
1430 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1431 // Get the locations of the startRef, endRef.
1432 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1433 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1434 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001435 InsertText(LessLoc, "/*", 2);
1436 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001437 }
1438 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001439 if (!proto)
1440 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001441 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001442 const char *startBuf = SM->getCharacterData(Loc);
1443 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001444 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1445 if (needToScanForQualifiers(proto->getArgType(i))) {
1446 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001447
Steve Naroffd5255f52007-11-01 13:24:47 +00001448 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001449 // scan forward (from the decl location) for argument types.
1450 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001451 const char *startRef = 0, *endRef = 0;
1452 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1453 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001454 SourceLocation LessLoc =
1455 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1456 SourceLocation GreaterLoc =
1457 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001458 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001459 InsertText(LessLoc, "/*", 2);
1460 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001461 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001462 startBuf = ++endBuf;
1463 }
1464 else {
1465 while (*startBuf != ')' && *startBuf != ',')
1466 startBuf++; // scan forward (from the decl location) for argument types.
1467 startBuf++;
1468 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001469 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001470}
1471
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001472// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1473void RewriteTest::SynthSelGetUidFunctionDecl() {
1474 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1475 llvm::SmallVector<QualType, 16> ArgTys;
1476 ArgTys.push_back(Context->getPointerType(
1477 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001478 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001479 &ArgTys[0], ArgTys.size(),
1480 false /*isVariadic*/);
1481 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1482 SelGetUidIdent, getFuncType,
1483 FunctionDecl::Extern, false, 0);
1484}
1485
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001486// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1487void RewriteTest::SynthGetProtocolFunctionDecl() {
1488 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1489 llvm::SmallVector<QualType, 16> ArgTys;
1490 ArgTys.push_back(Context->getPointerType(
1491 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001492 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001493 &ArgTys[0], ArgTys.size(),
1494 false /*isVariadic*/);
1495 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1496 SelGetProtoIdent, getFuncType,
1497 FunctionDecl::Extern, false, 0);
1498}
1499
Steve Naroff09b266e2007-10-30 23:14:51 +00001500void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1501 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001502 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001503 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001504 return;
1505 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001506 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001507}
1508
1509// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1510void RewriteTest::SynthMsgSendFunctionDecl() {
1511 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1512 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001513 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001514 assert(!argT.isNull() && "Can't find 'id' type");
1515 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001516 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001517 assert(!argT.isNull() && "Can't find 'SEL' type");
1518 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001519 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001520 &ArgTys[0], ArgTys.size(),
1521 true /*isVariadic*/);
1522 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1523 msgSendIdent, msgSendType,
1524 FunctionDecl::Extern, false, 0);
1525}
1526
Steve Naroff874e2322007-11-15 10:28:18 +00001527// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1528void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1529 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1530 llvm::SmallVector<QualType, 16> ArgTys;
1531 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1532 &Context->Idents.get("objc_super"), 0);
1533 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1534 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1535 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001536 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001537 assert(!argT.isNull() && "Can't find 'SEL' type");
1538 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001539 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001540 &ArgTys[0], ArgTys.size(),
1541 true /*isVariadic*/);
1542 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1543 msgSendIdent, msgSendType,
1544 FunctionDecl::Extern, false, 0);
1545}
1546
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001547// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1548void RewriteTest::SynthMsgSendStretFunctionDecl() {
1549 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1550 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001551 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001552 assert(!argT.isNull() && "Can't find 'id' type");
1553 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001554 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001555 assert(!argT.isNull() && "Can't find 'SEL' type");
1556 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001557 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001558 &ArgTys[0], ArgTys.size(),
1559 true /*isVariadic*/);
1560 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1561 msgSendIdent, msgSendType,
1562 FunctionDecl::Extern, false, 0);
1563}
1564
1565// SynthMsgSendSuperStretFunctionDecl -
1566// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1567void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1568 IdentifierInfo *msgSendIdent =
1569 &Context->Idents.get("objc_msgSendSuper_stret");
1570 llvm::SmallVector<QualType, 16> ArgTys;
1571 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1572 &Context->Idents.get("objc_super"), 0);
1573 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1574 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1575 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001576 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001577 assert(!argT.isNull() && "Can't find 'SEL' type");
1578 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001579 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001580 &ArgTys[0], ArgTys.size(),
1581 true /*isVariadic*/);
1582 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1583 msgSendIdent, msgSendType,
1584 FunctionDecl::Extern, false, 0);
1585}
1586
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001587// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1588void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1589 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1590 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001591 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001592 assert(!argT.isNull() && "Can't find 'id' type");
1593 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001594 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001595 assert(!argT.isNull() && "Can't find 'SEL' type");
1596 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001597 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001598 &ArgTys[0], ArgTys.size(),
1599 true /*isVariadic*/);
1600 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1601 msgSendIdent, msgSendType,
1602 FunctionDecl::Extern, false, 0);
1603}
1604
Steve Naroff09b266e2007-10-30 23:14:51 +00001605// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1606void RewriteTest::SynthGetClassFunctionDecl() {
1607 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1608 llvm::SmallVector<QualType, 16> ArgTys;
1609 ArgTys.push_back(Context->getPointerType(
1610 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001611 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001612 &ArgTys[0], ArgTys.size(),
1613 false /*isVariadic*/);
1614 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1615 getClassIdent, getClassType,
1616 FunctionDecl::Extern, false, 0);
1617}
1618
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001619// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1620void RewriteTest::SynthGetMetaClassFunctionDecl() {
1621 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1622 llvm::SmallVector<QualType, 16> ArgTys;
1623 ArgTys.push_back(Context->getPointerType(
1624 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001625 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001626 &ArgTys[0], ArgTys.size(),
1627 false /*isVariadic*/);
1628 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1629 getClassIdent, getClassType,
1630 FunctionDecl::Extern, false, 0);
1631}
1632
Steve Naroff96984642007-11-08 14:30:50 +00001633// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1634void RewriteTest::SynthCFStringFunctionDecl() {
1635 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1636 llvm::SmallVector<QualType, 16> ArgTys;
1637 ArgTys.push_back(Context->getPointerType(
1638 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001639 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001640 &ArgTys[0], ArgTys.size(),
1641 false /*isVariadic*/);
1642 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1643 getClassIdent, getClassType,
1644 FunctionDecl::Extern, false, 0);
1645}
1646
Steve Naroffbeaf2992007-11-03 11:27:19 +00001647Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001648#if 1
1649 // This rewrite is specific to GCC, which has builtin support for CFString.
1650 if (!CFStringFunctionDecl)
1651 SynthCFStringFunctionDecl();
1652 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1653 llvm::SmallVector<Expr*, 8> StrExpr;
1654 StrExpr.push_back(Exp->getString());
1655 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1656 &StrExpr[0], StrExpr.size());
1657 // cast to NSConstantString *
1658 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001659 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001660 delete Exp;
1661 return cast;
1662#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001663 assert(ConstantStringClassReference && "Can't find constant string reference");
1664 llvm::SmallVector<Expr*, 4> InitExprs;
1665
1666 // Synthesize "(Class)&_NSConstantStringClassReference"
1667 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1668 ConstantStringClassReference->getType(),
1669 SourceLocation());
1670 QualType expType = Context->getPointerType(ClsRef->getType());
1671 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1672 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001673 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001674 SourceLocation());
1675 InitExprs.push_back(cast); // set the 'isa'.
1676 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1677 unsigned IntSize = static_cast<unsigned>(
1678 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1679 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1680 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1681 Exp->getLocStart());
1682 InitExprs.push_back(len); // set "int numBytes".
1683
1684 // struct NSConstantString
1685 QualType CFConstantStrType = Context->getCFConstantStringType();
1686 // (struct NSConstantString) { <exprs from above> }
1687 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1688 &InitExprs[0], InitExprs.size(),
1689 SourceLocation());
Steve Naroffe9b12192008-01-14 18:19:28 +00001690 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001691 // struct NSConstantString *
1692 expType = Context->getPointerType(StrRep->getType());
1693 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1694 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001695 // cast to NSConstantString *
1696 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001697 ReplaceStmt(Exp, cast);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001698 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001699 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001700#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001701}
1702
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001703ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001704 // check if we are sending a message to 'super'
1705 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001706 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1707 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1708 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1709 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001710 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001711 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001712 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001713 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001714 if (ObjCInterfaceType *IT =
1715 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001716 if (IT->getDecl() ==
1717 CurMethodDecl->getClassInterface()->getSuperClass())
1718 return IT->getDecl();
1719 }
1720 }
1721 }
1722 }
1723 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001724 }
Steve Naroff874e2322007-11-15 10:28:18 +00001725 }
1726 return 0;
1727}
1728
1729// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1730QualType RewriteTest::getSuperStructType() {
1731 if (!SuperStructDecl) {
1732 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1733 &Context->Idents.get("objc_super"), 0);
1734 QualType FieldTypes[2];
1735
1736 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001737 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001738 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001739 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001740 // Create fields
1741 FieldDecl *FieldDecls[2];
1742
1743 for (unsigned i = 0; i < 2; ++i)
1744 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1745
1746 SuperStructDecl->defineBody(FieldDecls, 4);
1747 }
1748 return Context->getTagDeclType(SuperStructDecl);
1749}
1750
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001751Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001752 if (!SelGetUidFunctionDecl)
1753 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001754 if (!MsgSendFunctionDecl)
1755 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001756 if (!MsgSendSuperFunctionDecl)
1757 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001758 if (!MsgSendStretFunctionDecl)
1759 SynthMsgSendStretFunctionDecl();
1760 if (!MsgSendSuperStretFunctionDecl)
1761 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001762 if (!MsgSendFpretFunctionDecl)
1763 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001764 if (!GetClassFunctionDecl)
1765 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001766 if (!GetMetaClassFunctionDecl)
1767 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001768
Steve Naroff874e2322007-11-15 10:28:18 +00001769 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001770 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1771 // May need to use objc_msgSend_stret() as well.
1772 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001773 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001774 QualType resultType = mDecl->getResultType();
1775 if (resultType.getCanonicalType()->isStructureType()
1776 || resultType.getCanonicalType()->isUnionType())
1777 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001778 else if (resultType.getCanonicalType()->isRealFloatingType())
1779 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001780 }
Steve Naroff874e2322007-11-15 10:28:18 +00001781
Steve Naroff934f2762007-10-24 22:48:43 +00001782 // Synthesize a call to objc_msgSend().
1783 llvm::SmallVector<Expr*, 8> MsgExprs;
1784 IdentifierInfo *clsName = Exp->getClassName();
1785
1786 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1787 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001788 if (!strcmp(clsName->getName(), "super")) {
1789 MsgSendFlavor = MsgSendSuperFunctionDecl;
1790 if (MsgSendStretFlavor)
1791 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1792 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1793
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001794 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001795 CurMethodDecl->getClassInterface()->getSuperClass();
1796
1797 llvm::SmallVector<Expr*, 4> InitExprs;
1798
1799 // set the receiver to self, the first argument to all methods.
1800 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001801 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001802 SourceLocation()));
1803 llvm::SmallVector<Expr*, 8> ClsExprs;
1804 QualType argType = Context->getPointerType(Context->CharTy);
1805 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1806 SuperDecl->getIdentifier()->getLength(),
1807 false, argType, SourceLocation(),
1808 SourceLocation()));
1809 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1810 &ClsExprs[0],
1811 ClsExprs.size());
1812 // To turn off a warning, type-cast to 'id'
1813 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001814 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001815 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1816 // struct objc_super
1817 QualType superType = getSuperStructType();
1818 // (struct objc_super) { <exprs from above> }
1819 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1820 &InitExprs[0], InitExprs.size(),
1821 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001822 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001823 superType, ILE, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001824 // struct objc_super *
1825 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1826 Context->getPointerType(SuperRep->getType()),
1827 SourceLocation());
1828 MsgExprs.push_back(Unop);
1829 } else {
1830 llvm::SmallVector<Expr*, 8> ClsExprs;
1831 QualType argType = Context->getPointerType(Context->CharTy);
1832 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1833 clsName->getLength(),
1834 false, argType, SourceLocation(),
1835 SourceLocation()));
1836 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1837 &ClsExprs[0],
1838 ClsExprs.size());
1839 MsgExprs.push_back(Cls);
1840 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001841 } else { // instance message.
1842 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001843
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001844 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001845 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001846 if (MsgSendStretFlavor)
1847 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001848 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1849
1850 llvm::SmallVector<Expr*, 4> InitExprs;
1851
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001852 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001853 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001854 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001855
1856 llvm::SmallVector<Expr*, 8> ClsExprs;
1857 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001858 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1859 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001860 false, argType, SourceLocation(),
1861 SourceLocation()));
1862 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001863 &ClsExprs[0],
1864 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001865 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001866 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001867 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001868 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001869 // struct objc_super
1870 QualType superType = getSuperStructType();
1871 // (struct objc_super) { <exprs from above> }
1872 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1873 &InitExprs[0], InitExprs.size(),
1874 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001875 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001876 superType, ILE, false);
Steve Naroff874e2322007-11-15 10:28:18 +00001877 // struct objc_super *
1878 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1879 Context->getPointerType(SuperRep->getType()),
1880 SourceLocation());
1881 MsgExprs.push_back(Unop);
1882 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001883 // Remove all type-casts because it may contain objc-style types; e.g.
1884 // Foo<Proto> *.
1885 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1886 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001887 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001888 MsgExprs.push_back(recExpr);
1889 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001890 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001891 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001892 llvm::SmallVector<Expr*, 8> SelExprs;
1893 QualType argType = Context->getPointerType(Context->CharTy);
1894 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1895 Exp->getSelector().getName().size(),
1896 false, argType, SourceLocation(),
1897 SourceLocation()));
1898 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1899 &SelExprs[0], SelExprs.size());
1900 MsgExprs.push_back(SelExp);
1901
1902 // Now push any user supplied arguments.
1903 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001904 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001905 // Make all implicit casts explicit...ICE comes in handy:-)
1906 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1907 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001908 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1909 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001910 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001911 }
1912 // Make id<P...> cast into an 'id' cast.
1913 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001914 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001915 while ((CE = dyn_cast<CastExpr>(userExpr)))
1916 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001917 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001918 userExpr, SourceLocation());
1919 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001920 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001921 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001922 // We've transferred the ownership to MsgExprs. Null out the argument in
1923 // the original expression, since we will delete it below.
1924 Exp->setArg(i, 0);
1925 }
Steve Naroffab972d32007-11-04 22:37:50 +00001926 // Generate the funky cast.
1927 CastExpr *cast;
1928 llvm::SmallVector<QualType, 8> ArgTypes;
1929 QualType returnType;
1930
1931 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001932 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1933 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1934 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001935 ArgTypes.push_back(Context->getObjCIdType());
1936 ArgTypes.push_back(Context->getObjCSelType());
1937 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00001938 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001939 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001940 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1941 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001942 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001943 ArgTypes.push_back(t);
1944 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001945 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1946 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00001947 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001948 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00001949 }
1950 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001951 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001952
1953 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001954 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1955 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001956
1957 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1958 // If we don't do this cast, we get the following bizarre warning/note:
1959 // xx.m:13: warning: function called through a non-compatible type
1960 // xx.m:13: note: if this code is reached, the program will abort
1961 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1962 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001963
Steve Naroffab972d32007-11-04 22:37:50 +00001964 // Now do the "normal" pointer to function cast.
1965 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001966 &ArgTypes[0], ArgTypes.size(),
1967 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001968 castType = Context->getPointerType(castType);
1969 cast = new CastExpr(castType, cast, SourceLocation());
1970
1971 // Don't forget the parens to enforce the proper binding.
1972 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1973
1974 const FunctionType *FT = msgSendType->getAsFunctionType();
1975 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1976 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001977 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001978 if (MsgSendStretFlavor) {
1979 // We have the method which returns a struct/union. Must also generate
1980 // call to objc_msgSend_stret and hang both varieties on a conditional
1981 // expression which dictate which one to envoke depending on size of
1982 // method's return type.
1983
1984 // Create a reference to the objc_msgSend_stret() declaration.
1985 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1986 SourceLocation());
1987 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1988 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1989 SourceLocation());
1990 // Now do the "normal" pointer to function cast.
1991 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001992 &ArgTypes[0], ArgTypes.size(),
1993 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001994 castType = Context->getPointerType(castType);
1995 cast = new CastExpr(castType, cast, SourceLocation());
1996
1997 // Don't forget the parens to enforce the proper binding.
1998 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1999
2000 FT = msgSendType->getAsFunctionType();
2001 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2002 FT->getResultType(), SourceLocation());
2003
2004 // Build sizeof(returnType)
2005 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2006 returnType, Context->getSizeType(),
2007 SourceLocation(), SourceLocation());
2008 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2009 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2010 // For X86 it is more complicated and some kind of target specific routine
2011 // is needed to decide what to do.
2012 unsigned IntSize = static_cast<unsigned>(
2013 Context->getTypeSize(Context->IntTy, SourceLocation()));
2014
2015 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2016 Context->IntTy,
2017 SourceLocation());
2018 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2019 BinaryOperator::LE,
2020 Context->IntTy,
2021 SourceLocation());
2022 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2023 ConditionalOperator *CondExpr =
2024 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002025 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002026 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002027 return ReplacingStmt;
2028}
2029
2030Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2031 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002032 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002033 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002034
Chris Lattnere64b7772007-10-24 16:57:36 +00002035 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002036 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002037}
2038
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002039/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2040/// call to objc_getProtocol("proto-name").
2041Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2042 if (!GetProtocolFunctionDecl)
2043 SynthGetProtocolFunctionDecl();
2044 // Create a call to objc_getProtocol("ProtocolName").
2045 llvm::SmallVector<Expr*, 8> ProtoExprs;
2046 QualType argType = Context->getPointerType(Context->CharTy);
2047 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2048 strlen(Exp->getProtocol()->getName()),
2049 false, argType, SourceLocation(),
2050 SourceLocation()));
2051 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2052 &ProtoExprs[0],
2053 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002054 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002055 delete Exp;
2056 return ProtoExp;
2057
2058}
2059
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002060/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002061/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002062void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002063 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002064 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2065 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002066 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002067 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002068 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002069 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00002070 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00002071 SourceLocation LocStart = CDecl->getLocStart();
2072 SourceLocation LocEnd = CDecl->getLocEnd();
2073
2074 const char *startBuf = SM->getCharacterData(LocStart);
2075 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002076 // If no ivars and no root or if its root, directly or indirectly,
2077 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002078 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002079 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2080 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2081 Result.c_str(), Result.size());
2082 return;
2083 }
2084
2085 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002086 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002087 Result += "\nstruct ";
2088 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00002089
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002090 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002091 const char *cursor = strchr(startBuf, '{');
2092 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002093 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002094
2095 // rewrite the original header *without* disturbing the '{'
2096 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
2097 Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002098 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002099 Result = "\n struct ";
2100 Result += RCDecl->getName();
Steve Narofff69cc5d2008-01-30 19:17:43 +00002101 // Note: We don't name the field decl. This simplifies the "codegen" for
2102 // accessing a superclasses instance variables (and is similar to what gcc
2103 // does internally). The unnamed struct field feature is enabled with
2104 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2105 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002106 Result += ";\n";
2107
2108 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002109 SourceLocation OnePastCurly =
2110 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2111 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002112 }
2113 cursor++; // past '{'
2114
2115 // Now comment out any visibility specifiers.
2116 while (cursor < endBuf) {
2117 if (*cursor == '@') {
2118 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002119 // Skip whitespace.
2120 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2121 /*scan*/;
2122
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002123 // FIXME: presence of @public, etc. inside comment results in
2124 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002125 if (!strncmp(cursor, "public", strlen("public")) ||
2126 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002127 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002128 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002129 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002130 // FIXME: If there are cases where '<' is used in ivar declaration part
2131 // of user code, then scan the ivar list and use needToScanForQualifiers
2132 // for type checking.
2133 else if (*cursor == '<') {
2134 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002135 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002136 cursor = strchr(cursor, '>');
2137 cursor++;
2138 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002139 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002140 }
Steve Narofffea763e82007-11-14 19:25:57 +00002141 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002142 }
Steve Narofffea763e82007-11-14 19:25:57 +00002143 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002144 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002145 } else { // we don't have any instance variables - insert super struct.
2146 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2147 Result += " {\n struct ";
2148 Result += RCDecl->getName();
Steve Narofff69cc5d2008-01-30 19:17:43 +00002149 // Note: We don't name the field decl. This simplifies the "codegen" for
2150 // accessing a superclasses instance variables (and is similar to what gcc
2151 // does internally). The unnamed struct field feature is enabled with
2152 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2153 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002154 Result += ";\n};\n";
2155 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2156 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002157 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002158 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002159 if (!ObjCSynthesizedStructs.insert(CDecl))
2160 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002161}
2162
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002163// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002164/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002165void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002166 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002167 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002168 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002169 const char *ClassName,
2170 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002171 if (MethodBegin == MethodEnd) return;
2172
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002173 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002174 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002175 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002176 SEL _cmd;
2177 char *method_types;
2178 void *_imp;
2179 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002180 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002181 Result += "\nstruct _objc_method {\n";
2182 Result += "\tSEL _cmd;\n";
2183 Result += "\tchar *method_types;\n";
2184 Result += "\tvoid *_imp;\n";
2185 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002186
2187 /* struct _objc_method_list {
2188 struct _objc_method_list *next_method;
2189 int method_count;
2190 struct _objc_method method_list[];
2191 }
2192 */
2193 Result += "\nstruct _objc_method_list {\n";
2194 Result += "\tstruct _objc_method_list *next_method;\n";
2195 Result += "\tint method_count;\n";
2196 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002197 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002198 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002199
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002200 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002201 Result += "\nstatic struct _objc_method_list _OBJC_";
2202 Result += prefix;
2203 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2204 Result += "_METHODS_";
2205 Result += ClassName;
2206 Result += " __attribute__ ((section (\"__OBJC, __";
2207 Result += IsInstanceMethod ? "inst" : "cls";
2208 Result += "_meth\")))= ";
2209 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002210
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002211 Result += "\t,{{(SEL)\"";
2212 Result += (*MethodBegin)->getSelector().getName().c_str();
2213 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002214 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002215 Result += "\", \"";
2216 Result += MethodTypeString;
2217 Result += "\", ";
2218 Result += MethodInternalNames[*MethodBegin];
2219 Result += "}\n";
2220 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2221 Result += "\t ,{(SEL)\"";
2222 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002223 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002224 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002225 Result += "\", \"";
2226 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002227 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002228 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002229 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002230 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002231 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002232}
2233
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002234/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2235void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002236 int NumProtocols,
2237 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002238 const char *ClassName,
2239 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002240 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002241 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002242 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002243 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002244 // Output struct protocol_methods holder of method selector and type.
2245 if (!objc_protocol_methods &&
2246 (PDecl->getNumInstanceMethods() > 0
2247 || PDecl->getNumClassMethods() > 0)) {
2248 /* struct protocol_methods {
2249 SEL _cmd;
2250 char *method_types;
2251 }
2252 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002253 Result += "\nstruct protocol_methods {\n";
2254 Result += "\tSEL _cmd;\n";
2255 Result += "\tchar *method_types;\n";
2256 Result += "};\n";
2257
2258 /* struct _objc_protocol_method_list {
2259 int protocol_method_count;
2260 struct protocol_methods protocols[];
2261 }
2262 */
2263 Result += "\nstruct _objc_protocol_method_list {\n";
2264 Result += "\tint protocol_method_count;\n";
2265 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002266 objc_protocol_methods = true;
2267 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002268
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002269 int NumMethods = PDecl->getNumInstanceMethods();
2270 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002271 Result += "\nstatic struct _objc_protocol_method_list "
2272 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2273 Result += PDecl->getName();
2274 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2275 "{\n\t" + utostr(NumMethods) + "\n";
2276
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002277 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002278 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002279 E = PDecl->instmeth_end(); I != E; ++I) {
2280 if (I == PDecl->instmeth_begin())
2281 Result += "\t ,{{(SEL)\"";
2282 else
2283 Result += "\t ,{(SEL)\"";
2284 Result += (*I)->getSelector().getName().c_str();
2285 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002286 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002287 Result += "\", \"";
2288 Result += MethodTypeString;
2289 Result += "\"}\n";
2290 }
2291 Result += "\t }\n};\n";
2292 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002293
2294 // Output class methods declared in this protocol.
2295 NumMethods = PDecl->getNumClassMethods();
2296 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002297 Result += "\nstatic struct _objc_protocol_method_list "
2298 "_OBJC_PROTOCOL_CLASS_METHODS_";
2299 Result += PDecl->getName();
2300 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2301 "{\n\t";
2302 Result += utostr(NumMethods);
2303 Result += "\n";
2304
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002305 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002306 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002307 E = PDecl->classmeth_end(); I != E; ++I) {
2308 if (I == PDecl->classmeth_begin())
2309 Result += "\t ,{{(SEL)\"";
2310 else
2311 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002312 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002313 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002314 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002315 Result += "\", \"";
2316 Result += MethodTypeString;
2317 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002318 }
2319 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002320 }
2321 // Output:
2322 /* struct _objc_protocol {
2323 // Objective-C 1.0 extensions
2324 struct _objc_protocol_extension *isa;
2325 char *protocol_name;
2326 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002327 struct _objc_protocol_method_list *instance_methods;
2328 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002329 };
2330 */
2331 static bool objc_protocol = false;
2332 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002333 Result += "\nstruct _objc_protocol {\n";
2334 Result += "\tstruct _objc_protocol_extension *isa;\n";
2335 Result += "\tchar *protocol_name;\n";
2336 Result += "\tstruct _objc_protocol **protocol_list;\n";
2337 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2338 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2339 Result += "};\n";
2340
2341 /* struct _objc_protocol_list {
2342 struct _objc_protocol_list *next;
2343 int protocol_count;
2344 struct _objc_protocol *class_protocols[];
2345 }
2346 */
2347 Result += "\nstruct _objc_protocol_list {\n";
2348 Result += "\tstruct _objc_protocol_list *next;\n";
2349 Result += "\tint protocol_count;\n";
2350 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2351 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002352 objc_protocol = true;
2353 }
2354
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002355 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2356 Result += PDecl->getName();
2357 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2358 "{\n\t0, \"";
2359 Result += PDecl->getName();
2360 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002361 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002362 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2363 Result += PDecl->getName();
2364 Result += ", ";
2365 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002366 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002367 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002368 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002369 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2370 Result += PDecl->getName();
2371 Result += "\n";
2372 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002373 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002374 Result += "0\n";
2375 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002376 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002377 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002378 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2379 Result += prefix;
2380 Result += "_PROTOCOLS_";
2381 Result += ClassName;
2382 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2383 "{\n\t0, ";
2384 Result += utostr(NumProtocols);
2385 Result += "\n";
2386
2387 Result += "\t,{&_OBJC_PROTOCOL_";
2388 Result += Protocols[0]->getName();
2389 Result += " \n";
2390
2391 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002392 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002393 Result += "\t ,&_OBJC_PROTOCOL_";
2394 Result += PDecl->getName();
2395 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002396 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002397 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002398 }
2399}
2400
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002401/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002402/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002403void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002404 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002405 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002406 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002407 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002408 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2409 CDecl = CDecl->getNextClassCategory())
2410 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2411 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002412
Chris Lattnereb44eee2007-12-23 01:40:15 +00002413 std::string FullCategoryName = ClassDecl->getName();
2414 FullCategoryName += '_';
2415 FullCategoryName += IDecl->getName();
2416
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002417 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002418 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002419 true, "CATEGORY_", FullCategoryName.c_str(),
2420 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002421
2422 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002423 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002424 false, "CATEGORY_", FullCategoryName.c_str(),
2425 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002426
2427 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002428 // Null CDecl is case of a category implementation with no category interface
2429 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002430 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002431 CDecl->getNumReferencedProtocols(),
2432 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002433 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002434
2435 /* struct _objc_category {
2436 char *category_name;
2437 char *class_name;
2438 struct _objc_method_list *instance_methods;
2439 struct _objc_method_list *class_methods;
2440 struct _objc_protocol_list *protocols;
2441 // Objective-C 1.0 extensions
2442 uint32_t size; // sizeof (struct _objc_category)
2443 struct _objc_property_list *instance_properties; // category's own
2444 // @property decl.
2445 };
2446 */
2447
2448 static bool objc_category = false;
2449 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002450 Result += "\nstruct _objc_category {\n";
2451 Result += "\tchar *category_name;\n";
2452 Result += "\tchar *class_name;\n";
2453 Result += "\tstruct _objc_method_list *instance_methods;\n";
2454 Result += "\tstruct _objc_method_list *class_methods;\n";
2455 Result += "\tstruct _objc_protocol_list *protocols;\n";
2456 Result += "\tunsigned int size;\n";
2457 Result += "\tstruct _objc_property_list *instance_properties;\n";
2458 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002459 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002460 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002461 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2462 Result += FullCategoryName;
2463 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2464 Result += IDecl->getName();
2465 Result += "\"\n\t, \"";
2466 Result += ClassDecl->getName();
2467 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002468
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002469 if (IDecl->getNumInstanceMethods() > 0) {
2470 Result += "\t, (struct _objc_method_list *)"
2471 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2472 Result += FullCategoryName;
2473 Result += "\n";
2474 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002475 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002476 Result += "\t, 0\n";
2477 if (IDecl->getNumClassMethods() > 0) {
2478 Result += "\t, (struct _objc_method_list *)"
2479 "&_OBJC_CATEGORY_CLASS_METHODS_";
2480 Result += FullCategoryName;
2481 Result += "\n";
2482 }
2483 else
2484 Result += "\t, 0\n";
2485
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002486 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002487 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2488 Result += FullCategoryName;
2489 Result += "\n";
2490 }
2491 else
2492 Result += "\t, 0\n";
2493 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002494}
2495
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002496/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2497/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002498void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2499 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002500 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002501 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002502 Result += IDecl->getName();
2503 Result += ", ";
2504 Result += ivar->getName();
2505 Result += ")";
2506}
2507
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002508//===----------------------------------------------------------------------===//
2509// Meta Data Emission
2510//===----------------------------------------------------------------------===//
2511
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002512void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002513 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002514 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002515
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002516 // Explictly declared @interface's are already synthesized.
2517 if (CDecl->ImplicitInterfaceDecl()) {
2518 // FIXME: Implementation of a class with no @interface (legacy) doese not
2519 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002520 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002521 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002522
Chris Lattnerbe6df082007-12-12 07:56:42 +00002523 // Build _objc_ivar_list metadata for classes ivars if needed
2524 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2525 ? IDecl->getImplDeclNumIvars()
2526 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002527 if (NumIvars > 0) {
2528 static bool objc_ivar = false;
2529 if (!objc_ivar) {
2530 /* struct _objc_ivar {
2531 char *ivar_name;
2532 char *ivar_type;
2533 int ivar_offset;
2534 };
2535 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002536 Result += "\nstruct _objc_ivar {\n";
2537 Result += "\tchar *ivar_name;\n";
2538 Result += "\tchar *ivar_type;\n";
2539 Result += "\tint ivar_offset;\n";
2540 Result += "};\n";
2541
2542 /* struct _objc_ivar_list {
2543 int ivar_count;
2544 struct _objc_ivar ivar_list[];
2545 };
2546 */
2547 Result += "\nstruct _objc_ivar_list {\n";
2548 Result += "\tint ivar_count;\n";
2549 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002550 objc_ivar = true;
2551 }
2552
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002553 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2554 Result += IDecl->getName();
2555 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2556 "{\n\t";
2557 Result += utostr(NumIvars);
2558 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002559
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002560 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002561 if (IDecl->getImplDeclNumIvars() > 0) {
2562 IVI = IDecl->ivar_begin();
2563 IVE = IDecl->ivar_end();
2564 } else {
2565 IVI = CDecl->ivar_begin();
2566 IVE = CDecl->ivar_end();
2567 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002568 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002569 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002570 Result += "\", \"";
2571 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002572 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2573 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002574 Result += StrEncoding;
2575 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002576 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002577 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002578 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002579 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002580 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002581 Result += "\", \"";
2582 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002583 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2584 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002585 Result += StrEncoding;
2586 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002587 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002588 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002589 }
2590
2591 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002592 }
2593
2594 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002595 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002596 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002597
2598 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002599 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002600 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002601
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002602 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002603 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002604 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002605 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002606
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002607
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002608 // Declaration of class/meta-class metadata
2609 /* struct _objc_class {
2610 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002611 const char *super_class_name;
2612 char *name;
2613 long version;
2614 long info;
2615 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002616 struct _objc_ivar_list *ivars;
2617 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002618 struct objc_cache *cache;
2619 struct objc_protocol_list *protocols;
2620 const char *ivar_layout;
2621 struct _objc_class_ext *ext;
2622 };
2623 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002624 static bool objc_class = false;
2625 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002626 Result += "\nstruct _objc_class {\n";
2627 Result += "\tstruct _objc_class *isa;\n";
2628 Result += "\tconst char *super_class_name;\n";
2629 Result += "\tchar *name;\n";
2630 Result += "\tlong version;\n";
2631 Result += "\tlong info;\n";
2632 Result += "\tlong instance_size;\n";
2633 Result += "\tstruct _objc_ivar_list *ivars;\n";
2634 Result += "\tstruct _objc_method_list *methods;\n";
2635 Result += "\tstruct objc_cache *cache;\n";
2636 Result += "\tstruct _objc_protocol_list *protocols;\n";
2637 Result += "\tconst char *ivar_layout;\n";
2638 Result += "\tstruct _objc_class_ext *ext;\n";
2639 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002640 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002641 }
2642
2643 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002644 ObjCInterfaceDecl *RootClass = 0;
2645 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002646 while (SuperClass) {
2647 RootClass = SuperClass;
2648 SuperClass = SuperClass->getSuperClass();
2649 }
2650 SuperClass = CDecl->getSuperClass();
2651
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002652 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2653 Result += CDecl->getName();
2654 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2655 "{\n\t(struct _objc_class *)\"";
2656 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2657 Result += "\"";
2658
2659 if (SuperClass) {
2660 Result += ", \"";
2661 Result += SuperClass->getName();
2662 Result += "\", \"";
2663 Result += CDecl->getName();
2664 Result += "\"";
2665 }
2666 else {
2667 Result += ", 0, \"";
2668 Result += CDecl->getName();
2669 Result += "\"";
2670 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002671 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002672 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002673 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002674 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002675 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002676 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002677 Result += "\n";
2678 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002679 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002680 Result += ", 0\n";
2681 if (CDecl->getNumIntfRefProtocols() > 0) {
2682 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2683 Result += CDecl->getName();
2684 Result += ",0,0\n";
2685 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002686 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002687 Result += "\t,0,0,0,0\n";
2688 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002689
2690 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002691 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2692 Result += CDecl->getName();
2693 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2694 "{\n\t&_OBJC_METACLASS_";
2695 Result += CDecl->getName();
2696 if (SuperClass) {
2697 Result += ", \"";
2698 Result += SuperClass->getName();
2699 Result += "\", \"";
2700 Result += CDecl->getName();
2701 Result += "\"";
2702 }
2703 else {
2704 Result += ", 0, \"";
2705 Result += CDecl->getName();
2706 Result += "\"";
2707 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002708 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002709 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002710 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002711 Result += ",0";
2712 else {
2713 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002714 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002715 Result += CDecl->getName();
2716 Result += ")";
2717 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002718 if (NumIvars > 0) {
2719 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2720 Result += CDecl->getName();
2721 Result += "\n\t";
2722 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002723 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002724 Result += ",0";
2725 if (IDecl->getNumInstanceMethods() > 0) {
2726 Result += ", &_OBJC_INSTANCE_METHODS_";
2727 Result += CDecl->getName();
2728 Result += ", 0\n\t";
2729 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002730 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002731 Result += ",0,0";
2732 if (CDecl->getNumIntfRefProtocols() > 0) {
2733 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2734 Result += CDecl->getName();
2735 Result += ", 0,0\n";
2736 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002737 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002738 Result += ",0,0,0\n";
2739 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002740}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002741
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002742/// RewriteImplementations - This routine rewrites all method implementations
2743/// and emits meta-data.
2744
2745void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002746 int ClsDefCount = ClassImplementation.size();
2747 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002748
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002749 if (ClsDefCount == 0 && CatDefCount == 0)
2750 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002751 // Rewrite implemented methods
2752 for (int i = 0; i < ClsDefCount; i++)
2753 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002754
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002755 for (int i = 0; i < CatDefCount; i++)
2756 RewriteImplementationDecl(CategoryImplementation[i]);
2757
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002758 // This is needed for use of offsetof
2759 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002760
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002761 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002762 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002763 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002764
2765 // For each implemented category, write out all its meta data.
2766 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002767 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002768
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002769 // Write objc_symtab metadata
2770 /*
2771 struct _objc_symtab
2772 {
2773 long sel_ref_cnt;
2774 SEL *refs;
2775 short cls_def_cnt;
2776 short cat_def_cnt;
2777 void *defs[cls_def_cnt + cat_def_cnt];
2778 };
2779 */
2780
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002781 Result += "\nstruct _objc_symtab {\n";
2782 Result += "\tlong sel_ref_cnt;\n";
2783 Result += "\tSEL *refs;\n";
2784 Result += "\tshort cls_def_cnt;\n";
2785 Result += "\tshort cat_def_cnt;\n";
2786 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2787 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002788
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002789 Result += "static struct _objc_symtab "
2790 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2791 Result += "\t0, 0, " + utostr(ClsDefCount)
2792 + ", " + utostr(CatDefCount) + "\n";
2793 for (int i = 0; i < ClsDefCount; i++) {
2794 Result += "\t,&_OBJC_CLASS_";
2795 Result += ClassImplementation[i]->getName();
2796 Result += "\n";
2797 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002798
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002799 for (int i = 0; i < CatDefCount; i++) {
2800 Result += "\t,&_OBJC_CATEGORY_";
2801 Result += CategoryImplementation[i]->getClassInterface()->getName();
2802 Result += "_";
2803 Result += CategoryImplementation[i]->getName();
2804 Result += "\n";
2805 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002806
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002807 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002808
2809 // Write objc_module metadata
2810
2811 /*
2812 struct _objc_module {
2813 long version;
2814 long size;
2815 const char *name;
2816 struct _objc_symtab *symtab;
2817 }
2818 */
2819
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002820 Result += "\nstruct _objc_module {\n";
2821 Result += "\tlong version;\n";
2822 Result += "\tlong size;\n";
2823 Result += "\tconst char *name;\n";
2824 Result += "\tstruct _objc_symtab *symtab;\n";
2825 Result += "};\n\n";
2826 Result += "static struct _objc_module "
2827 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002828 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2829 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002830 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002831
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002832}
Chris Lattner311ff022007-10-16 22:36:42 +00002833