blob: c1243b91eddadce6751ce8c292f94253d40276cc [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 Naroff874e2322007-11-15 10:28:18 +000025#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000026using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000027using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000028
Chris Lattner77cd2a02007-10-11 00:43:27 +000029namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000030 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000031 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000032 Diagnostic &Diags;
Chris Lattner01c57482007-10-17 22:35:30 +000033 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000035 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000036 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000037 SourceLocation LastIncLoc;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000038 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
40 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
41 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
42 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000043 llvm::SmallVector<Stmt *, 32> Stmts;
44 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000045
46 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000047 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000048 FunctionDecl *MsgSendStretFunctionDecl;
49 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000050 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000051 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000052 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000053 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000054 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000055 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000056
Steve Naroffbeaf2992007-11-03 11:27:19 +000057 // ObjC string constant support.
58 FileVarDecl *ConstantStringClassReference;
59 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000060
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000061 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000062 int BcLabelCount;
63
Steve Naroff874e2322007-11-15 10:28:18 +000064 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000065 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000066 RecordDecl *SuperStructDecl;
67
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000068 // Needed for header files being rewritten
69 bool IsHeader;
70
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000071 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000072 public:
Ted Kremenek95041a22007-12-19 22:51:13 +000073 void Initialize(ASTContext &context) {
Chris Lattner01c57482007-10-17 22:35:30 +000074 Context = &context;
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000075 SM = &Context->getSourceManager();
Steve Naroffebf2b562007-10-23 23:50:29 +000076 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000077 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000078 MsgSendStretFunctionDecl = 0;
79 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000080 MsgSendFpretFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000081 GetClassFunctionDecl = 0;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000082 GetMetaClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000083 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000084 CFStringFunctionDecl = 0;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000085 GetProtocolFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000086 ConstantStringClassReference = 0;
87 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000088 CurMethodDecl = 0;
89 SuperStructDecl = 0;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000090 BcLabelCount = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000091
Chris Lattner26de4652007-12-02 01:13:47 +000092 // Get the ID and start/end of the main file.
Ted Kremenek95041a22007-12-19 22:51:13 +000093 MainFileID = SM->getMainFileID();
Chris Lattner26de4652007-12-02 01:13:47 +000094 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
95 MainFileStart = MainBuf->getBufferStart();
96 MainFileEnd = MainBuf->getBufferEnd();
97
98
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000099 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffe3abbf52007-11-05 14:55:35 +0000100 // declaring objc_selector outside the parameter list removes a silly
101 // scope related warning...
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000102 const char *s = "#pragma once\n"
103 "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000104 "#ifndef OBJC_SUPER\n"
105 "struct objc_super { struct objc_object *o; "
106 "struct objc_object *superClass; };\n"
107 "#define OBJC_SUPER\n"
108 "#endif\n"
109 "#ifndef _REWRITER_typedef_Protocol\n"
110 "typedef struct objc_object Protocol;\n"
111 "#define _REWRITER_typedef_Protocol\n"
112 "#endif\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +0000113 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +0000114 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +0000115 "extern struct objc_object *objc_msgSendSuper"
116 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000117 "extern struct objc_object *objc_msgSend_stret"
118 "(struct objc_object *, struct objc_selector *, ...);\n"
119 "extern struct objc_object *objc_msgSendSuper_stret"
120 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000121 "extern struct objc_object *objc_msgSend_fpret"
122 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +0000123 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +0000124 "(const char *);\n"
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000125 "extern struct objc_object *objc_getMetaClass"
126 "(const char *);\n"
Steve Naroff21867b12007-11-07 18:43:40 +0000127 "extern void objc_exception_throw(struct objc_object *);\n"
128 "extern void objc_exception_try_enter(void *);\n"
129 "extern void objc_exception_try_exit(void *);\n"
130 "extern struct objc_object *objc_exception_extract(void *);\n"
131 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +0000132 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000133 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000134 "#include <objc/objc.h>\n"
Fariborz Jahanian88007422008-01-10 23:04:06 +0000135 "#ifndef __FASTENUMERATIONSTATE\n"
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000136 "struct __objcFastEnumerationState {\n\t"
137 "unsigned long state;\n\t"
138 "id *itemsPtr;\n\t"
139 "unsigned long *mutationsPtr;\n\t"
Fariborz Jahanian88007422008-01-10 23:04:06 +0000140 "unsigned long extra[5];\n};\n"
141 "#define __FASTENUMERATIONSTATE\n"
142 "#endif\n";
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000143 if (IsHeader) {
144 // insert the whole string when rewriting a header file
145 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
146 s, strlen(s));
147 }
148 else {
149 // Not rewriting header, exclude the #pragma once pragma
150 const char *p = s + strlen("#pragma once\n");
151 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
152 p, strlen(p));
153 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000154 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000155
Chris Lattnerf04da132007-10-24 17:06:59 +0000156 // Top Level Driver code.
157 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000158 void HandleDeclInMainFile(Decl *D);
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000159 RewriteTest(bool isHeader, Diagnostic &D) : Diags(D) {IsHeader = isHeader;}
Chris Lattnerf04da132007-10-24 17:06:59 +0000160 ~RewriteTest();
161
162 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000163 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000164 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000165 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000166 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
167 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000168 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000169 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
170 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
171 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
172 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
173 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
174 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000175 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000176 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000177 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000178 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000179 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000180
Chris Lattnerf04da132007-10-24 17:06:59 +0000181 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000182 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000183 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000184 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000185 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000186 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000187 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000188 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000189 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
190 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
191 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
192 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000193 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000194 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
195 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000196 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000197 Stmt *RewriteBreakStmt(BreakStmt *S);
198 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000199 void SynthCountByEnumWithState(std::string &buf);
200
Steve Naroff09b266e2007-10-30 23:14:51 +0000201 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000202 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000203 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000204 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000205 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000206 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000207 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000208 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000209 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000210 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000211
Chris Lattnerf04da132007-10-24 17:06:59 +0000212 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000213 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000214 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000215
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000216 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000217 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000218
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000219 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
220 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000221 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000222 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000223 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000224 const char *ClassName,
225 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000226
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000227 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000228 int NumProtocols,
229 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000230 const char *ClassName,
231 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000232 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000233 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000234 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
235 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000236 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000237 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000238 };
239}
240
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000241static bool IsHeaderFile(const std::string &Filename) {
242 std::string::size_type DotPos = Filename.rfind('.');
243
244 if (DotPos == std::string::npos) {
245 // no file extension
246 return false;
247 }
248
249 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
250 // C header: .h
251 // C++ header: .hh or .H;
252 return Ext == "h" || Ext == "hh" || Ext == "H";
253}
254
255ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
256 Diagnostic &Diags) {
257 return new RewriteTest(IsHeaderFile(InFile), Diags);
Chris Lattnere365c502007-11-30 22:25:36 +0000258}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000259
Chris Lattnerf04da132007-10-24 17:06:59 +0000260//===----------------------------------------------------------------------===//
261// Top Level Driver Code
262//===----------------------------------------------------------------------===//
263
Chris Lattner8a12c272007-10-11 18:38:32 +0000264void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000265 // Two cases: either the decl could be in the main file, or it could be in a
266 // #included file. If the former, rewrite it now. If the later, check to see
267 // if we rewrote the #include/#import.
268 SourceLocation Loc = D->getLocation();
269 Loc = SM->getLogicalLoc(Loc);
270
271 // If this is for a builtin, ignore it.
272 if (Loc.isInvalid()) return;
273
Steve Naroffebf2b562007-10-23 23:50:29 +0000274 // Look for built-in declarations that we need to refer during the rewrite.
275 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000276 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000277 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
278 // declared in <Foundation/NSString.h>
279 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
280 ConstantStringClassReference = FVD;
281 return;
282 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000283 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000284 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000285 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000286 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000287 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000288 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 } else if (ObjCForwardProtocolDecl *FP =
290 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000291 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000292 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000293 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000294 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
295 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000296}
297
Chris Lattnerf04da132007-10-24 17:06:59 +0000298/// HandleDeclInMainFile - This is called for each top-level decl defined in the
299/// main file of the input.
300void RewriteTest::HandleDeclInMainFile(Decl *D) {
301 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
302 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000303 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000304
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000306 if (Stmt *Body = MD->getBody()) {
307 //Body->dump();
308 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000309 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000310 CurMethodDecl = 0;
311 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000312 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000313 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000314 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000315 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000316 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000317 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000318 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000319 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000320 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000321 if (VD->getInit())
322 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
323 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000324 // Nothing yet.
325}
326
327RewriteTest::~RewriteTest() {
328 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000329
330 // Rewrite tabs if we care.
331 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000332
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000333 RewriteInclude();
334
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000335 // Rewrite Objective-c meta data*
336 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000337 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000338
Chris Lattnerf04da132007-10-24 17:06:59 +0000339 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
340 // we are done.
341 if (const RewriteBuffer *RewriteBuf =
342 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000343 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000344 std::string S(RewriteBuf->begin(), RewriteBuf->end());
345 printf("%s\n", S.c_str());
346 } else {
347 printf("No changes\n");
348 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000349 // Emit metadata.
350 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000351}
352
Chris Lattnerf04da132007-10-24 17:06:59 +0000353//===----------------------------------------------------------------------===//
354// Syntactic (non-AST) Rewriting Code
355//===----------------------------------------------------------------------===//
356
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000357void RewriteTest::RewriteInclude() {
358 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
359 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
360 const char *MainBufStart = MainBuf.first;
361 const char *MainBufEnd = MainBuf.second;
362 size_t ImportLen = strlen("import");
363 size_t IncludeLen = strlen("include");
364
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000365 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000366 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
367 if (*BufPtr == '#') {
368 if (++BufPtr == MainBufEnd)
369 return;
370 while (*BufPtr == ' ' || *BufPtr == '\t')
371 if (++BufPtr == MainBufEnd)
372 return;
373 if (!strncmp(BufPtr, "import", ImportLen)) {
374 // replace import with include
375 SourceLocation ImportLoc =
376 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
377 Rewrite.ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
378 BufPtr += ImportLen;
379 }
380 }
381 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000382}
383
Chris Lattnerf04da132007-10-24 17:06:59 +0000384void RewriteTest::RewriteTabs() {
385 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
386 const char *MainBufStart = MainBuf.first;
387 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000388
Chris Lattnerf04da132007-10-24 17:06:59 +0000389 // Loop over the whole file, looking for tabs.
390 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
391 if (*BufPtr != '\t')
392 continue;
393
394 // Okay, we found a tab. This tab will turn into at least one character,
395 // but it depends on which 'virtual column' it is in. Compute that now.
396 unsigned VCol = 0;
397 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
398 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
399 ++VCol;
400
401 // Okay, now that we know the virtual column, we know how many spaces to
402 // insert. We assume 8-character tab-stops.
403 unsigned Spaces = 8-(VCol & 7);
404
405 // Get the location of the tab.
406 SourceLocation TabLoc =
407 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
408
409 // Rewrite the single tab character into a sequence of spaces.
410 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
411 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000412}
413
414
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000415void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000416 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000417 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000418
419 // Get the start location and compute the semi location.
420 SourceLocation startLoc = ClassDecl->getLocation();
421 const char *startBuf = SM->getCharacterData(startLoc);
422 const char *semiPtr = strchr(startBuf, ';');
423
424 // Translate to typedef's that forward reference structs with the same name
425 // as the class. As a convenience, we include the original declaration
426 // as a comment.
427 std::string typedefString;
428 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000429 typedefString.append(startBuf, semiPtr-startBuf+1);
430 typedefString += "\n";
431 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000432 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000433 typedefString += "#ifndef _REWRITER_typedef_";
434 typedefString += ForwardDecl->getName();
435 typedefString += "\n";
436 typedefString += "#define _REWRITER_typedef_";
437 typedefString += ForwardDecl->getName();
438 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000439 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000440 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000441 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000442 }
443
444 // Replace the @class with typedefs corresponding to the classes.
445 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
446 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000447}
448
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000449void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000450 SourceLocation LocStart = Method->getLocStart();
451 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000452
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000453 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
454 Rewrite.InsertText(LocStart, "/* ", 3);
455 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
456 } else {
457 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000458 }
459}
460
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000461void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000462{
463 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000464 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000465 SourceLocation Loc = Property->getLocation();
466
467 Rewrite.ReplaceText(Loc, 0, "// ", 3);
468
469 // FIXME: handle properties that are declared across multiple lines.
470 }
471}
472
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000473void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000474 SourceLocation LocStart = CatDecl->getLocStart();
475
476 // FIXME: handle category headers that are declared across multiple lines.
477 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
478
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000479 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000480 E = CatDecl->instmeth_end(); I != E; ++I)
481 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000482 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000483 E = CatDecl->classmeth_end(); I != E; ++I)
484 RewriteMethodDeclaration(*I);
485
Steve Naroff423cb562007-10-30 13:30:57 +0000486 // Lastly, comment out the @end.
487 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
488}
489
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000490void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000491 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000492
Steve Naroff752d6ef2007-10-30 16:42:30 +0000493 SourceLocation LocStart = PDecl->getLocStart();
494
495 // FIXME: handle protocol headers that are declared across multiple lines.
496 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
497
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000498 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000499 E = PDecl->instmeth_end(); I != E; ++I)
500 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000501 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000502 E = PDecl->classmeth_end(); I != E; ++I)
503 RewriteMethodDeclaration(*I);
504
Steve Naroff752d6ef2007-10-30 16:42:30 +0000505 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000506 SourceLocation LocEnd = PDecl->getAtEndLoc();
507 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000508
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000509 // Must comment out @optional/@required
510 const char *startBuf = SM->getCharacterData(LocStart);
511 const char *endBuf = SM->getCharacterData(LocEnd);
512 for (const char *p = startBuf; p < endBuf; p++) {
513 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
514 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000515 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000516 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
517 CommentedOptional.c_str(), CommentedOptional.size());
518
519 }
520 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
521 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000522 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000523 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
524 CommentedRequired.c_str(), CommentedRequired.size());
525
526 }
527 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000528}
529
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000530void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000531 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000532 if (LocStart.isInvalid())
533 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000534 // FIXME: handle forward protocol that are declared across multiple lines.
535 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
536}
537
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000538void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000539 std::string &ResultStr) {
540 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000541 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000542 ResultStr += "id";
543 else
544 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000545 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000546
547 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000548 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000549
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000550 if (OMD->isInstance())
551 NameStr += "_I_";
552 else
553 NameStr += "_C_";
554
555 NameStr += OMD->getClassInterface()->getName();
556 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000557
558 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000559 if (ObjCCategoryImplDecl *CID =
560 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000561 NameStr += CID->getName();
562 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000563 }
564 // Append selector names, replacing ':' with '_'
565 const char *selName = OMD->getSelector().getName().c_str();
566 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000567 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000568 else {
569 std::string selString = OMD->getSelector().getName();
570 int len = selString.size();
571 for (int i = 0; i < len; i++)
572 if (selString[i] == ':')
573 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000574 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000575 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000576 // Remember this name for metadata emission
577 MethodInternalNames[OMD] = NameStr;
578 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000579
580 // Rewrite arguments
581 ResultStr += "(";
582
583 // invisible arguments
584 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000585 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000586 selfTy = Context->getPointerType(selfTy);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000587 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000588 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000589 ResultStr += selfTy.getAsString();
590 }
591 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000592 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000593
594 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000595 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000596 ResultStr += " _cmd";
597
598 // Method arguments.
599 for (int i = 0; i < OMD->getNumParams(); i++) {
600 ParmVarDecl *PDecl = OMD->getParamDecl(i);
601 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000602 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000603 ResultStr += "id";
604 else
605 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000606 ResultStr += " ";
607 ResultStr += PDecl->getName();
608 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000609 if (OMD->isVariadic())
610 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000611 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000612
613}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000614void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000615 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
616 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000617
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000618 if (IMD)
619 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
620 else
621 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000622
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000623 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000624 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
625 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000626 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000627 ObjCMethodDecl *OMD = *I;
628 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000629 SourceLocation LocStart = OMD->getLocStart();
630 SourceLocation LocEnd = OMD->getBody()->getLocStart();
631
632 const char *startBuf = SM->getCharacterData(LocStart);
633 const char *endBuf = SM->getCharacterData(LocEnd);
634 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
635 ResultStr.c_str(), ResultStr.size());
636 }
637
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000638 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000639 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
640 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000641 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000642 ObjCMethodDecl *OMD = *I;
643 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000644 SourceLocation LocStart = OMD->getLocStart();
645 SourceLocation LocEnd = OMD->getBody()->getLocStart();
646
647 const char *startBuf = SM->getCharacterData(LocStart);
648 const char *endBuf = SM->getCharacterData(LocEnd);
649 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
650 ResultStr.c_str(), ResultStr.size());
651 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000652 if (IMD)
653 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
654 else
655 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000656}
657
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000658void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000659 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000660 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000661 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000662 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000663 ResultStr += ClassDecl->getName();
664 ResultStr += "\n";
665 ResultStr += "#define _REWRITER_typedef_";
666 ResultStr += ClassDecl->getName();
667 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000668 ResultStr += "typedef struct ";
669 ResultStr += ClassDecl->getName();
670 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000671 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000672 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000673
674 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000675 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000676 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000677 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000678
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000679 RewriteProperties(ClassDecl->getNumPropertyDecl(),
680 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000681 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000682 E = ClassDecl->instmeth_end(); I != E; ++I)
683 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000684 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000685 E = ClassDecl->classmeth_end(); I != E; ++I)
686 RewriteMethodDeclaration(*I);
687
Steve Naroff2feac5e2007-10-30 03:43:13 +0000688 // Lastly, comment out the @end.
689 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000690}
691
Steve Naroff7e3411b2007-11-15 02:58:25 +0000692Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000693 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff7e3411b2007-11-15 02:58:25 +0000694 if (IV->isFreeIvar()) {
695 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
696 IV->getLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +0000697 if (Rewrite.ReplaceStmt(IV, Replacement)) {
698 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000699 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
700 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000701 SourceRange Range = IV->getSourceRange();
702 Diags.Report(Context->getFullLoc(IV->getLocation()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000703 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000704 delete IV;
705 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000706 } else {
707 if (CurMethodDecl) {
708 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000709 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffc2a689b2007-11-15 11:33:00 +0000710 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
711 IdentifierInfo *II = intT->getDecl()->getIdentifier();
712 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
713 II, 0);
714 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
715
716 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
717 // Don't forget the parens to enforce the proper binding.
718 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroff5ca40202007-12-19 14:32:56 +0000719 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
720 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000721 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
722 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000723 SourceRange Range = IV->getBase()->getSourceRange();
724 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000725 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000726 delete IV->getBase();
727 return PE;
728 }
729 }
730 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000731 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000732 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000733}
734
Chris Lattnerf04da132007-10-24 17:06:59 +0000735//===----------------------------------------------------------------------===//
736// Function Body / Expression rewriting
737//===----------------------------------------------------------------------===//
738
Steve Narofff3473a72007-11-09 15:20:18 +0000739Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000740 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
741 isa<DoStmt>(S) || isa<ForStmt>(S))
742 Stmts.push_back(S);
743 else if (isa<ObjCForCollectionStmt>(S)) {
744 Stmts.push_back(S);
745 ObjCBcLabelNo.push_back(++BcLabelCount);
746 }
747
Chris Lattner311ff022007-10-16 22:36:42 +0000748 // Otherwise, just rewrite all children.
749 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
750 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000751 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000752 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000753 if (newStmt)
754 *CI = newStmt;
755 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000756
757 // Handle specific things.
758 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
759 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000760
761 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
762 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000763
764 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
765 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000766
767 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
768 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000769
Steve Naroff934f2762007-10-24 22:48:43 +0000770 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
771 // Before we rewrite it, put the original message expression in a comment.
772 SourceLocation startLoc = MessExpr->getLocStart();
773 SourceLocation endLoc = MessExpr->getLocEnd();
774
775 const char *startBuf = SM->getCharacterData(startLoc);
776 const char *endBuf = SM->getCharacterData(endLoc);
777
778 std::string messString;
779 messString += "// ";
780 messString.append(startBuf, endBuf-startBuf+1);
781 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000782
Steve Naroff934f2762007-10-24 22:48:43 +0000783 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
784 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
785 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000786 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000787 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000788 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000789
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000790 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
791 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000792
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000793 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
794 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000795
796 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
797 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000798
799 if (ObjCForCollectionStmt *StmtForCollection =
800 dyn_cast<ObjCForCollectionStmt>(S))
801 return RewriteObjCForCollectionStmt(StmtForCollection);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000802 if (BreakStmt *StmtBreakStmt =
803 dyn_cast<BreakStmt>(S))
804 return RewriteBreakStmt(StmtBreakStmt);
805 if (ContinueStmt *StmtContinueStmt =
806 dyn_cast<ContinueStmt>(S))
807 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000808
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000809 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
810 isa<DoStmt>(S) || isa<ForStmt>(S)) {
811 assert(!Stmts.empty() && "Statement stack is empty");
812 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
813 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
814 && "Statement stack mismatch");
815 Stmts.pop_back();
816 }
Steve Naroff874e2322007-11-15 10:28:18 +0000817#if 0
818 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
819 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
820 // Get the new text.
821 std::ostringstream Buf;
822 Replacement->printPretty(Buf);
823 const std::string &Str = Buf.str();
824
825 printf("CAST = %s\n", &Str[0]);
826 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
827 delete S;
828 return Replacement;
829 }
830#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000831 // Return this stmt unmodified.
832 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000833}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000834
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000835/// SynthCountByEnumWithState - To print:
836/// ((unsigned int (*)
837/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
838/// (void *)objc_msgSend)((id)l_collection,
839/// sel_registerName(
840/// "countByEnumeratingWithState:objects:count:"),
841/// &enumState,
842/// (id *)items, (unsigned int)16)
843///
844void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
845 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
846 "id *, unsigned int))(void *)objc_msgSend)";
847 buf += "\n\t\t";
848 buf += "((id)l_collection,\n\t\t";
849 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
850 buf += "\n\t\t";
851 buf += "&enumState, "
852 "(id *)items, (unsigned int)16)";
853}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000854
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000855/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
856/// statement to exit to its outer synthesized loop.
857///
858Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
859 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
860 return S;
861 // replace break with goto __break_label
862 std::string buf;
863
864 SourceLocation startLoc = S->getLocStart();
865 buf = "goto __break_label_";
866 buf += utostr(ObjCBcLabelNo.back());
867 Rewrite.ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
868
869 return 0;
870}
871
872/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
873/// statement to continue with its inner synthesized loop.
874///
875Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
876 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
877 return S;
878 // replace continue with goto __continue_label
879 std::string buf;
880
881 SourceLocation startLoc = S->getLocStart();
882 buf = "goto __continue_label_";
883 buf += utostr(ObjCBcLabelNo.back());
884 Rewrite.ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
885
886 return 0;
887}
888
Fariborz Jahaniane84b0402008-01-09 01:25:54 +0000889/// RewriteObjCTryStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000890/// It rewrites:
891/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000892
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000893/// Into:
894/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000895/// type elem;
896/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000897/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000898/// id l_collection = (id)collection;
899/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
900/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000901/// if (limit) {
902/// unsigned long startMutations = *enumState.mutationsPtr;
903/// do {
904/// unsigned long counter = 0;
905/// do {
906/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000907/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000908/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000909/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000910/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000911/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000912/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
913/// objects:items count:16]);
914/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000915/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000916/// }
917/// else
918/// elem = nil;
919/// }
920///
921Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000922 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
923 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
924 "ObjCForCollectionStmt Statement stack mismatch");
925 assert(!ObjCBcLabelNo.empty() &&
926 "ObjCForCollectionStmt - Label No stack empty");
927
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000928 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000929 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000930 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000931 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000932 std::string buf;
933 buf = "\n{\n\t";
934 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
935 // type elem;
936 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000937 elementTypeAsString = ElementType.getAsString();
938 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000939 buf += " ";
940 elementName = DS->getDecl()->getName();
941 buf += elementName;
942 buf += ";\n\t";
943 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000944 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000945 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000946 elementTypeAsString = DR->getDecl()->getType().getAsString();
947 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000948 else
949 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
950
951 // struct __objcFastEnumerationState enumState = { 0 };
952 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
953 // id items[16];
954 buf += "id items[16];\n\t";
955 // id l_collection = (id)
956 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +0000957 // Find start location of 'collection' the hard way!
958 const char *startCollectionBuf = startBuf;
959 startCollectionBuf += 3; // skip 'for'
960 startCollectionBuf = strchr(startCollectionBuf, '(');
961 startCollectionBuf++; // skip '('
962 // find 'in' and skip it.
963 while (*startCollectionBuf != ' ' ||
964 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
965 (*(startCollectionBuf+3) != ' ' &&
966 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
967 startCollectionBuf++;
968 startCollectionBuf += 3;
969
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000970 // Replace: "for (type element in" with string constructed thus far.
971 Rewrite.ReplaceText(startLoc, startCollectionBuf - startBuf,
972 buf.c_str(), buf.size());
973 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +0000974 SourceLocation rightParenLoc = S->getRParenLoc();
975 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
976 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000977 buf = ";\n\t";
978
979 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
980 // objects:items count:16];
981 // which is synthesized into:
982 // unsigned int limit =
983 // ((unsigned int (*)
984 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
985 // (void *)objc_msgSend)((id)l_collection,
986 // sel_registerName(
987 // "countByEnumeratingWithState:objects:count:"),
988 // (struct __objcFastEnumerationState *)&state,
989 // (id *)items, (unsigned int)16);
990 buf += "unsigned long limit =\n\t\t";
991 SynthCountByEnumWithState(buf);
992 buf += ";\n\t";
993 /// if (limit) {
994 /// unsigned long startMutations = *enumState.mutationsPtr;
995 /// do {
996 /// unsigned long counter = 0;
997 /// do {
998 /// if (startMutations != *enumState.mutationsPtr)
999 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001000 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001001 buf += "if (limit) {\n\t";
1002 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1003 buf += "do {\n\t\t";
1004 buf += "unsigned long counter = 0;\n\t\t";
1005 buf += "do {\n\t\t\t";
1006 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1007 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1008 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001009 buf += " = (";
1010 buf += elementTypeAsString;
1011 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001012 // Replace ')' in for '(' type elem in collection ')' with all of these.
1013 Rewrite.ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
1014
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001015 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001016 /// } while (counter < limit);
1017 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1018 /// objects:items count:16]);
1019 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001020 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001021 /// }
1022 /// else
1023 /// elem = nil;
1024 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001025 ///
1026 buf = ";\n\t";
1027 buf += "__continue_label_";
1028 buf += utostr(ObjCBcLabelNo.back());
1029 buf += ": ;";
1030 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001031 buf += "} while (counter < limit);\n\t";
1032 buf += "} while (limit = ";
1033 SynthCountByEnumWithState(buf);
1034 buf += ");\n\t";
1035 buf += elementName;
1036 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001037 buf += "__break_label_";
1038 buf += utostr(ObjCBcLabelNo.back());
1039 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001040 buf += "}\n\t";
1041 buf += "else\n\t\t";
1042 buf += elementName;
1043 buf += " = nil;\n";
1044 buf += "}\n";
1045 // Insert all these *after* the statement body.
1046 SourceLocation endBodyLoc = S->getBody()->getLocEnd();
1047 const char *endBodyBuf = SM->getCharacterData(endBodyLoc)+1;
1048 endBodyLoc = startLoc.getFileLocWithOffset(endBodyBuf-startBuf);
1049 Rewrite.InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001050 Stmts.pop_back();
1051 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001052
1053 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001054}
1055
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001056Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001057 // Get the start location and compute the semi location.
1058 SourceLocation startLoc = S->getLocStart();
1059 const char *startBuf = SM->getCharacterData(startLoc);
1060
1061 assert((*startBuf == '@') && "bogus @try location");
1062
1063 std::string buf;
1064 // declare a new scope with two variables, _stack and _rethrow.
1065 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1066 buf += "int buf[18/*32-bit i386*/];\n";
1067 buf += "char *pointers[4];} _stack;\n";
1068 buf += "id volatile _rethrow = 0;\n";
1069 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001070 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001071
1072 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
1073
1074 startLoc = S->getTryBody()->getLocEnd();
1075 startBuf = SM->getCharacterData(startLoc);
1076
1077 assert((*startBuf == '}') && "bogus @try block");
1078
1079 SourceLocation lastCurlyLoc = startLoc;
1080
1081 startLoc = startLoc.getFileLocWithOffset(1);
1082 buf = " /* @catch begin */ else {\n";
1083 buf += " id _caught = objc_exception_extract(&_stack);\n";
1084 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001085 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001086 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1087 buf += " else { /* @catch continue */";
1088
Chris Lattner28d1fe82007-11-08 04:41:51 +00001089 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001090
1091 bool sawIdTypedCatch = false;
1092 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001093 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001094 while (catchList) {
1095 Stmt *catchStmt = catchList->getCatchParamStmt();
1096
1097 if (catchList == S->getCatchStmts())
1098 buf = "if ("; // we are generating code for the first catch clause
1099 else
1100 buf = "else if (";
1101 startLoc = catchList->getLocStart();
1102 startBuf = SM->getCharacterData(startLoc);
1103
1104 assert((*startBuf == '@') && "bogus @catch location");
1105
1106 const char *lParenLoc = strchr(startBuf, '(');
1107
1108 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
1109 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001110 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001111 buf += "1) { ";
1112 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1113 buf.c_str(), buf.size());
1114 sawIdTypedCatch = true;
1115 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001116 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001117
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001118 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001119 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001120 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001121 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001122 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +00001123 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1124 buf.c_str(), buf.size());
1125 }
1126 }
1127 // Now rewrite the body...
1128 lastCatchBody = catchList->getCatchBody();
1129 SourceLocation rParenLoc = catchList->getRParenLoc();
1130 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1131 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1132 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1133 assert((*rParenBuf == ')') && "bogus @catch paren location");
1134 assert((*bodyBuf == '{') && "bogus @catch body location");
1135
1136 buf = " = _caught;";
1137 // Here we replace ") {" with "= _caught;" (which initializes and
1138 // declares the @catch parameter).
1139 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
1140 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001141 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001142 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001143 }
Steve Naroff75730982007-11-07 04:08:17 +00001144 catchList = catchList->getNextCatchStmt();
1145 }
1146 // Complete the catch list...
1147 if (lastCatchBody) {
1148 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1149 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1150 assert((*bodyBuf == '}') && "bogus @catch body location");
1151 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1152 buf = " } } /* @catch end */\n";
1153
Chris Lattner28d1fe82007-11-08 04:41:51 +00001154 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001155
1156 // Set lastCurlyLoc
1157 lastCurlyLoc = lastCatchBody->getLocEnd();
1158 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001159 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001160 startLoc = finalStmt->getLocStart();
1161 startBuf = SM->getCharacterData(startLoc);
1162 assert((*startBuf == '@') && "bogus @finally start");
1163
1164 buf = "/* @finally */";
1165 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
1166
1167 Stmt *body = finalStmt->getFinallyBody();
1168 SourceLocation startLoc = body->getLocStart();
1169 SourceLocation endLoc = body->getLocEnd();
1170 const char *startBuf = SM->getCharacterData(startLoc);
1171 const char *endBuf = SM->getCharacterData(endLoc);
1172 assert((*startBuf == '{') && "bogus @finally body location");
1173 assert((*endBuf == '}') && "bogus @finally body location");
1174
1175 startLoc = startLoc.getFileLocWithOffset(1);
1176 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001177 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001178 endLoc = endLoc.getFileLocWithOffset(-1);
1179 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001180 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001181
1182 // Set lastCurlyLoc
1183 lastCurlyLoc = body->getLocEnd();
1184 }
1185 // Now emit the final closing curly brace...
1186 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1187 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001188 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001189 return 0;
1190}
1191
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001192Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001193 return 0;
1194}
1195
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001196Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001197 return 0;
1198}
1199
Steve Naroff2bd03922007-11-07 15:32:26 +00001200// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
1201// the throw expression is typically a message expression that's already
1202// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001203Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001204 // Get the start location and compute the semi location.
1205 SourceLocation startLoc = S->getLocStart();
1206 const char *startBuf = SM->getCharacterData(startLoc);
1207
1208 assert((*startBuf == '@') && "bogus @throw location");
1209
1210 std::string buf;
1211 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001212 if (S->getThrowExpr())
1213 buf = "objc_exception_throw(";
1214 else // add an implicit argument
1215 buf = "objc_exception_throw(_caught";
Steve Naroff2bd03922007-11-07 15:32:26 +00001216 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1217 const char *semiBuf = strchr(startBuf, ';');
1218 assert((*semiBuf == ';') && "@throw: can't find ';'");
1219 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1220 buf = ");";
1221 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
1222 return 0;
1223}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001224
Chris Lattnere64b7772007-10-24 16:57:36 +00001225Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001226 // Create a new string expression.
1227 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001228 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001229 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001230 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1231 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001232 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +00001233 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
1234 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001235 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1236 "rewriting sub-expression within a macro (may not be correct)");
Chris Lattner182745a2007-12-02 01:09:57 +00001237 SourceRange Range = Exp->getSourceRange();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001238 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattnere365c502007-11-30 22:25:36 +00001239 }
1240
Chris Lattner07506182007-11-30 22:53:43 +00001241 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001242 delete Exp;
1243 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001244}
1245
Steve Naroffb42f8412007-11-05 14:50:49 +00001246Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1247 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1248 // Create a call to sel_registerName("selName").
1249 llvm::SmallVector<Expr*, 8> SelExprs;
1250 QualType argType = Context->getPointerType(Context->CharTy);
1251 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1252 Exp->getSelector().getName().size(),
1253 false, argType, SourceLocation(),
1254 SourceLocation()));
1255 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1256 &SelExprs[0], SelExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +00001257 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
1258 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001259 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1260 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001261 SourceRange Range = Exp->getSourceRange();
1262 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001263 }
Steve Naroffb42f8412007-11-05 14:50:49 +00001264 delete Exp;
1265 return SelExp;
1266}
1267
Steve Naroff934f2762007-10-24 22:48:43 +00001268CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1269 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001270 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001271 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001272
1273 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001274 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001275
1276 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001277 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001278 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1279
1280 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001281
Steve Naroff934f2762007-10-24 22:48:43 +00001282 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1283}
1284
Steve Naroffd5255f52007-11-01 13:24:47 +00001285static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1286 const char *&startRef, const char *&endRef) {
1287 while (startBuf < endBuf) {
1288 if (*startBuf == '<')
1289 startRef = startBuf; // mark the start.
1290 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001291 if (startRef && *startRef == '<') {
1292 endRef = startBuf; // mark the end.
1293 return true;
1294 }
1295 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001296 }
1297 startBuf++;
1298 }
1299 return false;
1300}
1301
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001302static void scanToNextArgument(const char *&argRef) {
1303 int angle = 0;
1304 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1305 if (*argRef == '<')
1306 angle++;
1307 else if (*argRef == '>')
1308 angle--;
1309 argRef++;
1310 }
1311 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1312}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001313
Steve Naroffd5255f52007-11-01 13:24:47 +00001314bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001315
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001316 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001317 return true;
1318
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001319 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001320 return true;
1321
Steve Naroffd5255f52007-11-01 13:24:47 +00001322 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001323 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001324 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001325 return true; // we have "Class <Protocol> *".
1326 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001327 return false;
1328}
1329
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001330void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001331 SourceLocation Loc;
1332 QualType Type;
1333 const FunctionTypeProto *proto = 0;
1334 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1335 Loc = VD->getLocation();
1336 Type = VD->getType();
1337 }
1338 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1339 Loc = FD->getLocation();
1340 // Check for ObjC 'id' and class types that have been adorned with protocol
1341 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1342 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1343 assert(funcType && "missing function type");
1344 proto = dyn_cast<FunctionTypeProto>(funcType);
1345 if (!proto)
1346 return;
1347 Type = proto->getResultType();
1348 }
1349 else
1350 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001351
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001352 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001353 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001354
1355 const char *endBuf = SM->getCharacterData(Loc);
1356 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001357 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001358 startBuf--; // scan backward (from the decl location) for return type.
1359 const char *startRef = 0, *endRef = 0;
1360 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1361 // Get the locations of the startRef, endRef.
1362 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1363 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1364 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001365 Rewrite.InsertText(LessLoc, "/*", 2);
1366 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001367 }
1368 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001369 if (!proto)
1370 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001371 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001372 const char *startBuf = SM->getCharacterData(Loc);
1373 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001374 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1375 if (needToScanForQualifiers(proto->getArgType(i))) {
1376 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001377
Steve Naroffd5255f52007-11-01 13:24:47 +00001378 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001379 // scan forward (from the decl location) for argument types.
1380 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001381 const char *startRef = 0, *endRef = 0;
1382 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1383 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001384 SourceLocation LessLoc =
1385 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1386 SourceLocation GreaterLoc =
1387 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001388 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001389 Rewrite.InsertText(LessLoc, "/*", 2);
1390 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001391 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001392 startBuf = ++endBuf;
1393 }
1394 else {
1395 while (*startBuf != ')' && *startBuf != ',')
1396 startBuf++; // scan forward (from the decl location) for argument types.
1397 startBuf++;
1398 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001399 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001400}
1401
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001402// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1403void RewriteTest::SynthSelGetUidFunctionDecl() {
1404 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1405 llvm::SmallVector<QualType, 16> ArgTys;
1406 ArgTys.push_back(Context->getPointerType(
1407 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001408 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001409 &ArgTys[0], ArgTys.size(),
1410 false /*isVariadic*/);
1411 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1412 SelGetUidIdent, getFuncType,
1413 FunctionDecl::Extern, false, 0);
1414}
1415
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001416// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1417void RewriteTest::SynthGetProtocolFunctionDecl() {
1418 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1419 llvm::SmallVector<QualType, 16> ArgTys;
1420 ArgTys.push_back(Context->getPointerType(
1421 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001422 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001423 &ArgTys[0], ArgTys.size(),
1424 false /*isVariadic*/);
1425 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1426 SelGetProtoIdent, getFuncType,
1427 FunctionDecl::Extern, false, 0);
1428}
1429
Steve Naroff09b266e2007-10-30 23:14:51 +00001430void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1431 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001432 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001433 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001434 return;
1435 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001436 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001437}
1438
1439// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1440void RewriteTest::SynthMsgSendFunctionDecl() {
1441 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1442 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001443 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001444 assert(!argT.isNull() && "Can't find 'id' type");
1445 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001446 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001447 assert(!argT.isNull() && "Can't find 'SEL' type");
1448 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001449 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001450 &ArgTys[0], ArgTys.size(),
1451 true /*isVariadic*/);
1452 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1453 msgSendIdent, msgSendType,
1454 FunctionDecl::Extern, false, 0);
1455}
1456
Steve Naroff874e2322007-11-15 10:28:18 +00001457// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1458void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1459 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1460 llvm::SmallVector<QualType, 16> ArgTys;
1461 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1462 &Context->Idents.get("objc_super"), 0);
1463 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1464 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1465 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001466 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001467 assert(!argT.isNull() && "Can't find 'SEL' type");
1468 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001469 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001470 &ArgTys[0], ArgTys.size(),
1471 true /*isVariadic*/);
1472 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1473 msgSendIdent, msgSendType,
1474 FunctionDecl::Extern, false, 0);
1475}
1476
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001477// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1478void RewriteTest::SynthMsgSendStretFunctionDecl() {
1479 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1480 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001481 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001482 assert(!argT.isNull() && "Can't find 'id' type");
1483 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001484 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001485 assert(!argT.isNull() && "Can't find 'SEL' type");
1486 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001487 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001488 &ArgTys[0], ArgTys.size(),
1489 true /*isVariadic*/);
1490 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1491 msgSendIdent, msgSendType,
1492 FunctionDecl::Extern, false, 0);
1493}
1494
1495// SynthMsgSendSuperStretFunctionDecl -
1496// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1497void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1498 IdentifierInfo *msgSendIdent =
1499 &Context->Idents.get("objc_msgSendSuper_stret");
1500 llvm::SmallVector<QualType, 16> ArgTys;
1501 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1502 &Context->Idents.get("objc_super"), 0);
1503 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1504 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1505 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001506 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001507 assert(!argT.isNull() && "Can't find 'SEL' type");
1508 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001509 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001510 &ArgTys[0], ArgTys.size(),
1511 true /*isVariadic*/);
1512 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1513 msgSendIdent, msgSendType,
1514 FunctionDecl::Extern, false, 0);
1515}
1516
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001517// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1518void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1519 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1520 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001521 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001522 assert(!argT.isNull() && "Can't find 'id' type");
1523 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001524 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001525 assert(!argT.isNull() && "Can't find 'SEL' type");
1526 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001527 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001528 &ArgTys[0], ArgTys.size(),
1529 true /*isVariadic*/);
1530 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1531 msgSendIdent, msgSendType,
1532 FunctionDecl::Extern, false, 0);
1533}
1534
Steve Naroff09b266e2007-10-30 23:14:51 +00001535// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1536void RewriteTest::SynthGetClassFunctionDecl() {
1537 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1538 llvm::SmallVector<QualType, 16> ArgTys;
1539 ArgTys.push_back(Context->getPointerType(
1540 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001541 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001542 &ArgTys[0], ArgTys.size(),
1543 false /*isVariadic*/);
1544 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1545 getClassIdent, getClassType,
1546 FunctionDecl::Extern, false, 0);
1547}
1548
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001549// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1550void RewriteTest::SynthGetMetaClassFunctionDecl() {
1551 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1552 llvm::SmallVector<QualType, 16> ArgTys;
1553 ArgTys.push_back(Context->getPointerType(
1554 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001555 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001556 &ArgTys[0], ArgTys.size(),
1557 false /*isVariadic*/);
1558 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1559 getClassIdent, getClassType,
1560 FunctionDecl::Extern, false, 0);
1561}
1562
Steve Naroff96984642007-11-08 14:30:50 +00001563// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1564void RewriteTest::SynthCFStringFunctionDecl() {
1565 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1566 llvm::SmallVector<QualType, 16> ArgTys;
1567 ArgTys.push_back(Context->getPointerType(
1568 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001569 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001570 &ArgTys[0], ArgTys.size(),
1571 false /*isVariadic*/);
1572 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1573 getClassIdent, getClassType,
1574 FunctionDecl::Extern, false, 0);
1575}
1576
Steve Naroffbeaf2992007-11-03 11:27:19 +00001577Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001578#if 1
1579 // This rewrite is specific to GCC, which has builtin support for CFString.
1580 if (!CFStringFunctionDecl)
1581 SynthCFStringFunctionDecl();
1582 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1583 llvm::SmallVector<Expr*, 8> StrExpr;
1584 StrExpr.push_back(Exp->getString());
1585 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1586 &StrExpr[0], StrExpr.size());
1587 // cast to NSConstantString *
1588 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +00001589 if (Rewrite.ReplaceStmt(Exp, cast)) {
1590 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001591 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1592 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001593 SourceRange Range = Exp->getSourceRange();
1594 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001595 }
Steve Naroff96984642007-11-08 14:30:50 +00001596 delete Exp;
1597 return cast;
1598#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001599 assert(ConstantStringClassReference && "Can't find constant string reference");
1600 llvm::SmallVector<Expr*, 4> InitExprs;
1601
1602 // Synthesize "(Class)&_NSConstantStringClassReference"
1603 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1604 ConstantStringClassReference->getType(),
1605 SourceLocation());
1606 QualType expType = Context->getPointerType(ClsRef->getType());
1607 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1608 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001609 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001610 SourceLocation());
1611 InitExprs.push_back(cast); // set the 'isa'.
1612 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1613 unsigned IntSize = static_cast<unsigned>(
1614 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1615 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1616 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1617 Exp->getLocStart());
1618 InitExprs.push_back(len); // set "int numBytes".
1619
1620 // struct NSConstantString
1621 QualType CFConstantStrType = Context->getCFConstantStringType();
1622 // (struct NSConstantString) { <exprs from above> }
1623 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1624 &InitExprs[0], InitExprs.size(),
1625 SourceLocation());
Steve Naroffe9b12192008-01-14 18:19:28 +00001626 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001627 // struct NSConstantString *
1628 expType = Context->getPointerType(StrRep->getType());
1629 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1630 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001631 // cast to NSConstantString *
1632 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001633 Rewrite.ReplaceStmt(Exp, cast);
1634 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001635 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001636#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001637}
1638
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001639ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001640 // check if we are sending a message to 'super'
1641 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001642 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1643 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1644 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1645 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001646 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001647 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001648 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001649 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001650 if (ObjCInterfaceType *IT =
1651 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001652 if (IT->getDecl() ==
1653 CurMethodDecl->getClassInterface()->getSuperClass())
1654 return IT->getDecl();
1655 }
1656 }
1657 }
1658 }
1659 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001660 }
Steve Naroff874e2322007-11-15 10:28:18 +00001661 }
1662 return 0;
1663}
1664
1665// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1666QualType RewriteTest::getSuperStructType() {
1667 if (!SuperStructDecl) {
1668 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1669 &Context->Idents.get("objc_super"), 0);
1670 QualType FieldTypes[2];
1671
1672 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001673 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001674 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001675 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001676 // Create fields
1677 FieldDecl *FieldDecls[2];
1678
1679 for (unsigned i = 0; i < 2; ++i)
1680 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1681
1682 SuperStructDecl->defineBody(FieldDecls, 4);
1683 }
1684 return Context->getTagDeclType(SuperStructDecl);
1685}
1686
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001687Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001688 if (!SelGetUidFunctionDecl)
1689 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001690 if (!MsgSendFunctionDecl)
1691 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001692 if (!MsgSendSuperFunctionDecl)
1693 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001694 if (!MsgSendStretFunctionDecl)
1695 SynthMsgSendStretFunctionDecl();
1696 if (!MsgSendSuperStretFunctionDecl)
1697 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001698 if (!MsgSendFpretFunctionDecl)
1699 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001700 if (!GetClassFunctionDecl)
1701 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001702 if (!GetMetaClassFunctionDecl)
1703 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001704
Steve Naroff874e2322007-11-15 10:28:18 +00001705 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001706 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1707 // May need to use objc_msgSend_stret() as well.
1708 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001709 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001710 QualType resultType = mDecl->getResultType();
1711 if (resultType.getCanonicalType()->isStructureType()
1712 || resultType.getCanonicalType()->isUnionType())
1713 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001714 else if (resultType.getCanonicalType()->isRealFloatingType())
1715 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001716 }
Steve Naroff874e2322007-11-15 10:28:18 +00001717
Steve Naroff934f2762007-10-24 22:48:43 +00001718 // Synthesize a call to objc_msgSend().
1719 llvm::SmallVector<Expr*, 8> MsgExprs;
1720 IdentifierInfo *clsName = Exp->getClassName();
1721
1722 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1723 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001724 if (!strcmp(clsName->getName(), "super")) {
1725 MsgSendFlavor = MsgSendSuperFunctionDecl;
1726 if (MsgSendStretFlavor)
1727 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1728 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1729
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001730 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001731 CurMethodDecl->getClassInterface()->getSuperClass();
1732
1733 llvm::SmallVector<Expr*, 4> InitExprs;
1734
1735 // set the receiver to self, the first argument to all methods.
1736 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001737 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001738 SourceLocation()));
1739 llvm::SmallVector<Expr*, 8> ClsExprs;
1740 QualType argType = Context->getPointerType(Context->CharTy);
1741 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1742 SuperDecl->getIdentifier()->getLength(),
1743 false, argType, SourceLocation(),
1744 SourceLocation()));
1745 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1746 &ClsExprs[0],
1747 ClsExprs.size());
1748 // To turn off a warning, type-cast to 'id'
1749 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001750 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001751 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1752 // struct objc_super
1753 QualType superType = getSuperStructType();
1754 // (struct objc_super) { <exprs from above> }
1755 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1756 &InitExprs[0], InitExprs.size(),
1757 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001758 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001759 superType, ILE, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001760 // struct objc_super *
1761 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1762 Context->getPointerType(SuperRep->getType()),
1763 SourceLocation());
1764 MsgExprs.push_back(Unop);
1765 } else {
1766 llvm::SmallVector<Expr*, 8> ClsExprs;
1767 QualType argType = Context->getPointerType(Context->CharTy);
1768 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1769 clsName->getLength(),
1770 false, argType, SourceLocation(),
1771 SourceLocation()));
1772 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1773 &ClsExprs[0],
1774 ClsExprs.size());
1775 MsgExprs.push_back(Cls);
1776 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001777 } else { // instance message.
1778 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001779
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001780 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001781 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001782 if (MsgSendStretFlavor)
1783 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001784 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1785
1786 llvm::SmallVector<Expr*, 4> InitExprs;
1787
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001788 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001789 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001790 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001791
1792 llvm::SmallVector<Expr*, 8> ClsExprs;
1793 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001794 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1795 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001796 false, argType, SourceLocation(),
1797 SourceLocation()));
1798 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001799 &ClsExprs[0],
1800 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001801 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001802 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001803 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001804 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001805 // struct objc_super
1806 QualType superType = getSuperStructType();
1807 // (struct objc_super) { <exprs from above> }
1808 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1809 &InitExprs[0], InitExprs.size(),
1810 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001811 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001812 superType, ILE, false);
Steve Naroff874e2322007-11-15 10:28:18 +00001813 // struct objc_super *
1814 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1815 Context->getPointerType(SuperRep->getType()),
1816 SourceLocation());
1817 MsgExprs.push_back(Unop);
1818 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001819 // Remove all type-casts because it may contain objc-style types; e.g.
1820 // Foo<Proto> *.
1821 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1822 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001823 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001824 MsgExprs.push_back(recExpr);
1825 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001826 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001827 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001828 llvm::SmallVector<Expr*, 8> SelExprs;
1829 QualType argType = Context->getPointerType(Context->CharTy);
1830 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1831 Exp->getSelector().getName().size(),
1832 false, argType, SourceLocation(),
1833 SourceLocation()));
1834 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1835 &SelExprs[0], SelExprs.size());
1836 MsgExprs.push_back(SelExp);
1837
1838 // Now push any user supplied arguments.
1839 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001840 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001841 // Make all implicit casts explicit...ICE comes in handy:-)
1842 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1843 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001844 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1845 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001846 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001847 }
1848 // Make id<P...> cast into an 'id' cast.
1849 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001850 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001851 while ((CE = dyn_cast<CastExpr>(userExpr)))
1852 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001853 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001854 userExpr, SourceLocation());
1855 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001856 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001857 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001858 // We've transferred the ownership to MsgExprs. Null out the argument in
1859 // the original expression, since we will delete it below.
1860 Exp->setArg(i, 0);
1861 }
Steve Naroffab972d32007-11-04 22:37:50 +00001862 // Generate the funky cast.
1863 CastExpr *cast;
1864 llvm::SmallVector<QualType, 8> ArgTypes;
1865 QualType returnType;
1866
1867 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001868 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1869 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1870 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001871 ArgTypes.push_back(Context->getObjCIdType());
1872 ArgTypes.push_back(Context->getObjCSelType());
1873 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00001874 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001875 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001876 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1877 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001878 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001879 ArgTypes.push_back(t);
1880 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001881 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1882 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00001883 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001884 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00001885 }
1886 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001887 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001888
1889 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001890 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1891 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001892
1893 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1894 // If we don't do this cast, we get the following bizarre warning/note:
1895 // xx.m:13: warning: function called through a non-compatible type
1896 // xx.m:13: note: if this code is reached, the program will abort
1897 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1898 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001899
Steve Naroffab972d32007-11-04 22:37:50 +00001900 // Now do the "normal" pointer to function cast.
1901 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001902 &ArgTypes[0], ArgTypes.size(),
1903 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001904 castType = Context->getPointerType(castType);
1905 cast = new CastExpr(castType, cast, SourceLocation());
1906
1907 // Don't forget the parens to enforce the proper binding.
1908 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1909
1910 const FunctionType *FT = msgSendType->getAsFunctionType();
1911 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1912 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001913 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001914 if (MsgSendStretFlavor) {
1915 // We have the method which returns a struct/union. Must also generate
1916 // call to objc_msgSend_stret and hang both varieties on a conditional
1917 // expression which dictate which one to envoke depending on size of
1918 // method's return type.
1919
1920 // Create a reference to the objc_msgSend_stret() declaration.
1921 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1922 SourceLocation());
1923 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1924 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1925 SourceLocation());
1926 // Now do the "normal" pointer to function cast.
1927 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001928 &ArgTypes[0], ArgTypes.size(),
1929 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001930 castType = Context->getPointerType(castType);
1931 cast = new CastExpr(castType, cast, SourceLocation());
1932
1933 // Don't forget the parens to enforce the proper binding.
1934 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1935
1936 FT = msgSendType->getAsFunctionType();
1937 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1938 FT->getResultType(), SourceLocation());
1939
1940 // Build sizeof(returnType)
1941 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1942 returnType, Context->getSizeType(),
1943 SourceLocation(), SourceLocation());
1944 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1945 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1946 // For X86 it is more complicated and some kind of target specific routine
1947 // is needed to decide what to do.
1948 unsigned IntSize = static_cast<unsigned>(
1949 Context->getTypeSize(Context->IntTy, SourceLocation()));
1950
1951 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1952 Context->IntTy,
1953 SourceLocation());
1954 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1955 BinaryOperator::LE,
1956 Context->IntTy,
1957 SourceLocation());
1958 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1959 ConditionalOperator *CondExpr =
1960 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001961 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001962 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001963 return ReplacingStmt;
1964}
1965
1966Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
1967 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00001968 // Now do the actual rewrite.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001969 if (Rewrite.ReplaceStmt(Exp, ReplacingStmt)) {
Steve Naroff5ca40202007-12-19 14:32:56 +00001970 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001971 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1972 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001973 SourceRange Range = Exp->getSourceRange();
1974 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001975 }
Steve Naroff934f2762007-10-24 22:48:43 +00001976
Chris Lattnere64b7772007-10-24 16:57:36 +00001977 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001978 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00001979}
1980
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001981/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1982/// call to objc_getProtocol("proto-name").
1983Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1984 if (!GetProtocolFunctionDecl)
1985 SynthGetProtocolFunctionDecl();
1986 // Create a call to objc_getProtocol("ProtocolName").
1987 llvm::SmallVector<Expr*, 8> ProtoExprs;
1988 QualType argType = Context->getPointerType(Context->CharTy);
1989 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1990 strlen(Exp->getProtocol()->getName()),
1991 false, argType, SourceLocation(),
1992 SourceLocation()));
1993 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1994 &ProtoExprs[0],
1995 ProtoExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +00001996 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
1997 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001998 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1999 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00002000 SourceRange Range = Exp->getSourceRange();
2001 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00002002 }
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002003 delete Exp;
2004 return ProtoExp;
2005
2006}
2007
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002008/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002009/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002010void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002011 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002012 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2013 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002014 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002015 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002016 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002017 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00002018 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00002019 SourceLocation LocStart = CDecl->getLocStart();
2020 SourceLocation LocEnd = CDecl->getLocEnd();
2021
2022 const char *startBuf = SM->getCharacterData(LocStart);
2023 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002024 // If no ivars and no root or if its root, directly or indirectly,
2025 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002026 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002027 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2028 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2029 Result.c_str(), Result.size());
2030 return;
2031 }
2032
2033 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002034 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002035 Result += "\nstruct ";
2036 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00002037
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002038 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002039 const char *cursor = strchr(startBuf, '{');
2040 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002041 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002042
2043 // rewrite the original header *without* disturbing the '{'
2044 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
2045 Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002046 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002047 Result = "\n struct ";
2048 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00002049 // Note: We don't name the field decl. This simplifies the "codegen" for
2050 // accessing a superclasses instance variables (and is similar to what gcc
2051 // does internally). The unnamed struct field feature is enabled with
2052 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2053 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002054 Result += ";\n";
2055
2056 // insert the super class structure definition.
2057 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
2058 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
2059 }
2060 cursor++; // past '{'
2061
2062 // Now comment out any visibility specifiers.
2063 while (cursor < endBuf) {
2064 if (*cursor == '@') {
2065 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002066 // Skip whitespace.
2067 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2068 /*scan*/;
2069
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002070 // FIXME: presence of @public, etc. inside comment results in
2071 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002072 if (!strncmp(cursor, "public", strlen("public")) ||
2073 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002074 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00002075 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002076 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002077 // FIXME: If there are cases where '<' is used in ivar declaration part
2078 // of user code, then scan the ivar list and use needToScanForQualifiers
2079 // for type checking.
2080 else if (*cursor == '<') {
2081 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2082 Rewrite.InsertText(atLoc, "/* ", 3);
2083 cursor = strchr(cursor, '>');
2084 cursor++;
2085 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2086 Rewrite.InsertText(atLoc, " */", 3);
2087 }
Steve Narofffea763e82007-11-14 19:25:57 +00002088 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002089 }
Steve Narofffea763e82007-11-14 19:25:57 +00002090 // Don't forget to add a ';'!!
2091 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
2092 } else { // we don't have any instance variables - insert super struct.
2093 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2094 Result += " {\n struct ";
2095 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00002096 // Note: We don't name the field decl. This simplifies the "codegen" for
2097 // accessing a superclasses instance variables (and is similar to what gcc
2098 // does internally). The unnamed struct field feature is enabled with
2099 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2100 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002101 Result += ";\n};\n";
2102 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2103 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002104 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002105 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002106 if (!ObjCSynthesizedStructs.insert(CDecl))
2107 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002108}
2109
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002110// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002111/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002112void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002113 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002114 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002115 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002116 const char *ClassName,
2117 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002118 if (MethodBegin == MethodEnd) return;
2119
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002120 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002121 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002122 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002123 SEL _cmd;
2124 char *method_types;
2125 void *_imp;
2126 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002127 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002128 Result += "\nstruct _objc_method {\n";
2129 Result += "\tSEL _cmd;\n";
2130 Result += "\tchar *method_types;\n";
2131 Result += "\tvoid *_imp;\n";
2132 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002133
2134 /* struct _objc_method_list {
2135 struct _objc_method_list *next_method;
2136 int method_count;
2137 struct _objc_method method_list[];
2138 }
2139 */
2140 Result += "\nstruct _objc_method_list {\n";
2141 Result += "\tstruct _objc_method_list *next_method;\n";
2142 Result += "\tint method_count;\n";
2143 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002144 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002145 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002146
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002147 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002148 Result += "\nstatic struct _objc_method_list _OBJC_";
2149 Result += prefix;
2150 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2151 Result += "_METHODS_";
2152 Result += ClassName;
2153 Result += " __attribute__ ((section (\"__OBJC, __";
2154 Result += IsInstanceMethod ? "inst" : "cls";
2155 Result += "_meth\")))= ";
2156 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002157
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002158 Result += "\t,{{(SEL)\"";
2159 Result += (*MethodBegin)->getSelector().getName().c_str();
2160 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002161 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002162 Result += "\", \"";
2163 Result += MethodTypeString;
2164 Result += "\", ";
2165 Result += MethodInternalNames[*MethodBegin];
2166 Result += "}\n";
2167 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2168 Result += "\t ,{(SEL)\"";
2169 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002170 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002171 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002172 Result += "\", \"";
2173 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002174 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002175 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002176 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002177 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002178 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002179}
2180
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002181/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2182void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002183 int NumProtocols,
2184 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002185 const char *ClassName,
2186 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002187 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002188 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002189 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002190 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002191 // Output struct protocol_methods holder of method selector and type.
2192 if (!objc_protocol_methods &&
2193 (PDecl->getNumInstanceMethods() > 0
2194 || PDecl->getNumClassMethods() > 0)) {
2195 /* struct protocol_methods {
2196 SEL _cmd;
2197 char *method_types;
2198 }
2199 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002200 Result += "\nstruct protocol_methods {\n";
2201 Result += "\tSEL _cmd;\n";
2202 Result += "\tchar *method_types;\n";
2203 Result += "};\n";
2204
2205 /* struct _objc_protocol_method_list {
2206 int protocol_method_count;
2207 struct protocol_methods protocols[];
2208 }
2209 */
2210 Result += "\nstruct _objc_protocol_method_list {\n";
2211 Result += "\tint protocol_method_count;\n";
2212 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002213 objc_protocol_methods = true;
2214 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002215
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002216 int NumMethods = PDecl->getNumInstanceMethods();
2217 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002218 Result += "\nstatic struct _objc_protocol_method_list "
2219 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2220 Result += PDecl->getName();
2221 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2222 "{\n\t" + utostr(NumMethods) + "\n";
2223
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002224 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002225 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002226 E = PDecl->instmeth_end(); I != E; ++I) {
2227 if (I == PDecl->instmeth_begin())
2228 Result += "\t ,{{(SEL)\"";
2229 else
2230 Result += "\t ,{(SEL)\"";
2231 Result += (*I)->getSelector().getName().c_str();
2232 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002233 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002234 Result += "\", \"";
2235 Result += MethodTypeString;
2236 Result += "\"}\n";
2237 }
2238 Result += "\t }\n};\n";
2239 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002240
2241 // Output class methods declared in this protocol.
2242 NumMethods = PDecl->getNumClassMethods();
2243 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002244 Result += "\nstatic struct _objc_protocol_method_list "
2245 "_OBJC_PROTOCOL_CLASS_METHODS_";
2246 Result += PDecl->getName();
2247 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2248 "{\n\t";
2249 Result += utostr(NumMethods);
2250 Result += "\n";
2251
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002252 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002253 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002254 E = PDecl->classmeth_end(); I != E; ++I) {
2255 if (I == PDecl->classmeth_begin())
2256 Result += "\t ,{{(SEL)\"";
2257 else
2258 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002259 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002260 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002261 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002262 Result += "\", \"";
2263 Result += MethodTypeString;
2264 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002265 }
2266 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002267 }
2268 // Output:
2269 /* struct _objc_protocol {
2270 // Objective-C 1.0 extensions
2271 struct _objc_protocol_extension *isa;
2272 char *protocol_name;
2273 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002274 struct _objc_protocol_method_list *instance_methods;
2275 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002276 };
2277 */
2278 static bool objc_protocol = false;
2279 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002280 Result += "\nstruct _objc_protocol {\n";
2281 Result += "\tstruct _objc_protocol_extension *isa;\n";
2282 Result += "\tchar *protocol_name;\n";
2283 Result += "\tstruct _objc_protocol **protocol_list;\n";
2284 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2285 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2286 Result += "};\n";
2287
2288 /* struct _objc_protocol_list {
2289 struct _objc_protocol_list *next;
2290 int protocol_count;
2291 struct _objc_protocol *class_protocols[];
2292 }
2293 */
2294 Result += "\nstruct _objc_protocol_list {\n";
2295 Result += "\tstruct _objc_protocol_list *next;\n";
2296 Result += "\tint protocol_count;\n";
2297 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2298 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002299 objc_protocol = true;
2300 }
2301
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002302 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2303 Result += PDecl->getName();
2304 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2305 "{\n\t0, \"";
2306 Result += PDecl->getName();
2307 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002308 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002309 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2310 Result += PDecl->getName();
2311 Result += ", ";
2312 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002313 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002314 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002315 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002316 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2317 Result += PDecl->getName();
2318 Result += "\n";
2319 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002320 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002321 Result += "0\n";
2322 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002323 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002324 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002325 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2326 Result += prefix;
2327 Result += "_PROTOCOLS_";
2328 Result += ClassName;
2329 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2330 "{\n\t0, ";
2331 Result += utostr(NumProtocols);
2332 Result += "\n";
2333
2334 Result += "\t,{&_OBJC_PROTOCOL_";
2335 Result += Protocols[0]->getName();
2336 Result += " \n";
2337
2338 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002339 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002340 Result += "\t ,&_OBJC_PROTOCOL_";
2341 Result += PDecl->getName();
2342 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002343 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002344 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002345 }
2346}
2347
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002348/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002349/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002350void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002351 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002352 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002353 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002354 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002355 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2356 CDecl = CDecl->getNextClassCategory())
2357 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2358 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002359
Chris Lattnereb44eee2007-12-23 01:40:15 +00002360 std::string FullCategoryName = ClassDecl->getName();
2361 FullCategoryName += '_';
2362 FullCategoryName += IDecl->getName();
2363
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002364 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002365 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002366 true, "CATEGORY_", FullCategoryName.c_str(),
2367 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002368
2369 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002370 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002371 false, "CATEGORY_", FullCategoryName.c_str(),
2372 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002373
2374 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002375 // Null CDecl is case of a category implementation with no category interface
2376 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002377 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002378 CDecl->getNumReferencedProtocols(),
2379 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002380 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002381
2382 /* struct _objc_category {
2383 char *category_name;
2384 char *class_name;
2385 struct _objc_method_list *instance_methods;
2386 struct _objc_method_list *class_methods;
2387 struct _objc_protocol_list *protocols;
2388 // Objective-C 1.0 extensions
2389 uint32_t size; // sizeof (struct _objc_category)
2390 struct _objc_property_list *instance_properties; // category's own
2391 // @property decl.
2392 };
2393 */
2394
2395 static bool objc_category = false;
2396 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002397 Result += "\nstruct _objc_category {\n";
2398 Result += "\tchar *category_name;\n";
2399 Result += "\tchar *class_name;\n";
2400 Result += "\tstruct _objc_method_list *instance_methods;\n";
2401 Result += "\tstruct _objc_method_list *class_methods;\n";
2402 Result += "\tstruct _objc_protocol_list *protocols;\n";
2403 Result += "\tunsigned int size;\n";
2404 Result += "\tstruct _objc_property_list *instance_properties;\n";
2405 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002406 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002407 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002408 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2409 Result += FullCategoryName;
2410 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2411 Result += IDecl->getName();
2412 Result += "\"\n\t, \"";
2413 Result += ClassDecl->getName();
2414 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002415
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002416 if (IDecl->getNumInstanceMethods() > 0) {
2417 Result += "\t, (struct _objc_method_list *)"
2418 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2419 Result += FullCategoryName;
2420 Result += "\n";
2421 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002422 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002423 Result += "\t, 0\n";
2424 if (IDecl->getNumClassMethods() > 0) {
2425 Result += "\t, (struct _objc_method_list *)"
2426 "&_OBJC_CATEGORY_CLASS_METHODS_";
2427 Result += FullCategoryName;
2428 Result += "\n";
2429 }
2430 else
2431 Result += "\t, 0\n";
2432
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002433 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002434 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2435 Result += FullCategoryName;
2436 Result += "\n";
2437 }
2438 else
2439 Result += "\t, 0\n";
2440 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002441}
2442
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002443/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2444/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002445void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2446 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002447 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002448 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002449 Result += IDecl->getName();
2450 Result += ", ";
2451 Result += ivar->getName();
2452 Result += ")";
2453}
2454
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002455//===----------------------------------------------------------------------===//
2456// Meta Data Emission
2457//===----------------------------------------------------------------------===//
2458
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002459void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002460 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002461 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002462
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002463 // Explictly declared @interface's are already synthesized.
2464 if (CDecl->ImplicitInterfaceDecl()) {
2465 // FIXME: Implementation of a class with no @interface (legacy) doese not
2466 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002467 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002468 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002469
Chris Lattnerbe6df082007-12-12 07:56:42 +00002470 // Build _objc_ivar_list metadata for classes ivars if needed
2471 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2472 ? IDecl->getImplDeclNumIvars()
2473 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002474 if (NumIvars > 0) {
2475 static bool objc_ivar = false;
2476 if (!objc_ivar) {
2477 /* struct _objc_ivar {
2478 char *ivar_name;
2479 char *ivar_type;
2480 int ivar_offset;
2481 };
2482 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002483 Result += "\nstruct _objc_ivar {\n";
2484 Result += "\tchar *ivar_name;\n";
2485 Result += "\tchar *ivar_type;\n";
2486 Result += "\tint ivar_offset;\n";
2487 Result += "};\n";
2488
2489 /* struct _objc_ivar_list {
2490 int ivar_count;
2491 struct _objc_ivar ivar_list[];
2492 };
2493 */
2494 Result += "\nstruct _objc_ivar_list {\n";
2495 Result += "\tint ivar_count;\n";
2496 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002497 objc_ivar = true;
2498 }
2499
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002500 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2501 Result += IDecl->getName();
2502 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2503 "{\n\t";
2504 Result += utostr(NumIvars);
2505 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002506
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002507 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002508 if (IDecl->getImplDeclNumIvars() > 0) {
2509 IVI = IDecl->ivar_begin();
2510 IVE = IDecl->ivar_end();
2511 } else {
2512 IVI = CDecl->ivar_begin();
2513 IVE = CDecl->ivar_end();
2514 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002515 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002516 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002517 Result += "\", \"";
2518 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002519 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002520 Result += StrEncoding;
2521 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002522 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002523 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002524 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002525 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002526 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002527 Result += "\", \"";
2528 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002529 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002530 Result += StrEncoding;
2531 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002532 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002533 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002534 }
2535
2536 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002537 }
2538
2539 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002540 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002541 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002542
2543 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002544 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002545 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002546
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002547 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002548 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002549 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002550 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002551
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002552
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002553 // Declaration of class/meta-class metadata
2554 /* struct _objc_class {
2555 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002556 const char *super_class_name;
2557 char *name;
2558 long version;
2559 long info;
2560 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002561 struct _objc_ivar_list *ivars;
2562 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002563 struct objc_cache *cache;
2564 struct objc_protocol_list *protocols;
2565 const char *ivar_layout;
2566 struct _objc_class_ext *ext;
2567 };
2568 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002569 static bool objc_class = false;
2570 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002571 Result += "\nstruct _objc_class {\n";
2572 Result += "\tstruct _objc_class *isa;\n";
2573 Result += "\tconst char *super_class_name;\n";
2574 Result += "\tchar *name;\n";
2575 Result += "\tlong version;\n";
2576 Result += "\tlong info;\n";
2577 Result += "\tlong instance_size;\n";
2578 Result += "\tstruct _objc_ivar_list *ivars;\n";
2579 Result += "\tstruct _objc_method_list *methods;\n";
2580 Result += "\tstruct objc_cache *cache;\n";
2581 Result += "\tstruct _objc_protocol_list *protocols;\n";
2582 Result += "\tconst char *ivar_layout;\n";
2583 Result += "\tstruct _objc_class_ext *ext;\n";
2584 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002585 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002586 }
2587
2588 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002589 ObjCInterfaceDecl *RootClass = 0;
2590 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002591 while (SuperClass) {
2592 RootClass = SuperClass;
2593 SuperClass = SuperClass->getSuperClass();
2594 }
2595 SuperClass = CDecl->getSuperClass();
2596
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002597 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2598 Result += CDecl->getName();
2599 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2600 "{\n\t(struct _objc_class *)\"";
2601 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2602 Result += "\"";
2603
2604 if (SuperClass) {
2605 Result += ", \"";
2606 Result += SuperClass->getName();
2607 Result += "\", \"";
2608 Result += CDecl->getName();
2609 Result += "\"";
2610 }
2611 else {
2612 Result += ", 0, \"";
2613 Result += CDecl->getName();
2614 Result += "\"";
2615 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002616 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002617 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002618 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002619 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002620 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002621 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002622 Result += "\n";
2623 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002624 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002625 Result += ", 0\n";
2626 if (CDecl->getNumIntfRefProtocols() > 0) {
2627 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2628 Result += CDecl->getName();
2629 Result += ",0,0\n";
2630 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002631 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002632 Result += "\t,0,0,0,0\n";
2633 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002634
2635 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002636 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2637 Result += CDecl->getName();
2638 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2639 "{\n\t&_OBJC_METACLASS_";
2640 Result += CDecl->getName();
2641 if (SuperClass) {
2642 Result += ", \"";
2643 Result += SuperClass->getName();
2644 Result += "\", \"";
2645 Result += CDecl->getName();
2646 Result += "\"";
2647 }
2648 else {
2649 Result += ", 0, \"";
2650 Result += CDecl->getName();
2651 Result += "\"";
2652 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002653 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002654 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002655 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002656 Result += ",0";
2657 else {
2658 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002659 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002660 Result += CDecl->getName();
2661 Result += ")";
2662 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002663 if (NumIvars > 0) {
2664 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2665 Result += CDecl->getName();
2666 Result += "\n\t";
2667 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002668 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002669 Result += ",0";
2670 if (IDecl->getNumInstanceMethods() > 0) {
2671 Result += ", &_OBJC_INSTANCE_METHODS_";
2672 Result += CDecl->getName();
2673 Result += ", 0\n\t";
2674 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002675 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002676 Result += ",0,0";
2677 if (CDecl->getNumIntfRefProtocols() > 0) {
2678 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2679 Result += CDecl->getName();
2680 Result += ", 0,0\n";
2681 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002682 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002683 Result += ",0,0,0\n";
2684 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002685}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002686
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002687/// RewriteImplementations - This routine rewrites all method implementations
2688/// and emits meta-data.
2689
2690void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002691 int ClsDefCount = ClassImplementation.size();
2692 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002693
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002694 if (ClsDefCount == 0 && CatDefCount == 0)
2695 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002696 // Rewrite implemented methods
2697 for (int i = 0; i < ClsDefCount; i++)
2698 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002699
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002700 for (int i = 0; i < CatDefCount; i++)
2701 RewriteImplementationDecl(CategoryImplementation[i]);
2702
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002703 // This is needed for use of offsetof
2704 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002705
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002706 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002707 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002708 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002709
2710 // For each implemented category, write out all its meta data.
2711 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002712 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002713
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002714 // Write objc_symtab metadata
2715 /*
2716 struct _objc_symtab
2717 {
2718 long sel_ref_cnt;
2719 SEL *refs;
2720 short cls_def_cnt;
2721 short cat_def_cnt;
2722 void *defs[cls_def_cnt + cat_def_cnt];
2723 };
2724 */
2725
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002726 Result += "\nstruct _objc_symtab {\n";
2727 Result += "\tlong sel_ref_cnt;\n";
2728 Result += "\tSEL *refs;\n";
2729 Result += "\tshort cls_def_cnt;\n";
2730 Result += "\tshort cat_def_cnt;\n";
2731 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2732 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002733
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002734 Result += "static struct _objc_symtab "
2735 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2736 Result += "\t0, 0, " + utostr(ClsDefCount)
2737 + ", " + utostr(CatDefCount) + "\n";
2738 for (int i = 0; i < ClsDefCount; i++) {
2739 Result += "\t,&_OBJC_CLASS_";
2740 Result += ClassImplementation[i]->getName();
2741 Result += "\n";
2742 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002743
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002744 for (int i = 0; i < CatDefCount; i++) {
2745 Result += "\t,&_OBJC_CATEGORY_";
2746 Result += CategoryImplementation[i]->getClassInterface()->getName();
2747 Result += "_";
2748 Result += CategoryImplementation[i]->getName();
2749 Result += "\n";
2750 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002751
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002752 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002753
2754 // Write objc_module metadata
2755
2756 /*
2757 struct _objc_module {
2758 long version;
2759 long size;
2760 const char *name;
2761 struct _objc_symtab *symtab;
2762 }
2763 */
2764
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002765 Result += "\nstruct _objc_module {\n";
2766 Result += "\tlong version;\n";
2767 Result += "\tlong size;\n";
2768 Result += "\tconst char *name;\n";
2769 Result += "\tstruct _objc_symtab *symtab;\n";
2770 Result += "};\n\n";
2771 Result += "static struct _objc_module "
2772 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002773 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2774 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002775 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002776
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002777}
Chris Lattner311ff022007-10-16 22:36:42 +00002778