blob: 237ed21f1d246099c4f113b663d95a371a506a8c [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//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000038 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000040 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000041 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +000042 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffebf2b562007-10-23 23:50:29 +000043
44 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000045 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000046 FunctionDecl *MsgSendStretFunctionDecl;
47 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000048 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000049 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000050 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000051 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000052 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000053 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000054
Steve Naroffbeaf2992007-11-03 11:27:19 +000055 // ObjC string constant support.
56 FileVarDecl *ConstantStringClassReference;
57 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000058
Steve Naroff874e2322007-11-15 10:28:18 +000059 // Needed for super.
60 ObjcMethodDecl *CurMethodDecl;
61 RecordDecl *SuperStructDecl;
62
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000063 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 public:
Chris Lattner01c57482007-10-17 22:35:30 +000065 void Initialize(ASTContext &context, unsigned mainFileID) {
66 Context = &context;
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000067 SM = &Context->getSourceManager();
Steve Naroffebf2b562007-10-23 23:50:29 +000068 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000069 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000070 MsgSendStretFunctionDecl = 0;
71 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000072 MsgSendFpretFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000073 GetClassFunctionDecl = 0;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000074 GetMetaClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000075 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000076 CFStringFunctionDecl = 0;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000077 GetProtocolFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000078 ConstantStringClassReference = 0;
79 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000080 CurMethodDecl = 0;
81 SuperStructDecl = 0;
82
Chris Lattner26de4652007-12-02 01:13:47 +000083 // Get the ID and start/end of the main file.
84 MainFileID = mainFileID;
85 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
86 MainFileStart = MainBuf->getBufferStart();
87 MainFileEnd = MainBuf->getBufferEnd();
88
89
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000090 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffe3abbf52007-11-05 14:55:35 +000091 // declaring objc_selector outside the parameter list removes a silly
92 // scope related warning...
Steve Naroff3cadd032007-12-04 23:59:30 +000093 const char *s = "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000094 "#ifndef OBJC_SUPER\n"
95 "struct objc_super { struct objc_object *o; "
96 "struct objc_object *superClass; };\n"
97 "#define OBJC_SUPER\n"
98 "#endif\n"
99 "#ifndef _REWRITER_typedef_Protocol\n"
100 "typedef struct objc_object Protocol;\n"
101 "#define _REWRITER_typedef_Protocol\n"
102 "#endif\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +0000103 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +0000104 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +0000105 "extern struct objc_object *objc_msgSendSuper"
106 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000107 "extern struct objc_object *objc_msgSend_stret"
108 "(struct objc_object *, struct objc_selector *, ...);\n"
109 "extern struct objc_object *objc_msgSendSuper_stret"
110 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000111 "extern struct objc_object *objc_msgSend_fpret"
112 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +0000113 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +0000114 "(const char *);\n"
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000115 "extern struct objc_object *objc_getMetaClass"
116 "(const char *);\n"
Steve Naroff21867b12007-11-07 18:43:40 +0000117 "extern void objc_exception_throw(struct objc_object *);\n"
118 "extern void objc_exception_try_enter(void *);\n"
119 "extern void objc_exception_try_exit(void *);\n"
120 "extern struct objc_object *objc_exception_extract(void *);\n"
121 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +0000122 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000123 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian2c1e9c72007-12-03 23:04:29 +0000124 "#include <objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000125
Steve Naroffab972d32007-11-04 22:37:50 +0000126 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
127 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +0000128 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000129
Chris Lattnerf04da132007-10-24 17:06:59 +0000130 // Top Level Driver code.
131 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000132 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +0000133 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +0000134 ~RewriteTest();
135
136 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000137 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000138 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000139 void RewriteTabs();
140 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +0000141 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000142 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000143 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +0000144 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000145 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000146 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +0000147 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000148 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000149 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane66894c2007-12-11 19:56:36 +0000150 void RewriteObjcQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000151 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000152 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
153 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000154
Chris Lattnerf04da132007-10-24 17:06:59 +0000155 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000156 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000157 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000158 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000159 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000160 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000161 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000162 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000163 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
164 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
165 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000166 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000167 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
168 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000169 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000170 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000171 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000172 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000173 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000174 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000175 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000176 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000177 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000178 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000179
Chris Lattnerf04da132007-10-24 17:06:59 +0000180 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000181 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
182 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000183
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000184 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
185 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000186
Steve Naroff0416fb92007-11-11 17:19:15 +0000187 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000188 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000189 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000190 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000191 const char *ClassName,
192 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000193
194 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
195 int NumProtocols,
196 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000197 const char *ClassName,
198 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000199 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
200 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000201 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
202 ObjcIvarDecl *ivar,
203 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000204 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000205 };
206}
207
Chris Lattnere365c502007-11-30 22:25:36 +0000208ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
209 return new RewriteTest(Diags);
210}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000211
Chris Lattnerf04da132007-10-24 17:06:59 +0000212//===----------------------------------------------------------------------===//
213// Top Level Driver Code
214//===----------------------------------------------------------------------===//
215
Chris Lattner8a12c272007-10-11 18:38:32 +0000216void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000217 // Two cases: either the decl could be in the main file, or it could be in a
218 // #included file. If the former, rewrite it now. If the later, check to see
219 // if we rewrote the #include/#import.
220 SourceLocation Loc = D->getLocation();
221 Loc = SM->getLogicalLoc(Loc);
222
223 // If this is for a builtin, ignore it.
224 if (Loc.isInvalid()) return;
225
Steve Naroffebf2b562007-10-23 23:50:29 +0000226 // Look for built-in declarations that we need to refer during the rewrite.
227 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000228 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000229 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
230 // declared in <Foundation/NSString.h>
231 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
232 ConstantStringClassReference = FVD;
233 return;
234 }
Steve Naroffbef11852007-10-26 20:53:56 +0000235 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
236 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000237 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
238 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000239 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
240 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000241 } else if (ObjcForwardProtocolDecl *FP =
242 dyn_cast<ObjcForwardProtocolDecl>(D)){
243 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000244 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000245 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000246 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
247 return HandleDeclInMainFile(D);
248
Chris Lattnerf04da132007-10-24 17:06:59 +0000249 // Otherwise, see if there is a #import in the main file that should be
250 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000251 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000252}
253
Chris Lattnerf04da132007-10-24 17:06:59 +0000254/// HandleDeclInMainFile - This is called for each top-level decl defined in the
255/// main file of the input.
256void RewriteTest::HandleDeclInMainFile(Decl *D) {
257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
258 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000259 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000260
261 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000262 if (Stmt *Body = MD->getBody()) {
263 //Body->dump();
264 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000265 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000266 CurMethodDecl = 0;
267 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000268 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000269 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
270 ClassImplementation.push_back(CI);
271 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
272 CategoryImplementation.push_back(CI);
273 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
274 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000275 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +0000276 RewriteObjcQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000277 if (VD->getInit())
278 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
279 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000280 // Nothing yet.
281}
282
283RewriteTest::~RewriteTest() {
284 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000285
286 // Rewrite tabs if we care.
287 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000288
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000289 // Rewrite Objective-c meta data*
290 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000291 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000292
Chris Lattnerf04da132007-10-24 17:06:59 +0000293 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
294 // we are done.
295 if (const RewriteBuffer *RewriteBuf =
296 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000297 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000298 std::string S(RewriteBuf->begin(), RewriteBuf->end());
299 printf("%s\n", S.c_str());
300 } else {
301 printf("No changes\n");
302 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000303 // Emit metadata.
304 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000305}
306
Chris Lattnerf04da132007-10-24 17:06:59 +0000307//===----------------------------------------------------------------------===//
308// Syntactic (non-AST) Rewriting Code
309//===----------------------------------------------------------------------===//
310
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000311void RewriteTest::RewriteInclude(SourceLocation Loc) {
312 // Rip up the #include stack to the main file.
313 SourceLocation IncLoc = Loc, NextLoc = Loc;
314 do {
315 IncLoc = Loc;
316 Loc = SM->getLogicalLoc(NextLoc);
317 NextLoc = SM->getIncludeLoc(Loc);
318 } while (!NextLoc.isInvalid());
319
320 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
321 // IncLoc indicates the header that was included if it is useful.
322 IncLoc = SM->getLogicalLoc(IncLoc);
323 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
324 Loc == LastIncLoc)
325 return;
326 LastIncLoc = Loc;
327
328 unsigned IncCol = SM->getColumnNumber(Loc);
329 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
330
331 // Replace the #import with #include.
332 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
333}
334
Chris Lattnerf04da132007-10-24 17:06:59 +0000335void RewriteTest::RewriteTabs() {
336 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
337 const char *MainBufStart = MainBuf.first;
338 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000339
Chris Lattnerf04da132007-10-24 17:06:59 +0000340 // Loop over the whole file, looking for tabs.
341 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
342 if (*BufPtr != '\t')
343 continue;
344
345 // Okay, we found a tab. This tab will turn into at least one character,
346 // but it depends on which 'virtual column' it is in. Compute that now.
347 unsigned VCol = 0;
348 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
349 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
350 ++VCol;
351
352 // Okay, now that we know the virtual column, we know how many spaces to
353 // insert. We assume 8-character tab-stops.
354 unsigned Spaces = 8-(VCol & 7);
355
356 // Get the location of the tab.
357 SourceLocation TabLoc =
358 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
359
360 // Rewrite the single tab character into a sequence of spaces.
361 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
362 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000363}
364
365
Chris Lattnerf04da132007-10-24 17:06:59 +0000366void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
367 int numDecls = ClassDecl->getNumForwardDecls();
368 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
369
370 // Get the start location and compute the semi location.
371 SourceLocation startLoc = ClassDecl->getLocation();
372 const char *startBuf = SM->getCharacterData(startLoc);
373 const char *semiPtr = strchr(startBuf, ';');
374
375 // Translate to typedef's that forward reference structs with the same name
376 // as the class. As a convenience, we include the original declaration
377 // as a comment.
378 std::string typedefString;
379 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000380 typedefString.append(startBuf, semiPtr-startBuf+1);
381 typedefString += "\n";
382 for (int i = 0; i < numDecls; i++) {
383 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000384 typedefString += "#ifndef _REWRITER_typedef_";
385 typedefString += ForwardDecl->getName();
386 typedefString += "\n";
387 typedefString += "#define _REWRITER_typedef_";
388 typedefString += ForwardDecl->getName();
389 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000390 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000391 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000392 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000393 }
394
395 // Replace the @class with typedefs corresponding to the classes.
396 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
397 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000398}
399
Steve Naroff71c0a952007-11-13 23:01:27 +0000400void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000401 for (int i = 0; i < nMethods; i++) {
402 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000403 SourceLocation LocStart = Method->getLocStart();
404 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000405
Steve Naroff1d098f62007-11-14 14:34:23 +0000406 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
407 Rewrite.InsertText(LocStart, "/* ", 3);
408 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
409 } else {
410 Rewrite.InsertText(LocStart, "// ", 3);
411 }
Steve Naroff423cb562007-10-30 13:30:57 +0000412 }
413}
414
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000415void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
416{
417 for (int i = 0; i < nProperties; i++) {
418 ObjcPropertyDecl *Property = Properties[i];
419 SourceLocation Loc = Property->getLocation();
420
421 Rewrite.ReplaceText(Loc, 0, "// ", 3);
422
423 // FIXME: handle properties that are declared across multiple lines.
424 }
425}
426
Steve Naroff423cb562007-10-30 13:30:57 +0000427void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
428 SourceLocation LocStart = CatDecl->getLocStart();
429
430 // FIXME: handle category headers that are declared across multiple lines.
431 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
432
Steve Naroff71c0a952007-11-13 23:01:27 +0000433 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
434 CatDecl->getInstanceMethods());
435 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
436 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000437 // Lastly, comment out the @end.
438 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
439}
440
Steve Naroff752d6ef2007-10-30 16:42:30 +0000441void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000442 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000443
Steve Naroff752d6ef2007-10-30 16:42:30 +0000444 SourceLocation LocStart = PDecl->getLocStart();
445
446 // FIXME: handle protocol headers that are declared across multiple lines.
447 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
448
Steve Naroff71c0a952007-11-13 23:01:27 +0000449 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
450 PDecl->getInstanceMethods());
451 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
452 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000453 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000454 SourceLocation LocEnd = PDecl->getAtEndLoc();
455 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000456
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000457 // Must comment out @optional/@required
458 const char *startBuf = SM->getCharacterData(LocStart);
459 const char *endBuf = SM->getCharacterData(LocEnd);
460 for (const char *p = startBuf; p < endBuf; p++) {
461 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
462 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000463 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000464 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
465 CommentedOptional.c_str(), CommentedOptional.size());
466
467 }
468 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
469 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000470 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000471 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
472 CommentedRequired.c_str(), CommentedRequired.size());
473
474 }
475 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000476}
477
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000478void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
479 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000480 if (LocStart.isInvalid())
481 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000482 // FIXME: handle forward protocol that are declared across multiple lines.
483 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
484}
485
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000486void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
487 std::string &ResultStr) {
488 ResultStr += "\nstatic ";
489 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000490 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000491
492 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000493 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000494
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000495 if (OMD->isInstance())
496 NameStr += "_I_";
497 else
498 NameStr += "_C_";
499
500 NameStr += OMD->getClassInterface()->getName();
501 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000502
503 NamedDecl *MethodContext = OMD->getMethodContext();
504 if (ObjcCategoryImplDecl *CID =
505 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000506 NameStr += CID->getName();
507 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000508 }
509 // Append selector names, replacing ':' with '_'
510 const char *selName = OMD->getSelector().getName().c_str();
511 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000512 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000513 else {
514 std::string selString = OMD->getSelector().getName();
515 int len = selString.size();
516 for (int i = 0; i < len; i++)
517 if (selString[i] == ':')
518 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000519 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000520 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000521 // Remember this name for metadata emission
522 MethodInternalNames[OMD] = NameStr;
523 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000524
525 // Rewrite arguments
526 ResultStr += "(";
527
528 // invisible arguments
529 if (OMD->isInstance()) {
530 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
531 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000532 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
533 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000534 ResultStr += selfTy.getAsString();
535 }
536 else
537 ResultStr += Context->getObjcIdType().getAsString();
538
539 ResultStr += " self, ";
540 ResultStr += Context->getObjcSelType().getAsString();
541 ResultStr += " _cmd";
542
543 // Method arguments.
544 for (int i = 0; i < OMD->getNumParams(); i++) {
545 ParmVarDecl *PDecl = OMD->getParamDecl(i);
546 ResultStr += ", ";
547 ResultStr += PDecl->getType().getAsString();
548 ResultStr += " ";
549 ResultStr += PDecl->getName();
550 }
551 ResultStr += ")";
552
553}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000554void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
555 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
556 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000557
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000558 if (IMD)
559 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
560 else
561 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000562
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000563 int numMethods = IMD ? IMD->getNumInstanceMethods()
564 : CID->getNumInstanceMethods();
565
566 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000567 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000568 ObjcMethodDecl *OMD;
569 if (IMD)
570 OMD = IMD->getInstanceMethods()[i];
571 else
572 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000573 RewriteObjcMethodDecl(OMD, ResultStr);
574 SourceLocation LocStart = OMD->getLocStart();
575 SourceLocation LocEnd = OMD->getBody()->getLocStart();
576
577 const char *startBuf = SM->getCharacterData(LocStart);
578 const char *endBuf = SM->getCharacterData(LocEnd);
579 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
580 ResultStr.c_str(), ResultStr.size());
581 }
582
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000583 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
584 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000585 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000586 ObjcMethodDecl *OMD;
587 if (IMD)
588 OMD = IMD->getClassMethods()[i];
589 else
590 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000591 RewriteObjcMethodDecl(OMD, ResultStr);
592 SourceLocation LocStart = OMD->getLocStart();
593 SourceLocation LocEnd = OMD->getBody()->getLocStart();
594
595 const char *startBuf = SM->getCharacterData(LocStart);
596 const char *endBuf = SM->getCharacterData(LocEnd);
597 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
598 ResultStr.c_str(), ResultStr.size());
599 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000600 if (IMD)
601 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
602 else
603 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000604}
605
Steve Naroffbef11852007-10-26 20:53:56 +0000606void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000607 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000608 if (!ObjcForwardDecls.count(ClassDecl)) {
609 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000610 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000611 ResultStr += ClassDecl->getName();
612 ResultStr += "\n";
613 ResultStr += "#define _REWRITER_typedef_";
614 ResultStr += ClassDecl->getName();
615 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000616 ResultStr += "typedef struct ";
617 ResultStr += ClassDecl->getName();
618 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000619 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000620 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000621
622 // Mark this typedef as having been generated.
623 ObjcForwardDecls.insert(ClassDecl);
624 }
Steve Narofff908a872007-10-30 02:23:23 +0000625 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
626
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000627 RewriteProperties(ClassDecl->getNumPropertyDecl(),
628 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000629 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
630 ClassDecl->getInstanceMethods());
631 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
632 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000633
Steve Naroff2feac5e2007-10-30 03:43:13 +0000634 // Lastly, comment out the @end.
635 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000636}
637
Steve Naroff7e3411b2007-11-15 02:58:25 +0000638Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
639 ObjcIvarDecl *D = IV->getDecl();
640 if (IV->isFreeIvar()) {
641 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
642 IV->getLocation());
643 Rewrite.ReplaceStmt(IV, Replacement);
644 delete IV;
645 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000646 } else {
647 if (CurMethodDecl) {
648 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
649 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
650 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
651 IdentifierInfo *II = intT->getDecl()->getIdentifier();
652 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
653 II, 0);
654 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
655
656 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
657 // Don't forget the parens to enforce the proper binding.
658 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
659 Rewrite.ReplaceStmt(IV->getBase(), PE);
660 delete IV->getBase();
661 return PE;
662 }
663 }
664 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000665 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000666 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000667}
668
Chris Lattnerf04da132007-10-24 17:06:59 +0000669//===----------------------------------------------------------------------===//
670// Function Body / Expression rewriting
671//===----------------------------------------------------------------------===//
672
Steve Narofff3473a72007-11-09 15:20:18 +0000673Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000674 // Otherwise, just rewrite all children.
675 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
676 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000677 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000678 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000679 if (newStmt)
680 *CI = newStmt;
681 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000682
683 // Handle specific things.
684 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
685 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000686
687 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
688 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000689
690 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
691 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000692
693 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
694 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000695
Steve Naroff934f2762007-10-24 22:48:43 +0000696 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
697 // Before we rewrite it, put the original message expression in a comment.
698 SourceLocation startLoc = MessExpr->getLocStart();
699 SourceLocation endLoc = MessExpr->getLocEnd();
700
701 const char *startBuf = SM->getCharacterData(startLoc);
702 const char *endBuf = SM->getCharacterData(endLoc);
703
704 std::string messString;
705 messString += "// ";
706 messString.append(startBuf, endBuf-startBuf+1);
707 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000708
Steve Naroff934f2762007-10-24 22:48:43 +0000709 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
710 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
711 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000712 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000713 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000714 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000715
716 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
717 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000718
719 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
720 return RewriteObjcThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000721
722 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
723 return RewriteObjCProtocolExpr(ProtocolExp);
Steve Naroff874e2322007-11-15 10:28:18 +0000724#if 0
725 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
726 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
727 // Get the new text.
728 std::ostringstream Buf;
729 Replacement->printPretty(Buf);
730 const std::string &Str = Buf.str();
731
732 printf("CAST = %s\n", &Str[0]);
733 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
734 delete S;
735 return Replacement;
736 }
737#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000738 // Return this stmt unmodified.
739 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000740}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000741
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000742Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000743 // Get the start location and compute the semi location.
744 SourceLocation startLoc = S->getLocStart();
745 const char *startBuf = SM->getCharacterData(startLoc);
746
747 assert((*startBuf == '@') && "bogus @try location");
748
749 std::string buf;
750 // declare a new scope with two variables, _stack and _rethrow.
751 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
752 buf += "int buf[18/*32-bit i386*/];\n";
753 buf += "char *pointers[4];} _stack;\n";
754 buf += "id volatile _rethrow = 0;\n";
755 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000756 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000757
758 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
759
760 startLoc = S->getTryBody()->getLocEnd();
761 startBuf = SM->getCharacterData(startLoc);
762
763 assert((*startBuf == '}') && "bogus @try block");
764
765 SourceLocation lastCurlyLoc = startLoc;
766
767 startLoc = startLoc.getFileLocWithOffset(1);
768 buf = " /* @catch begin */ else {\n";
769 buf += " id _caught = objc_exception_extract(&_stack);\n";
770 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000771 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000772 buf += " _rethrow = objc_exception_extract(&_stack);\n";
773 buf += " else { /* @catch continue */";
774
Chris Lattner28d1fe82007-11-08 04:41:51 +0000775 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000776
777 bool sawIdTypedCatch = false;
778 Stmt *lastCatchBody = 0;
779 ObjcAtCatchStmt *catchList = S->getCatchStmts();
780 while (catchList) {
781 Stmt *catchStmt = catchList->getCatchParamStmt();
782
783 if (catchList == S->getCatchStmts())
784 buf = "if ("; // we are generating code for the first catch clause
785 else
786 buf = "else if (";
787 startLoc = catchList->getLocStart();
788 startBuf = SM->getCharacterData(startLoc);
789
790 assert((*startBuf == '@') && "bogus @catch location");
791
792 const char *lParenLoc = strchr(startBuf, '(');
793
794 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
795 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
796 if (t == Context->getObjcIdType()) {
797 buf += "1) { ";
798 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
799 buf.c_str(), buf.size());
800 sawIdTypedCatch = true;
801 } else if (const PointerType *pType = t->getAsPointerType()) {
802 ObjcInterfaceType *cls; // Should be a pointer to a class.
803
804 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
805 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000806 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000807 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000808 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000809 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
810 buf.c_str(), buf.size());
811 }
812 }
813 // Now rewrite the body...
814 lastCatchBody = catchList->getCatchBody();
815 SourceLocation rParenLoc = catchList->getRParenLoc();
816 SourceLocation bodyLoc = lastCatchBody->getLocStart();
817 const char *bodyBuf = SM->getCharacterData(bodyLoc);
818 const char *rParenBuf = SM->getCharacterData(rParenLoc);
819 assert((*rParenBuf == ')') && "bogus @catch paren location");
820 assert((*bodyBuf == '{') && "bogus @catch body location");
821
822 buf = " = _caught;";
823 // Here we replace ") {" with "= _caught;" (which initializes and
824 // declares the @catch parameter).
825 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
826 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000827 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000828 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000829 }
Steve Naroff75730982007-11-07 04:08:17 +0000830 catchList = catchList->getNextCatchStmt();
831 }
832 // Complete the catch list...
833 if (lastCatchBody) {
834 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
835 const char *bodyBuf = SM->getCharacterData(bodyLoc);
836 assert((*bodyBuf == '}') && "bogus @catch body location");
837 bodyLoc = bodyLoc.getFileLocWithOffset(1);
838 buf = " } } /* @catch end */\n";
839
Chris Lattner28d1fe82007-11-08 04:41:51 +0000840 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000841
842 // Set lastCurlyLoc
843 lastCurlyLoc = lastCatchBody->getLocEnd();
844 }
845 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
846 startLoc = finalStmt->getLocStart();
847 startBuf = SM->getCharacterData(startLoc);
848 assert((*startBuf == '@') && "bogus @finally start");
849
850 buf = "/* @finally */";
851 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
852
853 Stmt *body = finalStmt->getFinallyBody();
854 SourceLocation startLoc = body->getLocStart();
855 SourceLocation endLoc = body->getLocEnd();
856 const char *startBuf = SM->getCharacterData(startLoc);
857 const char *endBuf = SM->getCharacterData(endLoc);
858 assert((*startBuf == '{') && "bogus @finally body location");
859 assert((*endBuf == '}') && "bogus @finally body location");
860
861 startLoc = startLoc.getFileLocWithOffset(1);
862 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000863 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000864 endLoc = endLoc.getFileLocWithOffset(-1);
865 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000866 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000867
868 // Set lastCurlyLoc
869 lastCurlyLoc = body->getLocEnd();
870 }
871 // Now emit the final closing curly brace...
872 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
873 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000874 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000875 return 0;
876}
877
878Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
879 return 0;
880}
881
882Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
883 return 0;
884}
885
Steve Naroff2bd03922007-11-07 15:32:26 +0000886// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
887// the throw expression is typically a message expression that's already
888// been rewritten! (which implies the SourceLocation's are invalid).
889Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
890 // Get the start location and compute the semi location.
891 SourceLocation startLoc = S->getLocStart();
892 const char *startBuf = SM->getCharacterData(startLoc);
893
894 assert((*startBuf == '@') && "bogus @throw location");
895
896 std::string buf;
897 /* void objc_exception_throw(id) __attribute__((noreturn)); */
898 buf = "objc_exception_throw(";
899 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
900 const char *semiBuf = strchr(startBuf, ';');
901 assert((*semiBuf == ';') && "@throw: can't find ';'");
902 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
903 buf = ");";
904 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
905 return 0;
906}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000907
Chris Lattnere64b7772007-10-24 16:57:36 +0000908Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000909 // Create a new string expression.
910 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000911 std::string StrEncoding;
912 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
913 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
914 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000915 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +0000916 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
917 // replacement failed.
Chris Lattner182745a2007-12-02 01:09:57 +0000918 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
919 "rewriter could not replace sub-expression due to macros");
920 SourceRange Range = Exp->getSourceRange();
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000921 Diags.Report(Exp->getAtLoc(), DiagID, Context->getSourceManager(),
922 0, 0, &Range, 1);
Chris Lattner182745a2007-12-02 01:09:57 +0000923 delete Replacement;
Chris Lattnere365c502007-11-30 22:25:36 +0000924 return Exp;
925 }
926
Chris Lattner07506182007-11-30 22:53:43 +0000927 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +0000928 delete Exp;
929 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000930}
931
Steve Naroffb42f8412007-11-05 14:50:49 +0000932Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
933 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
934 // Create a call to sel_registerName("selName").
935 llvm::SmallVector<Expr*, 8> SelExprs;
936 QualType argType = Context->getPointerType(Context->CharTy);
937 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
938 Exp->getSelector().getName().size(),
939 false, argType, SourceLocation(),
940 SourceLocation()));
941 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
942 &SelExprs[0], SelExprs.size());
943 Rewrite.ReplaceStmt(Exp, SelExp);
944 delete Exp;
945 return SelExp;
946}
947
Steve Naroff934f2762007-10-24 22:48:43 +0000948CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
949 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000950 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000951 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000952
953 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000954 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000955
956 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000957 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000958 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
959
960 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000961
Steve Naroff934f2762007-10-24 22:48:43 +0000962 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
963}
964
Steve Naroffd5255f52007-11-01 13:24:47 +0000965static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
966 const char *&startRef, const char *&endRef) {
967 while (startBuf < endBuf) {
968 if (*startBuf == '<')
969 startRef = startBuf; // mark the start.
970 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000971 if (startRef && *startRef == '<') {
972 endRef = startBuf; // mark the end.
973 return true;
974 }
975 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000976 }
977 startBuf++;
978 }
979 return false;
980}
981
Fariborz Jahanian61477f72007-12-11 22:50:14 +0000982static void scanToNextArgument(const char *&argRef) {
983 int angle = 0;
984 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
985 if (*argRef == '<')
986 angle++;
987 else if (*argRef == '>')
988 angle--;
989 argRef++;
990 }
991 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
992}
Steve Naroffd5255f52007-11-01 13:24:47 +0000993bool RewriteTest::needToScanForQualifiers(QualType T) {
994 // FIXME: we don't currently represent "id <Protocol>" in the type system.
995 if (T == Context->getObjcIdType())
996 return true;
997
998 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000999 Type *pointeeType = pType->getPointeeType().getTypePtr();
1000 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
1001 return true; // we have "Class <Protocol> *".
1002 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001003 return false;
1004}
1005
Fariborz Jahaniane66894c2007-12-11 19:56:36 +00001006void RewriteTest::RewriteObjcQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001007 SourceLocation Loc;
1008 QualType Type;
1009 const FunctionTypeProto *proto = 0;
1010 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1011 Loc = VD->getLocation();
1012 Type = VD->getType();
1013 }
1014 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1015 Loc = FD->getLocation();
1016 // Check for ObjC 'id' and class types that have been adorned with protocol
1017 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1018 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1019 assert(funcType && "missing function type");
1020 proto = dyn_cast<FunctionTypeProto>(funcType);
1021 if (!proto)
1022 return;
1023 Type = proto->getResultType();
1024 }
1025 else
1026 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001027
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001028 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001029 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001030
1031 const char *endBuf = SM->getCharacterData(Loc);
1032 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001033 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001034 startBuf--; // scan backward (from the decl location) for return type.
1035 const char *startRef = 0, *endRef = 0;
1036 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1037 // Get the locations of the startRef, endRef.
1038 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1039 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1040 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001041 Rewrite.InsertText(LessLoc, "/*", 2);
1042 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001043 }
1044 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001045 if (!proto)
1046 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001047 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001048 const char *startBuf = SM->getCharacterData(Loc);
1049 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001050 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1051 if (needToScanForQualifiers(proto->getArgType(i))) {
1052 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001053
Steve Naroffd5255f52007-11-01 13:24:47 +00001054 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001055 // scan forward (from the decl location) for argument types.
1056 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001057 const char *startRef = 0, *endRef = 0;
1058 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1059 // Get the locations of the startRef, endRef.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001060 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startFuncBuf);
1061 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001062 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001063 Rewrite.InsertText(LessLoc, "/*", 2);
1064 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001065 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001066 startBuf = ++endBuf;
1067 }
1068 else {
1069 while (*startBuf != ')' && *startBuf != ',')
1070 startBuf++; // scan forward (from the decl location) for argument types.
1071 startBuf++;
1072 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001073 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001074}
1075
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001076// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1077void RewriteTest::SynthSelGetUidFunctionDecl() {
1078 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1079 llvm::SmallVector<QualType, 16> ArgTys;
1080 ArgTys.push_back(Context->getPointerType(
1081 Context->CharTy.getQualifiedType(QualType::Const)));
1082 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1083 &ArgTys[0], ArgTys.size(),
1084 false /*isVariadic*/);
1085 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1086 SelGetUidIdent, getFuncType,
1087 FunctionDecl::Extern, false, 0);
1088}
1089
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001090// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1091void RewriteTest::SynthGetProtocolFunctionDecl() {
1092 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1093 llvm::SmallVector<QualType, 16> ArgTys;
1094 ArgTys.push_back(Context->getPointerType(
1095 Context->CharTy.getQualifiedType(QualType::Const)));
1096 QualType getFuncType = Context->getFunctionType(Context->getObjcProtoType(),
1097 &ArgTys[0], ArgTys.size(),
1098 false /*isVariadic*/);
1099 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1100 SelGetProtoIdent, getFuncType,
1101 FunctionDecl::Extern, false, 0);
1102}
1103
Steve Naroff09b266e2007-10-30 23:14:51 +00001104void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1105 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001106 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001107 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001108 return;
1109 }
Fariborz Jahaniane66894c2007-12-11 19:56:36 +00001110 RewriteObjcQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001111}
1112
1113// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1114void RewriteTest::SynthMsgSendFunctionDecl() {
1115 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1116 llvm::SmallVector<QualType, 16> ArgTys;
1117 QualType argT = Context->getObjcIdType();
1118 assert(!argT.isNull() && "Can't find 'id' type");
1119 ArgTys.push_back(argT);
1120 argT = Context->getObjcSelType();
1121 assert(!argT.isNull() && "Can't find 'SEL' type");
1122 ArgTys.push_back(argT);
1123 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1124 &ArgTys[0], ArgTys.size(),
1125 true /*isVariadic*/);
1126 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1127 msgSendIdent, msgSendType,
1128 FunctionDecl::Extern, false, 0);
1129}
1130
Steve Naroff874e2322007-11-15 10:28:18 +00001131// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1132void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1133 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1134 llvm::SmallVector<QualType, 16> ArgTys;
1135 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1136 &Context->Idents.get("objc_super"), 0);
1137 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1138 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1139 ArgTys.push_back(argT);
1140 argT = Context->getObjcSelType();
1141 assert(!argT.isNull() && "Can't find 'SEL' type");
1142 ArgTys.push_back(argT);
1143 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1144 &ArgTys[0], ArgTys.size(),
1145 true /*isVariadic*/);
1146 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1147 msgSendIdent, msgSendType,
1148 FunctionDecl::Extern, false, 0);
1149}
1150
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001151// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1152void RewriteTest::SynthMsgSendStretFunctionDecl() {
1153 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1154 llvm::SmallVector<QualType, 16> ArgTys;
1155 QualType argT = Context->getObjcIdType();
1156 assert(!argT.isNull() && "Can't find 'id' type");
1157 ArgTys.push_back(argT);
1158 argT = Context->getObjcSelType();
1159 assert(!argT.isNull() && "Can't find 'SEL' type");
1160 ArgTys.push_back(argT);
1161 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1162 &ArgTys[0], ArgTys.size(),
1163 true /*isVariadic*/);
1164 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1165 msgSendIdent, msgSendType,
1166 FunctionDecl::Extern, false, 0);
1167}
1168
1169// SynthMsgSendSuperStretFunctionDecl -
1170// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1171void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1172 IdentifierInfo *msgSendIdent =
1173 &Context->Idents.get("objc_msgSendSuper_stret");
1174 llvm::SmallVector<QualType, 16> ArgTys;
1175 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1176 &Context->Idents.get("objc_super"), 0);
1177 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1178 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1179 ArgTys.push_back(argT);
1180 argT = Context->getObjcSelType();
1181 assert(!argT.isNull() && "Can't find 'SEL' type");
1182 ArgTys.push_back(argT);
1183 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1184 &ArgTys[0], ArgTys.size(),
1185 true /*isVariadic*/);
1186 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1187 msgSendIdent, msgSendType,
1188 FunctionDecl::Extern, false, 0);
1189}
1190
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001191// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1192void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1193 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1194 llvm::SmallVector<QualType, 16> ArgTys;
1195 QualType argT = Context->getObjcIdType();
1196 assert(!argT.isNull() && "Can't find 'id' type");
1197 ArgTys.push_back(argT);
1198 argT = Context->getObjcSelType();
1199 assert(!argT.isNull() && "Can't find 'SEL' type");
1200 ArgTys.push_back(argT);
1201 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1202 &ArgTys[0], ArgTys.size(),
1203 true /*isVariadic*/);
1204 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1205 msgSendIdent, msgSendType,
1206 FunctionDecl::Extern, false, 0);
1207}
1208
Steve Naroff09b266e2007-10-30 23:14:51 +00001209// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1210void RewriteTest::SynthGetClassFunctionDecl() {
1211 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1212 llvm::SmallVector<QualType, 16> ArgTys;
1213 ArgTys.push_back(Context->getPointerType(
1214 Context->CharTy.getQualifiedType(QualType::Const)));
1215 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1216 &ArgTys[0], ArgTys.size(),
1217 false /*isVariadic*/);
1218 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1219 getClassIdent, getClassType,
1220 FunctionDecl::Extern, false, 0);
1221}
1222
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001223// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1224void RewriteTest::SynthGetMetaClassFunctionDecl() {
1225 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1226 llvm::SmallVector<QualType, 16> ArgTys;
1227 ArgTys.push_back(Context->getPointerType(
1228 Context->CharTy.getQualifiedType(QualType::Const)));
1229 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1230 &ArgTys[0], ArgTys.size(),
1231 false /*isVariadic*/);
1232 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1233 getClassIdent, getClassType,
1234 FunctionDecl::Extern, false, 0);
1235}
1236
Steve Naroff96984642007-11-08 14:30:50 +00001237// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1238void RewriteTest::SynthCFStringFunctionDecl() {
1239 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1240 llvm::SmallVector<QualType, 16> ArgTys;
1241 ArgTys.push_back(Context->getPointerType(
1242 Context->CharTy.getQualifiedType(QualType::Const)));
1243 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1244 &ArgTys[0], ArgTys.size(),
1245 false /*isVariadic*/);
1246 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1247 getClassIdent, getClassType,
1248 FunctionDecl::Extern, false, 0);
1249}
1250
Steve Naroffbeaf2992007-11-03 11:27:19 +00001251Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001252#if 1
1253 // This rewrite is specific to GCC, which has builtin support for CFString.
1254 if (!CFStringFunctionDecl)
1255 SynthCFStringFunctionDecl();
1256 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1257 llvm::SmallVector<Expr*, 8> StrExpr;
1258 StrExpr.push_back(Exp->getString());
1259 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1260 &StrExpr[0], StrExpr.size());
1261 // cast to NSConstantString *
1262 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1263 Rewrite.ReplaceStmt(Exp, cast);
1264 delete Exp;
1265 return cast;
1266#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001267 assert(ConstantStringClassReference && "Can't find constant string reference");
1268 llvm::SmallVector<Expr*, 4> InitExprs;
1269
1270 // Synthesize "(Class)&_NSConstantStringClassReference"
1271 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1272 ConstantStringClassReference->getType(),
1273 SourceLocation());
1274 QualType expType = Context->getPointerType(ClsRef->getType());
1275 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1276 expType, SourceLocation());
1277 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1278 SourceLocation());
1279 InitExprs.push_back(cast); // set the 'isa'.
1280 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1281 unsigned IntSize = static_cast<unsigned>(
1282 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1283 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1284 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1285 Exp->getLocStart());
1286 InitExprs.push_back(len); // set "int numBytes".
1287
1288 // struct NSConstantString
1289 QualType CFConstantStrType = Context->getCFConstantStringType();
1290 // (struct NSConstantString) { <exprs from above> }
1291 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1292 &InitExprs[0], InitExprs.size(),
1293 SourceLocation());
1294 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1295 // struct NSConstantString *
1296 expType = Context->getPointerType(StrRep->getType());
1297 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1298 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001299 // cast to NSConstantString *
1300 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001301 Rewrite.ReplaceStmt(Exp, cast);
1302 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001303 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001304#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001305}
1306
Steve Naroff874e2322007-11-15 10:28:18 +00001307ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001308 // check if we are sending a message to 'super'
1309 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001310 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1311 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1312 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1313 if (!strcmp(PVD->getName(), "self")) {
1314 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1315 if (ObjcInterfaceType *IT =
1316 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1317 if (IT->getDecl() ==
1318 CurMethodDecl->getClassInterface()->getSuperClass())
1319 return IT->getDecl();
1320 }
1321 }
1322 }
1323 }
1324 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001325 }
Steve Naroff874e2322007-11-15 10:28:18 +00001326 }
1327 return 0;
1328}
1329
1330// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1331QualType RewriteTest::getSuperStructType() {
1332 if (!SuperStructDecl) {
1333 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1334 &Context->Idents.get("objc_super"), 0);
1335 QualType FieldTypes[2];
1336
1337 // struct objc_object *receiver;
1338 FieldTypes[0] = Context->getObjcIdType();
1339 // struct objc_class *super;
1340 FieldTypes[1] = Context->getObjcClassType();
1341 // Create fields
1342 FieldDecl *FieldDecls[2];
1343
1344 for (unsigned i = 0; i < 2; ++i)
1345 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1346
1347 SuperStructDecl->defineBody(FieldDecls, 4);
1348 }
1349 return Context->getTagDeclType(SuperStructDecl);
1350}
1351
Steve Naroff934f2762007-10-24 22:48:43 +00001352Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001353 if (!SelGetUidFunctionDecl)
1354 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001355 if (!MsgSendFunctionDecl)
1356 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001357 if (!MsgSendSuperFunctionDecl)
1358 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001359 if (!MsgSendStretFunctionDecl)
1360 SynthMsgSendStretFunctionDecl();
1361 if (!MsgSendSuperStretFunctionDecl)
1362 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001363 if (!MsgSendFpretFunctionDecl)
1364 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001365 if (!GetClassFunctionDecl)
1366 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001367 if (!GetMetaClassFunctionDecl)
1368 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001369
Steve Naroff874e2322007-11-15 10:28:18 +00001370 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001371 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1372 // May need to use objc_msgSend_stret() as well.
1373 FunctionDecl *MsgSendStretFlavor = 0;
1374 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1375 QualType resultType = mDecl->getResultType();
1376 if (resultType.getCanonicalType()->isStructureType()
1377 || resultType.getCanonicalType()->isUnionType())
1378 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001379 else if (resultType.getCanonicalType()->isRealFloatingType())
1380 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001381 }
Steve Naroff874e2322007-11-15 10:28:18 +00001382
Steve Naroff934f2762007-10-24 22:48:43 +00001383 // Synthesize a call to objc_msgSend().
1384 llvm::SmallVector<Expr*, 8> MsgExprs;
1385 IdentifierInfo *clsName = Exp->getClassName();
1386
1387 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1388 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001389 if (!strcmp(clsName->getName(), "super")) {
1390 MsgSendFlavor = MsgSendSuperFunctionDecl;
1391 if (MsgSendStretFlavor)
1392 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1393 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1394
1395 ObjcInterfaceDecl *SuperDecl =
1396 CurMethodDecl->getClassInterface()->getSuperClass();
1397
1398 llvm::SmallVector<Expr*, 4> InitExprs;
1399
1400 // set the receiver to self, the first argument to all methods.
1401 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
1402 Context->getObjcIdType(),
1403 SourceLocation()));
1404 llvm::SmallVector<Expr*, 8> ClsExprs;
1405 QualType argType = Context->getPointerType(Context->CharTy);
1406 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1407 SuperDecl->getIdentifier()->getLength(),
1408 false, argType, SourceLocation(),
1409 SourceLocation()));
1410 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1411 &ClsExprs[0],
1412 ClsExprs.size());
1413 // To turn off a warning, type-cast to 'id'
1414 InitExprs.push_back(
1415 new CastExpr(Context->getObjcIdType(),
1416 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1417 // struct objc_super
1418 QualType superType = getSuperStructType();
1419 // (struct objc_super) { <exprs from above> }
1420 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1421 &InitExprs[0], InitExprs.size(),
1422 SourceLocation());
1423 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1424 // struct objc_super *
1425 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1426 Context->getPointerType(SuperRep->getType()),
1427 SourceLocation());
1428 MsgExprs.push_back(Unop);
1429 } else {
1430 llvm::SmallVector<Expr*, 8> ClsExprs;
1431 QualType argType = Context->getPointerType(Context->CharTy);
1432 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1433 clsName->getLength(),
1434 false, argType, SourceLocation(),
1435 SourceLocation()));
1436 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1437 &ClsExprs[0],
1438 ClsExprs.size());
1439 MsgExprs.push_back(Cls);
1440 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001441 } else { // instance message.
1442 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001443
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001444 if (ObjcInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001445 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001446 if (MsgSendStretFlavor)
1447 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001448 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1449
1450 llvm::SmallVector<Expr*, 4> InitExprs;
1451
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001452 InitExprs.push_back(
1453 new CastExpr(Context->getObjcIdType(),
1454 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001455
1456 llvm::SmallVector<Expr*, 8> ClsExprs;
1457 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001458 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1459 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001460 false, argType, SourceLocation(),
1461 SourceLocation()));
1462 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001463 &ClsExprs[0],
1464 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001465 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001466 InitExprs.push_back(
Fariborz Jahanian71274312007-12-05 17:29:46 +00001467 new CastExpr(Context->getObjcIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001468 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001469 // struct objc_super
1470 QualType superType = getSuperStructType();
1471 // (struct objc_super) { <exprs from above> }
1472 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1473 &InitExprs[0], InitExprs.size(),
1474 SourceLocation());
1475 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1476 // struct objc_super *
1477 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1478 Context->getPointerType(SuperRep->getType()),
1479 SourceLocation());
1480 MsgExprs.push_back(Unop);
1481 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001482 // Remove all type-casts because it may contain objc-style types; e.g.
1483 // Foo<Proto> *.
1484 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1485 recExpr = CE->getSubExpr();
Steve Naroff874e2322007-11-15 10:28:18 +00001486 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1487 MsgExprs.push_back(recExpr);
1488 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001489 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001490 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001491 llvm::SmallVector<Expr*, 8> SelExprs;
1492 QualType argType = Context->getPointerType(Context->CharTy);
1493 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1494 Exp->getSelector().getName().size(),
1495 false, argType, SourceLocation(),
1496 SourceLocation()));
1497 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1498 &SelExprs[0], SelExprs.size());
1499 MsgExprs.push_back(SelExp);
1500
1501 // Now push any user supplied arguments.
1502 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001503 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001504 // Make all implicit casts explicit...ICE comes in handy:-)
1505 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1506 // Reuse the ICE type, it is exactly what the doctor ordered.
1507 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1508 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001509 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001510 // We've transferred the ownership to MsgExprs. Null out the argument in
1511 // the original expression, since we will delete it below.
1512 Exp->setArg(i, 0);
1513 }
Steve Naroffab972d32007-11-04 22:37:50 +00001514 // Generate the funky cast.
1515 CastExpr *cast;
1516 llvm::SmallVector<QualType, 8> ArgTypes;
1517 QualType returnType;
1518
1519 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001520 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1521 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1522 else
1523 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001524 ArgTypes.push_back(Context->getObjcSelType());
1525 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1526 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001527 for (int i = 0; i < mDecl->getNumParams(); i++) {
1528 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001529 ArgTypes.push_back(t);
1530 }
Steve Naroffab972d32007-11-04 22:37:50 +00001531 returnType = mDecl->getResultType();
1532 } else {
1533 returnType = Context->getObjcIdType();
1534 }
1535 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001536 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001537
1538 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001539 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1540 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001541
1542 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1543 // If we don't do this cast, we get the following bizarre warning/note:
1544 // xx.m:13: warning: function called through a non-compatible type
1545 // xx.m:13: note: if this code is reached, the program will abort
1546 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1547 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001548
Steve Naroffab972d32007-11-04 22:37:50 +00001549 // Now do the "normal" pointer to function cast.
1550 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001551 &ArgTypes[0], ArgTypes.size(),
1552 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001553 castType = Context->getPointerType(castType);
1554 cast = new CastExpr(castType, cast, SourceLocation());
1555
1556 // Don't forget the parens to enforce the proper binding.
1557 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1558
1559 const FunctionType *FT = msgSendType->getAsFunctionType();
1560 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1561 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001562 if (MsgSendStretFlavor) {
1563 // We have the method which returns a struct/union. Must also generate
1564 // call to objc_msgSend_stret and hang both varieties on a conditional
1565 // expression which dictate which one to envoke depending on size of
1566 // method's return type.
1567
1568 // Create a reference to the objc_msgSend_stret() declaration.
1569 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1570 SourceLocation());
1571 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1572 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1573 SourceLocation());
1574 // Now do the "normal" pointer to function cast.
1575 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001576 &ArgTypes[0], ArgTypes.size(),
1577 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001578 castType = Context->getPointerType(castType);
1579 cast = new CastExpr(castType, cast, SourceLocation());
1580
1581 // Don't forget the parens to enforce the proper binding.
1582 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1583
1584 FT = msgSendType->getAsFunctionType();
1585 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1586 FT->getResultType(), SourceLocation());
1587
1588 // Build sizeof(returnType)
1589 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1590 returnType, Context->getSizeType(),
1591 SourceLocation(), SourceLocation());
1592 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1593 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1594 // For X86 it is more complicated and some kind of target specific routine
1595 // is needed to decide what to do.
1596 unsigned IntSize = static_cast<unsigned>(
1597 Context->getTypeSize(Context->IntTy, SourceLocation()));
1598
1599 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1600 Context->IntTy,
1601 SourceLocation());
1602 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1603 BinaryOperator::LE,
1604 Context->IntTy,
1605 SourceLocation());
1606 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1607 ConditionalOperator *CondExpr =
1608 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1609 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1610 // Now do the actual rewrite.
1611 Rewrite.ReplaceStmt(Exp, PE);
1612 delete Exp;
1613 return PE;
1614 }
Steve Naroff934f2762007-10-24 22:48:43 +00001615 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001616 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001617
Chris Lattnere64b7772007-10-24 16:57:36 +00001618 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001619 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001620}
1621
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001622/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1623/// call to objc_getProtocol("proto-name").
1624Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1625 if (!GetProtocolFunctionDecl)
1626 SynthGetProtocolFunctionDecl();
1627 // Create a call to objc_getProtocol("ProtocolName").
1628 llvm::SmallVector<Expr*, 8> ProtoExprs;
1629 QualType argType = Context->getPointerType(Context->CharTy);
1630 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1631 strlen(Exp->getProtocol()->getName()),
1632 false, argType, SourceLocation(),
1633 SourceLocation()));
1634 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1635 &ProtoExprs[0],
1636 ProtoExprs.size());
1637 Rewrite.ReplaceStmt(Exp, ProtoExp);
1638 delete Exp;
1639 return ProtoExp;
1640
1641}
1642
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001643/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1644/// an objective-c class with ivars.
1645void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1646 std::string &Result) {
1647 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1648 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001649 // Do not synthesize more than once.
1650 if (ObjcSynthesizedStructs.count(CDecl))
1651 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001652 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001653 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001654 SourceLocation LocStart = CDecl->getLocStart();
1655 SourceLocation LocEnd = CDecl->getLocEnd();
1656
1657 const char *startBuf = SM->getCharacterData(LocStart);
1658 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001659 // If no ivars and no root or if its root, directly or indirectly,
1660 // have no ivars (thus not synthesized) then no need to synthesize this class.
1661 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001662 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1663 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1664 Result.c_str(), Result.size());
1665 return;
1666 }
1667
1668 // FIXME: This has potential of causing problem. If
1669 // SynthesizeObjcInternalStruct is ever called recursively.
1670 Result += "\nstruct ";
1671 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001672
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001673 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001674 const char *cursor = strchr(startBuf, '{');
1675 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001676 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001677
1678 // rewrite the original header *without* disturbing the '{'
1679 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1680 Result.c_str(), Result.size());
1681 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1682 Result = "\n struct ";
1683 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001684 // Note: We don't name the field decl. This simplifies the "codegen" for
1685 // accessing a superclasses instance variables (and is similar to what gcc
1686 // does internally). The unnamed struct field feature is enabled with
1687 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1688 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001689 Result += ";\n";
1690
1691 // insert the super class structure definition.
1692 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1693 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1694 }
1695 cursor++; // past '{'
1696
1697 // Now comment out any visibility specifiers.
1698 while (cursor < endBuf) {
1699 if (*cursor == '@') {
1700 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001701 // Skip whitespace.
1702 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1703 /*scan*/;
1704
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001705 // FIXME: presence of @public, etc. inside comment results in
1706 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001707 if (!strncmp(cursor, "public", strlen("public")) ||
1708 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001709 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001710 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001711 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001712 // FIXME: If there are cases where '<' is used in ivar declaration part
1713 // of user code, then scan the ivar list and use needToScanForQualifiers
1714 // for type checking.
1715 else if (*cursor == '<') {
1716 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1717 Rewrite.InsertText(atLoc, "/* ", 3);
1718 cursor = strchr(cursor, '>');
1719 cursor++;
1720 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1721 Rewrite.InsertText(atLoc, " */", 3);
1722 }
Steve Narofffea763e82007-11-14 19:25:57 +00001723 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001724 }
Steve Narofffea763e82007-11-14 19:25:57 +00001725 // Don't forget to add a ';'!!
1726 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1727 } else { // we don't have any instance variables - insert super struct.
1728 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1729 Result += " {\n struct ";
1730 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001731 // Note: We don't name the field decl. This simplifies the "codegen" for
1732 // accessing a superclasses instance variables (and is similar to what gcc
1733 // does internally). The unnamed struct field feature is enabled with
1734 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1735 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001736 Result += ";\n};\n";
1737 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1738 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001739 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001740 // Mark this struct as having been generated.
1741 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001742 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001743}
1744
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001745// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1746/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001747void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001748 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001749 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001750 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001751 const char *ClassName,
1752 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001753 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001754 if (NumMethods > 0 && !objc_impl_method) {
1755 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001756 SEL _cmd;
1757 char *method_types;
1758 void *_imp;
1759 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001760 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001761 Result += "\nstruct _objc_method {\n";
1762 Result += "\tSEL _cmd;\n";
1763 Result += "\tchar *method_types;\n";
1764 Result += "\tvoid *_imp;\n";
1765 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001766
1767 /* struct _objc_method_list {
1768 struct _objc_method_list *next_method;
1769 int method_count;
1770 struct _objc_method method_list[];
1771 }
1772 */
1773 Result += "\nstruct _objc_method_list {\n";
1774 Result += "\tstruct _objc_method_list *next_method;\n";
1775 Result += "\tint method_count;\n";
1776 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001777 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001778 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001779 // Build _objc_method_list for class's methods if needed
1780 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001781 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001782 Result += prefix;
1783 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1784 Result += "_METHODS_";
1785 Result += ClassName;
1786 Result += " __attribute__ ((section (\"__OBJC, __";
1787 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001788 Result += "_meth\")))= ";
1789 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1790
1791 Result += "\t,{{(SEL)\"";
1792 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001793 std::string MethodTypeString;
1794 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1795 Result += "\", \"";
1796 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001797 Result += "\", ";
1798 Result += MethodInternalNames[Methods[0]];
1799 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001800 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001801 Result += "\t ,{(SEL)\"";
1802 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001803 std::string MethodTypeString;
1804 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1805 Result += "\", \"";
1806 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001807 Result += "\", ";
1808 Result += MethodInternalNames[Methods[i]];
1809 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001810 }
1811 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001812 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001813}
1814
1815/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1816void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1817 int NumProtocols,
1818 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001819 const char *ClassName,
1820 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001821 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001822 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001823 for (int i = 0; i < NumProtocols; i++) {
1824 ObjcProtocolDecl *PDecl = Protocols[i];
1825 // Output struct protocol_methods holder of method selector and type.
1826 if (!objc_protocol_methods &&
1827 (PDecl->getNumInstanceMethods() > 0
1828 || PDecl->getNumClassMethods() > 0)) {
1829 /* struct protocol_methods {
1830 SEL _cmd;
1831 char *method_types;
1832 }
1833 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001834 Result += "\nstruct protocol_methods {\n";
1835 Result += "\tSEL _cmd;\n";
1836 Result += "\tchar *method_types;\n";
1837 Result += "};\n";
1838
1839 /* struct _objc_protocol_method_list {
1840 int protocol_method_count;
1841 struct protocol_methods protocols[];
1842 }
1843 */
1844 Result += "\nstruct _objc_protocol_method_list {\n";
1845 Result += "\tint protocol_method_count;\n";
1846 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001847 objc_protocol_methods = true;
1848 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001849
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001850 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001851 int NumMethods = PDecl->getNumInstanceMethods();
1852 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001853 Result += "\nstatic struct _objc_protocol_method_list "
1854 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1855 Result += PDecl->getName();
1856 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1857 "{\n\t" + utostr(NumMethods) + "\n";
1858
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001859 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001860 Result += "\t,{{(SEL)\"";
1861 Result += Methods[0]->getSelector().getName().c_str();
1862 Result += "\", \"\"}\n";
1863
1864 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001865 Result += "\t ,{(SEL)\"";
1866 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001867 std::string MethodTypeString;
1868 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1869 Result += "\", \"";
1870 Result += MethodTypeString;
1871 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001872 }
1873 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001874 }
1875
1876 // Output class methods declared in this protocol.
1877 NumMethods = PDecl->getNumClassMethods();
1878 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001879 Result += "\nstatic struct _objc_protocol_method_list "
1880 "_OBJC_PROTOCOL_CLASS_METHODS_";
1881 Result += PDecl->getName();
1882 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1883 "{\n\t";
1884 Result += utostr(NumMethods);
1885 Result += "\n";
1886
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001887 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001888 Result += "\t,{{(SEL)\"";
1889 Result += Methods[0]->getSelector().getName().c_str();
1890 Result += "\", \"\"}\n";
1891
1892 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001893 Result += "\t ,{(SEL)\"";
1894 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001895 std::string MethodTypeString;
1896 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1897 Result += "\", \"";
1898 Result += MethodTypeString;
1899 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001900 }
1901 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001902 }
1903 // Output:
1904 /* struct _objc_protocol {
1905 // Objective-C 1.0 extensions
1906 struct _objc_protocol_extension *isa;
1907 char *protocol_name;
1908 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001909 struct _objc_protocol_method_list *instance_methods;
1910 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001911 };
1912 */
1913 static bool objc_protocol = false;
1914 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001915 Result += "\nstruct _objc_protocol {\n";
1916 Result += "\tstruct _objc_protocol_extension *isa;\n";
1917 Result += "\tchar *protocol_name;\n";
1918 Result += "\tstruct _objc_protocol **protocol_list;\n";
1919 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1920 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1921 Result += "};\n";
1922
1923 /* struct _objc_protocol_list {
1924 struct _objc_protocol_list *next;
1925 int protocol_count;
1926 struct _objc_protocol *class_protocols[];
1927 }
1928 */
1929 Result += "\nstruct _objc_protocol_list {\n";
1930 Result += "\tstruct _objc_protocol_list *next;\n";
1931 Result += "\tint protocol_count;\n";
1932 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1933 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001934 objc_protocol = true;
1935 }
1936
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001937 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1938 Result += PDecl->getName();
1939 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1940 "{\n\t0, \"";
1941 Result += PDecl->getName();
1942 Result += "\", 0, ";
1943 if (PDecl->getInstanceMethods() > 0) {
1944 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1945 Result += PDecl->getName();
1946 Result += ", ";
1947 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001948 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001949 Result += "0, ";
1950 if (PDecl->getClassMethods() > 0) {
1951 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1952 Result += PDecl->getName();
1953 Result += "\n";
1954 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001955 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001956 Result += "0\n";
1957 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001958 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001959 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001960 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1961 Result += prefix;
1962 Result += "_PROTOCOLS_";
1963 Result += ClassName;
1964 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1965 "{\n\t0, ";
1966 Result += utostr(NumProtocols);
1967 Result += "\n";
1968
1969 Result += "\t,{&_OBJC_PROTOCOL_";
1970 Result += Protocols[0]->getName();
1971 Result += " \n";
1972
1973 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001974 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001975 Result += "\t ,&_OBJC_PROTOCOL_";
1976 Result += PDecl->getName();
1977 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001978 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001979 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001980 }
1981}
1982
1983/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1984/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001985void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1986 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001987 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1988 // Find category declaration for this implementation.
1989 ObjcCategoryDecl *CDecl;
1990 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1991 CDecl = CDecl->getNextClassCategory())
1992 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1993 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001994
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001995 char *FullCategoryName = (char*)alloca(
1996 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1997 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1998
1999 // Build _objc_method_list for class's instance methods if needed
2000 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
2001 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002002 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002003 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002004
2005 // Build _objc_method_list for class's class methods if needed
2006 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
2007 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002008 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002009 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002010
2011 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002012 // Null CDecl is case of a category implementation with no category interface
2013 if (CDecl)
2014 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2015 CDecl->getNumReferencedProtocols(),
2016 "CATEGORY",
2017 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002018
2019 /* struct _objc_category {
2020 char *category_name;
2021 char *class_name;
2022 struct _objc_method_list *instance_methods;
2023 struct _objc_method_list *class_methods;
2024 struct _objc_protocol_list *protocols;
2025 // Objective-C 1.0 extensions
2026 uint32_t size; // sizeof (struct _objc_category)
2027 struct _objc_property_list *instance_properties; // category's own
2028 // @property decl.
2029 };
2030 */
2031
2032 static bool objc_category = false;
2033 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002034 Result += "\nstruct _objc_category {\n";
2035 Result += "\tchar *category_name;\n";
2036 Result += "\tchar *class_name;\n";
2037 Result += "\tstruct _objc_method_list *instance_methods;\n";
2038 Result += "\tstruct _objc_method_list *class_methods;\n";
2039 Result += "\tstruct _objc_protocol_list *protocols;\n";
2040 Result += "\tunsigned int size;\n";
2041 Result += "\tstruct _objc_property_list *instance_properties;\n";
2042 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002043 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002044 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002045 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2046 Result += FullCategoryName;
2047 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2048 Result += IDecl->getName();
2049 Result += "\"\n\t, \"";
2050 Result += ClassDecl->getName();
2051 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002052
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002053 if (IDecl->getNumInstanceMethods() > 0) {
2054 Result += "\t, (struct _objc_method_list *)"
2055 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2056 Result += FullCategoryName;
2057 Result += "\n";
2058 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002059 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002060 Result += "\t, 0\n";
2061 if (IDecl->getNumClassMethods() > 0) {
2062 Result += "\t, (struct _objc_method_list *)"
2063 "&_OBJC_CATEGORY_CLASS_METHODS_";
2064 Result += FullCategoryName;
2065 Result += "\n";
2066 }
2067 else
2068 Result += "\t, 0\n";
2069
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002070 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002071 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2072 Result += FullCategoryName;
2073 Result += "\n";
2074 }
2075 else
2076 Result += "\t, 0\n";
2077 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002078}
2079
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002080/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2081/// ivar offset.
2082void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
2083 ObjcIvarDecl *ivar,
2084 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002085 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002086 Result += IDecl->getName();
2087 Result += ", ";
2088 Result += ivar->getName();
2089 Result += ")";
2090}
2091
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002092//===----------------------------------------------------------------------===//
2093// Meta Data Emission
2094//===----------------------------------------------------------------------===//
2095
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002096void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
2097 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002098 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
2099
2100 // Build _objc_ivar_list metadata for classes ivars if needed
2101 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2102 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00002103 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002104 // Explictly declared @interface's are already synthesized.
2105 if (CDecl->ImplicitInterfaceDecl()) {
2106 // FIXME: Implementation of a class with no @interface (legacy) doese not
2107 // produce correct synthesis as yet.
2108 SynthesizeObjcInternalStruct(CDecl, Result);
2109 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002110
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002111 if (NumIvars > 0) {
2112 static bool objc_ivar = false;
2113 if (!objc_ivar) {
2114 /* struct _objc_ivar {
2115 char *ivar_name;
2116 char *ivar_type;
2117 int ivar_offset;
2118 };
2119 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002120 Result += "\nstruct _objc_ivar {\n";
2121 Result += "\tchar *ivar_name;\n";
2122 Result += "\tchar *ivar_type;\n";
2123 Result += "\tint ivar_offset;\n";
2124 Result += "};\n";
2125
2126 /* struct _objc_ivar_list {
2127 int ivar_count;
2128 struct _objc_ivar ivar_list[];
2129 };
2130 */
2131 Result += "\nstruct _objc_ivar_list {\n";
2132 Result += "\tint ivar_count;\n";
2133 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002134 objc_ivar = true;
2135 }
2136
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002137 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2138 Result += IDecl->getName();
2139 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2140 "{\n\t";
2141 Result += utostr(NumIvars);
2142 Result += "\n";
2143
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002144 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
2145 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00002146 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002147 Result += "\t,{{\"";
2148 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002149 Result += "\", \"";
2150 std::string StrEncoding;
2151 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
2152 Result += StrEncoding;
2153 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002154 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
2155 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002156 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002157 Result += "\t ,{\"";
2158 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002159 Result += "\", \"";
2160 std::string StrEncoding;
2161 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
2162 Result += StrEncoding;
2163 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002164 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
2165 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002166 }
2167
2168 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002169 }
2170
2171 // Build _objc_method_list for class's instance methods if needed
2172 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
2173 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002174 true,
2175 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002176
2177 // Build _objc_method_list for class's class methods if needed
2178 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002179 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002180 false,
2181 "", IDecl->getName(), Result);
2182
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002183 // Protocols referenced in class declaration?
2184 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2185 CDecl->getNumIntfRefProtocols(),
2186 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002187 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002188
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002189
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002190 // Declaration of class/meta-class metadata
2191 /* struct _objc_class {
2192 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002193 const char *super_class_name;
2194 char *name;
2195 long version;
2196 long info;
2197 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002198 struct _objc_ivar_list *ivars;
2199 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002200 struct objc_cache *cache;
2201 struct objc_protocol_list *protocols;
2202 const char *ivar_layout;
2203 struct _objc_class_ext *ext;
2204 };
2205 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002206 static bool objc_class = false;
2207 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002208 Result += "\nstruct _objc_class {\n";
2209 Result += "\tstruct _objc_class *isa;\n";
2210 Result += "\tconst char *super_class_name;\n";
2211 Result += "\tchar *name;\n";
2212 Result += "\tlong version;\n";
2213 Result += "\tlong info;\n";
2214 Result += "\tlong instance_size;\n";
2215 Result += "\tstruct _objc_ivar_list *ivars;\n";
2216 Result += "\tstruct _objc_method_list *methods;\n";
2217 Result += "\tstruct objc_cache *cache;\n";
2218 Result += "\tstruct _objc_protocol_list *protocols;\n";
2219 Result += "\tconst char *ivar_layout;\n";
2220 Result += "\tstruct _objc_class_ext *ext;\n";
2221 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002222 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002223 }
2224
2225 // Meta-class metadata generation.
2226 ObjcInterfaceDecl *RootClass = 0;
2227 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2228 while (SuperClass) {
2229 RootClass = SuperClass;
2230 SuperClass = SuperClass->getSuperClass();
2231 }
2232 SuperClass = CDecl->getSuperClass();
2233
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002234 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2235 Result += CDecl->getName();
2236 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2237 "{\n\t(struct _objc_class *)\"";
2238 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2239 Result += "\"";
2240
2241 if (SuperClass) {
2242 Result += ", \"";
2243 Result += SuperClass->getName();
2244 Result += "\", \"";
2245 Result += CDecl->getName();
2246 Result += "\"";
2247 }
2248 else {
2249 Result += ", 0, \"";
2250 Result += CDecl->getName();
2251 Result += "\"";
2252 }
Fariborz Jahanian04b38242007-12-04 19:31:56 +00002253 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002254 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002255 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002256 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002257 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002258 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002259 Result += "\n";
2260 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002261 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002262 Result += ", 0\n";
2263 if (CDecl->getNumIntfRefProtocols() > 0) {
2264 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2265 Result += CDecl->getName();
2266 Result += ",0,0\n";
2267 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002268 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002269 Result += "\t,0,0,0,0\n";
2270 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002271
2272 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002273 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2274 Result += CDecl->getName();
2275 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2276 "{\n\t&_OBJC_METACLASS_";
2277 Result += CDecl->getName();
2278 if (SuperClass) {
2279 Result += ", \"";
2280 Result += SuperClass->getName();
2281 Result += "\", \"";
2282 Result += CDecl->getName();
2283 Result += "\"";
2284 }
2285 else {
2286 Result += ", 0, \"";
2287 Result += CDecl->getName();
2288 Result += "\"";
2289 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002290 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002291 Result += ", 0,1";
2292 if (!ObjcSynthesizedStructs.count(CDecl))
2293 Result += ",0";
2294 else {
2295 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002296 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002297 Result += CDecl->getName();
2298 Result += ")";
2299 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002300 if (NumIvars > 0) {
2301 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2302 Result += CDecl->getName();
2303 Result += "\n\t";
2304 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002305 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002306 Result += ",0";
2307 if (IDecl->getNumInstanceMethods() > 0) {
2308 Result += ", &_OBJC_INSTANCE_METHODS_";
2309 Result += CDecl->getName();
2310 Result += ", 0\n\t";
2311 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002312 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002313 Result += ",0,0";
2314 if (CDecl->getNumIntfRefProtocols() > 0) {
2315 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2316 Result += CDecl->getName();
2317 Result += ", 0,0\n";
2318 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002319 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002320 Result += ",0,0,0\n";
2321 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002322}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002323
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002324/// RewriteImplementations - This routine rewrites all method implementations
2325/// and emits meta-data.
2326
2327void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002328 int ClsDefCount = ClassImplementation.size();
2329 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002330
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002331 if (ClsDefCount == 0 && CatDefCount == 0)
2332 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002333 // Rewrite implemented methods
2334 for (int i = 0; i < ClsDefCount; i++)
2335 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002336
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002337 for (int i = 0; i < CatDefCount; i++)
2338 RewriteImplementationDecl(CategoryImplementation[i]);
2339
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002340 // This is needed for use of offsetof
2341 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002342
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002343 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002344 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002345 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002346
2347 // For each implemented category, write out all its meta data.
2348 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002349 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002350
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002351 // Write objc_symtab metadata
2352 /*
2353 struct _objc_symtab
2354 {
2355 long sel_ref_cnt;
2356 SEL *refs;
2357 short cls_def_cnt;
2358 short cat_def_cnt;
2359 void *defs[cls_def_cnt + cat_def_cnt];
2360 };
2361 */
2362
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002363 Result += "\nstruct _objc_symtab {\n";
2364 Result += "\tlong sel_ref_cnt;\n";
2365 Result += "\tSEL *refs;\n";
2366 Result += "\tshort cls_def_cnt;\n";
2367 Result += "\tshort cat_def_cnt;\n";
2368 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2369 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002370
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002371 Result += "static struct _objc_symtab "
2372 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2373 Result += "\t0, 0, " + utostr(ClsDefCount)
2374 + ", " + utostr(CatDefCount) + "\n";
2375 for (int i = 0; i < ClsDefCount; i++) {
2376 Result += "\t,&_OBJC_CLASS_";
2377 Result += ClassImplementation[i]->getName();
2378 Result += "\n";
2379 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002380
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002381 for (int i = 0; i < CatDefCount; i++) {
2382 Result += "\t,&_OBJC_CATEGORY_";
2383 Result += CategoryImplementation[i]->getClassInterface()->getName();
2384 Result += "_";
2385 Result += CategoryImplementation[i]->getName();
2386 Result += "\n";
2387 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002388
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002389 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002390
2391 // Write objc_module metadata
2392
2393 /*
2394 struct _objc_module {
2395 long version;
2396 long size;
2397 const char *name;
2398 struct _objc_symtab *symtab;
2399 }
2400 */
2401
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002402 Result += "\nstruct _objc_module {\n";
2403 Result += "\tlong version;\n";
2404 Result += "\tlong size;\n";
2405 Result += "\tconst char *name;\n";
2406 Result += "\tstruct _objc_symtab *symtab;\n";
2407 Result += "};\n\n";
2408 Result += "static struct _objc_module "
2409 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002410 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2411 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002412 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002413
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002414}
Chris Lattner311ff022007-10-16 22:36:42 +00002415