blob: 52a93df30143b2338c2000a025f3e80c4a121ff9 [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 Lattner158ecb92007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff2feac5e2007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000023using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000025
Chris Lattner77cd2a02007-10-11 00:43:27 +000026namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Steve Naroffebf2b562007-10-23 23:50:29 +000037
38 FunctionDecl *MsgSendFunctionDecl;
39 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000040 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000041
Steve Naroffbeaf2992007-11-03 11:27:19 +000042 // ObjC string constant support.
43 FileVarDecl *ConstantStringClassReference;
44 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000045
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000046 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000047 public:
Chris Lattner01c57482007-10-17 22:35:30 +000048 void Initialize(ASTContext &context, unsigned mainFileID) {
49 Context = &context;
50 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000051 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000052 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000053 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000054 SelGetUidFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000055 ConstantStringClassReference = 0;
56 NSStringRecord = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000057 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000058 // declaring objc_selector outside the parameter list removes a silly
59 // scope related warning...
60 const char *s = "struct objc_selector;\n"
61 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000062 "(struct objc_object *, struct objc_selector *, ...);\n"
63 "extern struct objc_object *objc_getClass"
64 "(const char *);\n";
65 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
66 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000067 }
Chris Lattner8a12c272007-10-11 18:38:32 +000068
Chris Lattnerf04da132007-10-24 17:06:59 +000069 // Top Level Driver code.
70 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000071 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000072 ~RewriteTest();
73
74 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000075 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000076 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000077 void RewriteTabs();
78 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000079 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000080 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000081 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000082 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +000083 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +000084 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000085 void RewriteObjcQualifiedInterfaceTypes(
86 const FunctionTypeProto *proto, FunctionDecl *FD);
87 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +000088
Chris Lattnerf04da132007-10-24 17:06:59 +000089 // Expression Rewriting.
Chris Lattnere64b7772007-10-24 16:57:36 +000090 Stmt *RewriteFunctionBody(Stmt *S);
91 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +000092 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +000093 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +000094 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +000095 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
96 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
97 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +000098 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +000099 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
100 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000101 void SynthMsgSendFunctionDecl();
102 void SynthGetClassFunctionDecl();
103
Chris Lattnerf04da132007-10-24 17:06:59 +0000104 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000105 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
106 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000107
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000108 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
109 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000110
111 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
112 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000113 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000114 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000115 const char *ClassName,
116 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000117
118 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
119 int NumProtocols,
120 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000121 const char *ClassName,
122 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000123 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
124 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000125 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
126 ObjcIvarDecl *ivar,
127 std::string &Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000128 void WriteObjcMetaData(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000129 };
130}
131
Chris Lattner8a12c272007-10-11 18:38:32 +0000132ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000133
Chris Lattnerf04da132007-10-24 17:06:59 +0000134//===----------------------------------------------------------------------===//
135// Top Level Driver Code
136//===----------------------------------------------------------------------===//
137
Chris Lattner8a12c272007-10-11 18:38:32 +0000138void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000139 // Two cases: either the decl could be in the main file, or it could be in a
140 // #included file. If the former, rewrite it now. If the later, check to see
141 // if we rewrote the #include/#import.
142 SourceLocation Loc = D->getLocation();
143 Loc = SM->getLogicalLoc(Loc);
144
145 // If this is for a builtin, ignore it.
146 if (Loc.isInvalid()) return;
147
Steve Naroffebf2b562007-10-23 23:50:29 +0000148 // Look for built-in declarations that we need to refer during the rewrite.
149 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000150 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000151 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
152 // declared in <Foundation/NSString.h>
153 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
154 ConstantStringClassReference = FVD;
155 return;
156 }
Steve Naroffbef11852007-10-26 20:53:56 +0000157 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
158 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000159 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
160 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000161 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
162 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000163 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000164 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000165 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
166 return HandleDeclInMainFile(D);
167
Chris Lattnerf04da132007-10-24 17:06:59 +0000168 // Otherwise, see if there is a #import in the main file that should be
169 // rewritten.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000170 RewriteInclude(Loc);
171}
172
Chris Lattnerf04da132007-10-24 17:06:59 +0000173/// HandleDeclInMainFile - This is called for each top-level decl defined in the
174/// main file of the input.
175void RewriteTest::HandleDeclInMainFile(Decl *D) {
176 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
177 if (Stmt *Body = FD->getBody())
178 FD->setBody(RewriteFunctionBody(Body));
179
180 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
181 ClassImplementation.push_back(CI);
182 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
183 CategoryImplementation.push_back(CI);
184 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
185 RewriteForwardClassDecl(CD);
186 // Nothing yet.
187}
188
189RewriteTest::~RewriteTest() {
190 // Get the top-level buffer that this corresponds to.
191 RewriteTabs();
192
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000193 // Rewrite Objective-c meta data*
194 std::string ResultStr;
195 WriteObjcMetaData(ResultStr);
196 // For now just print the string out.
197 printf("%s", ResultStr.c_str());
198
Chris Lattnerf04da132007-10-24 17:06:59 +0000199 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
200 // we are done.
201 if (const RewriteBuffer *RewriteBuf =
202 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000203 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000204 std::string S(RewriteBuf->begin(), RewriteBuf->end());
205 printf("%s\n", S.c_str());
206 } else {
207 printf("No changes\n");
208 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000209
210}
211
Chris Lattnerf04da132007-10-24 17:06:59 +0000212//===----------------------------------------------------------------------===//
213// Syntactic (non-AST) Rewriting Code
214//===----------------------------------------------------------------------===//
215
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000216void RewriteTest::RewriteInclude(SourceLocation Loc) {
217 // Rip up the #include stack to the main file.
218 SourceLocation IncLoc = Loc, NextLoc = Loc;
219 do {
220 IncLoc = Loc;
221 Loc = SM->getLogicalLoc(NextLoc);
222 NextLoc = SM->getIncludeLoc(Loc);
223 } while (!NextLoc.isInvalid());
224
225 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
226 // IncLoc indicates the header that was included if it is useful.
227 IncLoc = SM->getLogicalLoc(IncLoc);
228 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
229 Loc == LastIncLoc)
230 return;
231 LastIncLoc = Loc;
232
233 unsigned IncCol = SM->getColumnNumber(Loc);
234 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
235
236 // Replace the #import with #include.
237 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
238}
239
Chris Lattnerf04da132007-10-24 17:06:59 +0000240void RewriteTest::RewriteTabs() {
241 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
242 const char *MainBufStart = MainBuf.first;
243 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000244
Chris Lattnerf04da132007-10-24 17:06:59 +0000245 // Loop over the whole file, looking for tabs.
246 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
247 if (*BufPtr != '\t')
248 continue;
249
250 // Okay, we found a tab. This tab will turn into at least one character,
251 // but it depends on which 'virtual column' it is in. Compute that now.
252 unsigned VCol = 0;
253 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
254 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
255 ++VCol;
256
257 // Okay, now that we know the virtual column, we know how many spaces to
258 // insert. We assume 8-character tab-stops.
259 unsigned Spaces = 8-(VCol & 7);
260
261 // Get the location of the tab.
262 SourceLocation TabLoc =
263 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
264
265 // Rewrite the single tab character into a sequence of spaces.
266 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
267 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000268}
269
270
Chris Lattnerf04da132007-10-24 17:06:59 +0000271void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
272 int numDecls = ClassDecl->getNumForwardDecls();
273 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
274
275 // Get the start location and compute the semi location.
276 SourceLocation startLoc = ClassDecl->getLocation();
277 const char *startBuf = SM->getCharacterData(startLoc);
278 const char *semiPtr = strchr(startBuf, ';');
279
280 // Translate to typedef's that forward reference structs with the same name
281 // as the class. As a convenience, we include the original declaration
282 // as a comment.
283 std::string typedefString;
284 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000285 typedefString.append(startBuf, semiPtr-startBuf+1);
286 typedefString += "\n";
287 for (int i = 0; i < numDecls; i++) {
288 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff8749be52007-10-31 22:11:35 +0000289 if (ObjcForwardDecls.count(ForwardDecl))
290 continue;
Steve Naroff352336b2007-11-05 14:36:37 +0000291 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000292 typedefString += ForwardDecl->getName();
293 typedefString += ";\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000294
295 // Mark this typedef as having been generated.
296 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000297 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000298 }
299
300 // Replace the @class with typedefs corresponding to the classes.
301 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
302 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000303}
304
Steve Naroff423cb562007-10-30 13:30:57 +0000305void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
306 for (int i = 0; i < nMethods; i++) {
307 ObjcMethodDecl *Method = Methods[i];
308 SourceLocation Loc = Method->getLocStart();
309
310 Rewrite.ReplaceText(Loc, 0, "// ", 3);
311
312 // FIXME: handle methods that are declared across multiple lines.
313 }
314}
315
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000316void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
317{
318 for (int i = 0; i < nProperties; i++) {
319 ObjcPropertyDecl *Property = Properties[i];
320 SourceLocation Loc = Property->getLocation();
321
322 Rewrite.ReplaceText(Loc, 0, "// ", 3);
323
324 // FIXME: handle properties that are declared across multiple lines.
325 }
326}
327
Steve Naroff423cb562007-10-30 13:30:57 +0000328void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
329 SourceLocation LocStart = CatDecl->getLocStart();
330
331 // FIXME: handle category headers that are declared across multiple lines.
332 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
333
334 RewriteMethods(CatDecl->getNumInstanceMethods(),
335 CatDecl->getInstanceMethods());
336 RewriteMethods(CatDecl->getNumClassMethods(),
337 CatDecl->getClassMethods());
338 // Lastly, comment out the @end.
339 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
340}
341
Steve Naroff752d6ef2007-10-30 16:42:30 +0000342void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
343 SourceLocation LocStart = PDecl->getLocStart();
344
345 // FIXME: handle protocol headers that are declared across multiple lines.
346 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
347
348 RewriteMethods(PDecl->getNumInstanceMethods(),
349 PDecl->getInstanceMethods());
350 RewriteMethods(PDecl->getNumClassMethods(),
351 PDecl->getClassMethods());
352 // Lastly, comment out the @end.
353 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
354}
355
Steve Naroffbef11852007-10-26 20:53:56 +0000356void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000357
358 SourceLocation LocStart = ClassDecl->getLocStart();
359 SourceLocation LocEnd = ClassDecl->getLocEnd();
360
361 const char *startBuf = SM->getCharacterData(LocStart);
362 const char *endBuf = SM->getCharacterData(LocEnd);
363
Steve Naroff2feac5e2007-10-30 03:43:13 +0000364 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000365
366 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000367 if (!ObjcForwardDecls.count(ClassDecl)) {
368 // we haven't seen a forward decl - generate a typedef.
Steve Naroff352336b2007-11-05 14:36:37 +0000369 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000370 ResultStr += ClassDecl->getName();
371 ResultStr += ";";
372
373 // Mark this typedef as having been generated.
374 ObjcForwardDecls.insert(ClassDecl);
375 }
Steve Narofff908a872007-10-30 02:23:23 +0000376 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
377
Steve Naroff2feac5e2007-10-30 03:43:13 +0000378 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000379 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000380 RewriteProperties(ClassDecl->getNumPropertyDecl(),
381 ClassDecl->getPropertyDecl());
Steve Naroff423cb562007-10-30 13:30:57 +0000382 RewriteMethods(ClassDecl->getNumInstanceMethods(),
383 ClassDecl->getInstanceMethods());
384 RewriteMethods(ClassDecl->getNumClassMethods(),
385 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000386
Steve Naroff2feac5e2007-10-30 03:43:13 +0000387 // Lastly, comment out the @end.
388 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000389}
390
Chris Lattnerf04da132007-10-24 17:06:59 +0000391//===----------------------------------------------------------------------===//
392// Function Body / Expression rewriting
393//===----------------------------------------------------------------------===//
394
Chris Lattnere64b7772007-10-24 16:57:36 +0000395Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000396 // Otherwise, just rewrite all children.
397 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
398 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000399 if (*CI) {
400 Stmt *newStmt = RewriteFunctionBody(*CI);
401 if (newStmt)
402 *CI = newStmt;
403 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000404
405 // Handle specific things.
406 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
407 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000408
409 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
410 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000411
412 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
413 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000414
Steve Naroff934f2762007-10-24 22:48:43 +0000415 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
416 // Before we rewrite it, put the original message expression in a comment.
417 SourceLocation startLoc = MessExpr->getLocStart();
418 SourceLocation endLoc = MessExpr->getLocEnd();
419
420 const char *startBuf = SM->getCharacterData(startLoc);
421 const char *endBuf = SM->getCharacterData(endLoc);
422
423 std::string messString;
424 messString += "// ";
425 messString.append(startBuf, endBuf-startBuf+1);
426 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000427
Steve Naroff934f2762007-10-24 22:48:43 +0000428 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
429 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
430 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000431 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000432 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000433 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000434
435 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
436 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000437
438 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
439 return RewriteObjcThrowStmt(StmtThrow);
440
Chris Lattnere64b7772007-10-24 16:57:36 +0000441 // Return this stmt unmodified.
442 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000443}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000444
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000445Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000446 // Get the start location and compute the semi location.
447 SourceLocation startLoc = S->getLocStart();
448 const char *startBuf = SM->getCharacterData(startLoc);
449
450 assert((*startBuf == '@') && "bogus @try location");
451
452 std::string buf;
453 // declare a new scope with two variables, _stack and _rethrow.
454 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
455 buf += "int buf[18/*32-bit i386*/];\n";
456 buf += "char *pointers[4];} _stack;\n";
457 buf += "id volatile _rethrow = 0;\n";
458 buf += "objc_exception_try_enter(&_stack);\n";
459 buf += "if (!_setjmp(&_stack.buf)) /* @try block continue */\n";
460
461 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
462
463 startLoc = S->getTryBody()->getLocEnd();
464 startBuf = SM->getCharacterData(startLoc);
465
466 assert((*startBuf == '}') && "bogus @try block");
467
468 SourceLocation lastCurlyLoc = startLoc;
469
470 startLoc = startLoc.getFileLocWithOffset(1);
471 buf = " /* @catch begin */ else {\n";
472 buf += " id _caught = objc_exception_extract(&_stack);\n";
473 buf += " objc_exception_try_enter (&_stack);\n";
474 buf += " if (_setjmp(&_stack.buf))\n";
475 buf += " _rethrow = objc_exception_extract(&_stack);\n";
476 buf += " else { /* @catch continue */";
477
478 Rewrite.ReplaceText(startLoc, 0, buf.c_str(), buf.size());
479
480 bool sawIdTypedCatch = false;
481 Stmt *lastCatchBody = 0;
482 ObjcAtCatchStmt *catchList = S->getCatchStmts();
483 while (catchList) {
484 Stmt *catchStmt = catchList->getCatchParamStmt();
485
486 if (catchList == S->getCatchStmts())
487 buf = "if ("; // we are generating code for the first catch clause
488 else
489 buf = "else if (";
490 startLoc = catchList->getLocStart();
491 startBuf = SM->getCharacterData(startLoc);
492
493 assert((*startBuf == '@') && "bogus @catch location");
494
495 const char *lParenLoc = strchr(startBuf, '(');
496
497 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
498 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
499 if (t == Context->getObjcIdType()) {
500 buf += "1) { ";
501 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
502 buf.c_str(), buf.size());
503 sawIdTypedCatch = true;
504 } else if (const PointerType *pType = t->getAsPointerType()) {
505 ObjcInterfaceType *cls; // Should be a pointer to a class.
506
507 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
508 if (cls) {
509 buf += "objc_exception_match(objc_getClass(\"";
510 buf += cls->getDecl()->getName();
511 buf += "\"), _caught)) { ";
512 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
513 buf.c_str(), buf.size());
514 }
515 }
516 // Now rewrite the body...
517 lastCatchBody = catchList->getCatchBody();
518 SourceLocation rParenLoc = catchList->getRParenLoc();
519 SourceLocation bodyLoc = lastCatchBody->getLocStart();
520 const char *bodyBuf = SM->getCharacterData(bodyLoc);
521 const char *rParenBuf = SM->getCharacterData(rParenLoc);
522 assert((*rParenBuf == ')') && "bogus @catch paren location");
523 assert((*bodyBuf == '{') && "bogus @catch body location");
524
525 buf = " = _caught;";
526 // Here we replace ") {" with "= _caught;" (which initializes and
527 // declares the @catch parameter).
528 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
529 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000530 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000531 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000532 }
Steve Naroff75730982007-11-07 04:08:17 +0000533 catchList = catchList->getNextCatchStmt();
534 }
535 // Complete the catch list...
536 if (lastCatchBody) {
537 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
538 const char *bodyBuf = SM->getCharacterData(bodyLoc);
539 assert((*bodyBuf == '}') && "bogus @catch body location");
540 bodyLoc = bodyLoc.getFileLocWithOffset(1);
541 buf = " } } /* @catch end */\n";
542
543 Rewrite.ReplaceText(bodyLoc, 0, buf.c_str(), buf.size());
544
545 // Set lastCurlyLoc
546 lastCurlyLoc = lastCatchBody->getLocEnd();
547 }
548 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
549 startLoc = finalStmt->getLocStart();
550 startBuf = SM->getCharacterData(startLoc);
551 assert((*startBuf == '@') && "bogus @finally start");
552
553 buf = "/* @finally */";
554 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
555
556 Stmt *body = finalStmt->getFinallyBody();
557 SourceLocation startLoc = body->getLocStart();
558 SourceLocation endLoc = body->getLocEnd();
559 const char *startBuf = SM->getCharacterData(startLoc);
560 const char *endBuf = SM->getCharacterData(endLoc);
561 assert((*startBuf == '{') && "bogus @finally body location");
562 assert((*endBuf == '}') && "bogus @finally body location");
563
564 startLoc = startLoc.getFileLocWithOffset(1);
565 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
566 Rewrite.ReplaceText(startLoc, 0, buf.c_str(), buf.size());
567 endLoc = endLoc.getFileLocWithOffset(-1);
568 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
569 Rewrite.ReplaceText(endLoc, 0, buf.c_str(), buf.size());
570
571 // Set lastCurlyLoc
572 lastCurlyLoc = body->getLocEnd();
573 }
574 // Now emit the final closing curly brace...
575 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
576 buf = " } /* @try scope end */\n";
577 Rewrite.ReplaceText(lastCurlyLoc, 0, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000578 return 0;
579}
580
581Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
582 return 0;
583}
584
585Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
586 return 0;
587}
588
Steve Naroff2bd03922007-11-07 15:32:26 +0000589// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
590// the throw expression is typically a message expression that's already
591// been rewritten! (which implies the SourceLocation's are invalid).
592Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
593 // Get the start location and compute the semi location.
594 SourceLocation startLoc = S->getLocStart();
595 const char *startBuf = SM->getCharacterData(startLoc);
596
597 assert((*startBuf == '@') && "bogus @throw location");
598
599 std::string buf;
600 /* void objc_exception_throw(id) __attribute__((noreturn)); */
601 buf = "objc_exception_throw(";
602 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
603 const char *semiBuf = strchr(startBuf, ';');
604 assert((*semiBuf == ';') && "@throw: can't find ';'");
605 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
606 buf = ");";
607 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
608 return 0;
609}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000610
Chris Lattnere64b7772007-10-24 16:57:36 +0000611Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000612 // Create a new string expression.
613 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000614 std::string StrEncoding;
615 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
616 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
617 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000618 SourceLocation(), SourceLocation());
619 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000620 delete Exp;
621 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000622}
623
Steve Naroffb42f8412007-11-05 14:50:49 +0000624Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
625 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
626 // Create a call to sel_registerName("selName").
627 llvm::SmallVector<Expr*, 8> SelExprs;
628 QualType argType = Context->getPointerType(Context->CharTy);
629 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
630 Exp->getSelector().getName().size(),
631 false, argType, SourceLocation(),
632 SourceLocation()));
633 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
634 &SelExprs[0], SelExprs.size());
635 Rewrite.ReplaceStmt(Exp, SelExp);
636 delete Exp;
637 return SelExp;
638}
639
Steve Naroff934f2762007-10-24 22:48:43 +0000640CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
641 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000642 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000643 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000644
645 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000646 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000647
648 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000649 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000650 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
651
652 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000653
Steve Naroff934f2762007-10-24 22:48:43 +0000654 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
655}
656
Steve Naroffd5255f52007-11-01 13:24:47 +0000657static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
658 const char *&startRef, const char *&endRef) {
659 while (startBuf < endBuf) {
660 if (*startBuf == '<')
661 startRef = startBuf; // mark the start.
662 if (*startBuf == '>') {
663 assert((startRef && *startRef == '<') && "rewrite scanning error");
664 endRef = startBuf; // mark the end.
665 return true;
666 }
667 startBuf++;
668 }
669 return false;
670}
671
672bool RewriteTest::needToScanForQualifiers(QualType T) {
673 // FIXME: we don't currently represent "id <Protocol>" in the type system.
674 if (T == Context->getObjcIdType())
675 return true;
676
677 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000678 Type *pointeeType = pType->getPointeeType().getTypePtr();
679 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
680 return true; // we have "Class <Protocol> *".
681 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000682 return false;
683}
684
685void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
686 const FunctionTypeProto *proto, FunctionDecl *FD) {
687
688 if (needToScanForQualifiers(proto->getResultType())) {
689 // Since types are unique, we need to scan the buffer.
690 SourceLocation Loc = FD->getLocation();
691
692 const char *endBuf = SM->getCharacterData(Loc);
693 const char *startBuf = endBuf;
694 while (*startBuf != ';')
695 startBuf--; // scan backward (from the decl location) for return type.
696 const char *startRef = 0, *endRef = 0;
697 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
698 // Get the locations of the startRef, endRef.
699 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
700 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
701 // Comment out the protocol references.
702 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
703 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000704 }
705 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000706 // Now check arguments.
707 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
708 if (needToScanForQualifiers(proto->getArgType(i))) {
709 // Since types are unique, we need to scan the buffer.
710 SourceLocation Loc = FD->getLocation();
711
712 const char *startBuf = SM->getCharacterData(Loc);
713 const char *endBuf = startBuf;
714 while (*endBuf != ';')
715 endBuf++; // scan forward (from the decl location) for argument types.
716 const char *startRef = 0, *endRef = 0;
717 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
718 // Get the locations of the startRef, endRef.
719 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
720 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
721 // Comment out the protocol references.
722 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
723 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
724 }
725 }
726 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000727}
728
Steve Naroff09b266e2007-10-30 23:14:51 +0000729void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
730 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000731 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000732 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000733 return;
734 }
735 // Check for ObjC 'id' and class types that have been adorned with protocol
736 // information (id<p>, C<p>*). The protocol references need to be rewritten!
737 const FunctionType *funcType = FD->getType()->getAsFunctionType();
738 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000739 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
740 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000741}
742
743// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
744void RewriteTest::SynthMsgSendFunctionDecl() {
745 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
746 llvm::SmallVector<QualType, 16> ArgTys;
747 QualType argT = Context->getObjcIdType();
748 assert(!argT.isNull() && "Can't find 'id' type");
749 ArgTys.push_back(argT);
750 argT = Context->getObjcSelType();
751 assert(!argT.isNull() && "Can't find 'SEL' type");
752 ArgTys.push_back(argT);
753 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
754 &ArgTys[0], ArgTys.size(),
755 true /*isVariadic*/);
756 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
757 msgSendIdent, msgSendType,
758 FunctionDecl::Extern, false, 0);
759}
760
761// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
762void RewriteTest::SynthGetClassFunctionDecl() {
763 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
764 llvm::SmallVector<QualType, 16> ArgTys;
765 ArgTys.push_back(Context->getPointerType(
766 Context->CharTy.getQualifiedType(QualType::Const)));
767 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
768 &ArgTys[0], ArgTys.size(),
769 false /*isVariadic*/);
770 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
771 getClassIdent, getClassType,
772 FunctionDecl::Extern, false, 0);
773}
774
Steve Naroffbeaf2992007-11-03 11:27:19 +0000775Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
776 assert(ConstantStringClassReference && "Can't find constant string reference");
777 llvm::SmallVector<Expr*, 4> InitExprs;
778
779 // Synthesize "(Class)&_NSConstantStringClassReference"
780 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
781 ConstantStringClassReference->getType(),
782 SourceLocation());
783 QualType expType = Context->getPointerType(ClsRef->getType());
784 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
785 expType, SourceLocation());
786 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
787 SourceLocation());
788 InitExprs.push_back(cast); // set the 'isa'.
789 InitExprs.push_back(Exp->getString()); // set "char *bytes".
790 unsigned IntSize = static_cast<unsigned>(
791 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
792 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
793 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
794 Exp->getLocStart());
795 InitExprs.push_back(len); // set "int numBytes".
796
797 // struct NSConstantString
798 QualType CFConstantStrType = Context->getCFConstantStringType();
799 // (struct NSConstantString) { <exprs from above> }
800 InitListExpr *ILE = new InitListExpr(SourceLocation(),
801 &InitExprs[0], InitExprs.size(),
802 SourceLocation());
803 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
804 // struct NSConstantString *
805 expType = Context->getPointerType(StrRep->getType());
806 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
807 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +0000808 // cast to NSConstantString *
809 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +0000810 Rewrite.ReplaceStmt(Exp, cast);
811 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +0000812 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +0000813}
814
Steve Naroff934f2762007-10-24 22:48:43 +0000815Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000816 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000817 if (!MsgSendFunctionDecl)
818 SynthMsgSendFunctionDecl();
819 if (!GetClassFunctionDecl)
820 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000821
822 // Synthesize a call to objc_msgSend().
823 llvm::SmallVector<Expr*, 8> MsgExprs;
824 IdentifierInfo *clsName = Exp->getClassName();
825
826 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
827 if (clsName) { // class message.
828 llvm::SmallVector<Expr*, 8> ClsExprs;
829 QualType argType = Context->getPointerType(Context->CharTy);
830 ClsExprs.push_back(new StringLiteral(clsName->getName(),
831 clsName->getLength(),
832 false, argType, SourceLocation(),
833 SourceLocation()));
834 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
835 &ClsExprs[0], ClsExprs.size());
836 MsgExprs.push_back(Cls);
837 } else // instance message.
838 MsgExprs.push_back(Exp->getReceiver());
839
Steve Naroffbeaf2992007-11-03 11:27:19 +0000840 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +0000841 llvm::SmallVector<Expr*, 8> SelExprs;
842 QualType argType = Context->getPointerType(Context->CharTy);
843 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
844 Exp->getSelector().getName().size(),
845 false, argType, SourceLocation(),
846 SourceLocation()));
847 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
848 &SelExprs[0], SelExprs.size());
849 MsgExprs.push_back(SelExp);
850
851 // Now push any user supplied arguments.
852 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
853 MsgExprs.push_back(Exp->getArg(i));
854 // We've transferred the ownership to MsgExprs. Null out the argument in
855 // the original expression, since we will delete it below.
856 Exp->setArg(i, 0);
857 }
Steve Naroffab972d32007-11-04 22:37:50 +0000858 // Generate the funky cast.
859 CastExpr *cast;
860 llvm::SmallVector<QualType, 8> ArgTypes;
861 QualType returnType;
862
863 // Push 'id' and 'SEL', the 2 implicit arguments.
864 ArgTypes.push_back(Context->getObjcIdType());
865 ArgTypes.push_back(Context->getObjcSelType());
866 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
867 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +0000868 for (int i = 0; i < mDecl->getNumParams(); i++) {
869 QualType t = mDecl->getParamDecl(i)->getType();
870 if (t == Context->getObjcClassType())
871 t = Context->getObjcIdType(); // Convert "Class"->"id"
872 ArgTypes.push_back(t);
873 }
Steve Naroffab972d32007-11-04 22:37:50 +0000874 returnType = mDecl->getResultType();
875 } else {
876 returnType = Context->getObjcIdType();
877 }
878 // Get the type, we will need to reference it in a couple spots.
879 QualType msgSendType = MsgSendFunctionDecl->getType();
880
881 // Create a reference to the objc_msgSend() declaration.
882 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
883
884 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
885 // If we don't do this cast, we get the following bizarre warning/note:
886 // xx.m:13: warning: function called through a non-compatible type
887 // xx.m:13: note: if this code is reached, the program will abort
888 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
889 SourceLocation());
890
891 // Now do the "normal" pointer to function cast.
892 QualType castType = Context->getFunctionType(returnType,
893 &ArgTypes[0], ArgTypes.size(),
894 false/*FIXME:variadic*/);
895 castType = Context->getPointerType(castType);
896 cast = new CastExpr(castType, cast, SourceLocation());
897
898 // Don't forget the parens to enforce the proper binding.
899 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
900
901 const FunctionType *FT = msgSendType->getAsFunctionType();
902 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
903 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +0000904 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +0000905 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +0000906
Chris Lattnere64b7772007-10-24 16:57:36 +0000907 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +0000908 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +0000909}
910
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000911/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
912/// an objective-c class with ivars.
913void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
914 std::string &Result) {
915 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
916 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +0000917 // Do not synthesize more than once.
918 if (ObjcSynthesizedStructs.count(CDecl))
919 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000920 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
921 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
922 // Do it for the root
923 SynthesizeObjcInternalStruct(RCDecl, Result);
924 }
925
926 int NumIvars = CDecl->getIntfDeclNumIvars();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000927 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +0000928 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000929 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
930 return;
931
Steve Naroff04960052007-11-01 17:12:31 +0000932 Result += "\nstruct ";
933 Result += CDecl->getName();
934 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
935 Result += " {\n struct ";
936 Result += RCDecl->getName();
937 Result += " _";
938 Result += RCDecl->getName();
939 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000940 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000941 else
942 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +0000943
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000944 if (NumIvars > 0) {
945 SourceLocation LocStart = CDecl->getLocStart();
946 SourceLocation LocEnd = CDecl->getLocEnd();
947
948 const char *startBuf = SM->getCharacterData(LocStart);
949 const char *endBuf = SM->getCharacterData(LocEnd);
950 startBuf = strchr(startBuf, '{');
951 assert((startBuf && endBuf)
952 && "SynthesizeObjcInternalStruct - malformed @interface");
953 startBuf++; // past '{'
954 while (startBuf < endBuf) {
955 if (*startBuf == '@') {
956 startBuf = strchr(startBuf, 'p');
957 // FIXME: presence of @public, etc. inside comment results in
958 // this transformation as well, which is still correct c-code.
959 if (!strncmp(startBuf, "public", strlen("public"))) {
960 startBuf += strlen("public");
961 Result += "/* @public */";
962 }
963 else if (!strncmp(startBuf, "private", strlen("private"))) {
964 startBuf += strlen("private");
965 Result += "/* @private */";
966 }
967 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
968 startBuf += strlen("protected");
969 Result += "/* @protected */";
970 }
971 }
972 Result += *startBuf++;
973 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000974 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000975
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000976 Result += "};\n";
977 // Mark this struct as having been generated.
978 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000979 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000980}
981
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000982// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
983/// class methods.
984void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
985 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000986 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000987 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000988 const char *ClassName,
989 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000990 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000991 if (NumMethods > 0 && !objc_impl_method) {
992 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000993 SEL _cmd;
994 char *method_types;
995 void *_imp;
996 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000997 */
Chris Lattner158ecb92007-10-25 17:07:24 +0000998 Result += "\nstruct _objc_method {\n";
999 Result += "\tSEL _cmd;\n";
1000 Result += "\tchar *method_types;\n";
1001 Result += "\tvoid *_imp;\n";
1002 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001003
1004 /* struct _objc_method_list {
1005 struct _objc_method_list *next_method;
1006 int method_count;
1007 struct _objc_method method_list[];
1008 }
1009 */
1010 Result += "\nstruct _objc_method_list {\n";
1011 Result += "\tstruct _objc_method_list *next_method;\n";
1012 Result += "\tint method_count;\n";
1013 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001014 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001015 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001016 // Build _objc_method_list for class's methods if needed
1017 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001018 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001019 Result += prefix;
1020 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1021 Result += "_METHODS_";
1022 Result += ClassName;
1023 Result += " __attribute__ ((section (\"__OBJC, __";
1024 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001025 Result += "_meth\")))= ";
1026 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1027
1028 Result += "\t,{{(SEL)\"";
1029 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001030 std::string MethodTypeString;
1031 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1032 Result += "\", \"";
1033 Result += MethodTypeString;
1034 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001035 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001036 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001037 Result += "\t ,{(SEL)\"";
1038 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001039 std::string MethodTypeString;
1040 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1041 Result += "\", \"";
1042 Result += MethodTypeString;
1043 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001044 }
1045 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001046 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001047}
1048
1049/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1050void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1051 int NumProtocols,
1052 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001053 const char *ClassName,
1054 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001055 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001056 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001057 for (int i = 0; i < NumProtocols; i++) {
1058 ObjcProtocolDecl *PDecl = Protocols[i];
1059 // Output struct protocol_methods holder of method selector and type.
1060 if (!objc_protocol_methods &&
1061 (PDecl->getNumInstanceMethods() > 0
1062 || PDecl->getNumClassMethods() > 0)) {
1063 /* struct protocol_methods {
1064 SEL _cmd;
1065 char *method_types;
1066 }
1067 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001068 Result += "\nstruct protocol_methods {\n";
1069 Result += "\tSEL _cmd;\n";
1070 Result += "\tchar *method_types;\n";
1071 Result += "};\n";
1072
1073 /* struct _objc_protocol_method_list {
1074 int protocol_method_count;
1075 struct protocol_methods protocols[];
1076 }
1077 */
1078 Result += "\nstruct _objc_protocol_method_list {\n";
1079 Result += "\tint protocol_method_count;\n";
1080 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001081 objc_protocol_methods = true;
1082 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001083
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001084 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001085 int NumMethods = PDecl->getNumInstanceMethods();
1086 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001087 Result += "\nstatic struct _objc_protocol_method_list "
1088 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1089 Result += PDecl->getName();
1090 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1091 "{\n\t" + utostr(NumMethods) + "\n";
1092
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001093 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001094 Result += "\t,{{(SEL)\"";
1095 Result += Methods[0]->getSelector().getName().c_str();
1096 Result += "\", \"\"}\n";
1097
1098 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001099 Result += "\t ,{(SEL)\"";
1100 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001101 std::string MethodTypeString;
1102 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1103 Result += "\", \"";
1104 Result += MethodTypeString;
1105 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001106 }
1107 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001108 }
1109
1110 // Output class methods declared in this protocol.
1111 NumMethods = PDecl->getNumClassMethods();
1112 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001113 Result += "\nstatic struct _objc_protocol_method_list "
1114 "_OBJC_PROTOCOL_CLASS_METHODS_";
1115 Result += PDecl->getName();
1116 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1117 "{\n\t";
1118 Result += utostr(NumMethods);
1119 Result += "\n";
1120
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001121 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001122 Result += "\t,{{(SEL)\"";
1123 Result += Methods[0]->getSelector().getName().c_str();
1124 Result += "\", \"\"}\n";
1125
1126 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001127 Result += "\t ,{(SEL)\"";
1128 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001129 std::string MethodTypeString;
1130 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1131 Result += "\", \"";
1132 Result += MethodTypeString;
1133 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001134 }
1135 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001136 }
1137 // Output:
1138 /* struct _objc_protocol {
1139 // Objective-C 1.0 extensions
1140 struct _objc_protocol_extension *isa;
1141 char *protocol_name;
1142 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001143 struct _objc_protocol_method_list *instance_methods;
1144 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001145 };
1146 */
1147 static bool objc_protocol = false;
1148 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001149 Result += "\nstruct _objc_protocol {\n";
1150 Result += "\tstruct _objc_protocol_extension *isa;\n";
1151 Result += "\tchar *protocol_name;\n";
1152 Result += "\tstruct _objc_protocol **protocol_list;\n";
1153 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1154 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1155 Result += "};\n";
1156
1157 /* struct _objc_protocol_list {
1158 struct _objc_protocol_list *next;
1159 int protocol_count;
1160 struct _objc_protocol *class_protocols[];
1161 }
1162 */
1163 Result += "\nstruct _objc_protocol_list {\n";
1164 Result += "\tstruct _objc_protocol_list *next;\n";
1165 Result += "\tint protocol_count;\n";
1166 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1167 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001168 objc_protocol = true;
1169 }
1170
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001171 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1172 Result += PDecl->getName();
1173 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1174 "{\n\t0, \"";
1175 Result += PDecl->getName();
1176 Result += "\", 0, ";
1177 if (PDecl->getInstanceMethods() > 0) {
1178 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1179 Result += PDecl->getName();
1180 Result += ", ";
1181 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001182 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001183 Result += "0, ";
1184 if (PDecl->getClassMethods() > 0) {
1185 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1186 Result += PDecl->getName();
1187 Result += "\n";
1188 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001189 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001190 Result += "0\n";
1191 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001192 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001193 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001194 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1195 Result += prefix;
1196 Result += "_PROTOCOLS_";
1197 Result += ClassName;
1198 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1199 "{\n\t0, ";
1200 Result += utostr(NumProtocols);
1201 Result += "\n";
1202
1203 Result += "\t,{&_OBJC_PROTOCOL_";
1204 Result += Protocols[0]->getName();
1205 Result += " \n";
1206
1207 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001208 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001209 Result += "\t ,&_OBJC_PROTOCOL_";
1210 Result += PDecl->getName();
1211 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001212 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001213 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001214 }
1215}
1216
1217/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1218/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001219void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1220 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001221 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1222 // Find category declaration for this implementation.
1223 ObjcCategoryDecl *CDecl;
1224 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1225 CDecl = CDecl->getNextClassCategory())
1226 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1227 break;
1228 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1229
1230 char *FullCategoryName = (char*)alloca(
1231 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1232 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1233
1234 // Build _objc_method_list for class's instance methods if needed
1235 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1236 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001237 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001238 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001239
1240 // Build _objc_method_list for class's class methods if needed
1241 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1242 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001243 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001244 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001245
1246 // Protocols referenced in class declaration?
1247 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1248 CDecl->getNumReferencedProtocols(),
1249 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001250 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001251
1252 /* struct _objc_category {
1253 char *category_name;
1254 char *class_name;
1255 struct _objc_method_list *instance_methods;
1256 struct _objc_method_list *class_methods;
1257 struct _objc_protocol_list *protocols;
1258 // Objective-C 1.0 extensions
1259 uint32_t size; // sizeof (struct _objc_category)
1260 struct _objc_property_list *instance_properties; // category's own
1261 // @property decl.
1262 };
1263 */
1264
1265 static bool objc_category = false;
1266 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001267 Result += "\nstruct _objc_category {\n";
1268 Result += "\tchar *category_name;\n";
1269 Result += "\tchar *class_name;\n";
1270 Result += "\tstruct _objc_method_list *instance_methods;\n";
1271 Result += "\tstruct _objc_method_list *class_methods;\n";
1272 Result += "\tstruct _objc_protocol_list *protocols;\n";
1273 Result += "\tunsigned int size;\n";
1274 Result += "\tstruct _objc_property_list *instance_properties;\n";
1275 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001276 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001277 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001278 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1279 Result += FullCategoryName;
1280 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1281 Result += IDecl->getName();
1282 Result += "\"\n\t, \"";
1283 Result += ClassDecl->getName();
1284 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001285
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001286 if (IDecl->getNumInstanceMethods() > 0) {
1287 Result += "\t, (struct _objc_method_list *)"
1288 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1289 Result += FullCategoryName;
1290 Result += "\n";
1291 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001292 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001293 Result += "\t, 0\n";
1294 if (IDecl->getNumClassMethods() > 0) {
1295 Result += "\t, (struct _objc_method_list *)"
1296 "&_OBJC_CATEGORY_CLASS_METHODS_";
1297 Result += FullCategoryName;
1298 Result += "\n";
1299 }
1300 else
1301 Result += "\t, 0\n";
1302
1303 if (CDecl->getNumReferencedProtocols() > 0) {
1304 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1305 Result += FullCategoryName;
1306 Result += "\n";
1307 }
1308 else
1309 Result += "\t, 0\n";
1310 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001311}
1312
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001313/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1314/// ivar offset.
1315void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1316 ObjcIvarDecl *ivar,
1317 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001318 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001319 Result += IDecl->getName();
1320 Result += ", ";
1321 Result += ivar->getName();
1322 Result += ")";
1323}
1324
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001325//===----------------------------------------------------------------------===//
1326// Meta Data Emission
1327//===----------------------------------------------------------------------===//
1328
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001329void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1330 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001331 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1332
1333 // Build _objc_ivar_list metadata for classes ivars if needed
1334 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1335 ? IDecl->getImplDeclNumIvars()
1336 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
1337
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001338 SynthesizeObjcInternalStruct(CDecl, Result);
1339
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001340 if (NumIvars > 0) {
1341 static bool objc_ivar = false;
1342 if (!objc_ivar) {
1343 /* struct _objc_ivar {
1344 char *ivar_name;
1345 char *ivar_type;
1346 int ivar_offset;
1347 };
1348 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001349 Result += "\nstruct _objc_ivar {\n";
1350 Result += "\tchar *ivar_name;\n";
1351 Result += "\tchar *ivar_type;\n";
1352 Result += "\tint ivar_offset;\n";
1353 Result += "};\n";
1354
1355 /* struct _objc_ivar_list {
1356 int ivar_count;
1357 struct _objc_ivar ivar_list[];
1358 };
1359 */
1360 Result += "\nstruct _objc_ivar_list {\n";
1361 Result += "\tint ivar_count;\n";
1362 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001363 objc_ivar = true;
1364 }
1365
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001366 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1367 Result += IDecl->getName();
1368 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1369 "{\n\t";
1370 Result += utostr(NumIvars);
1371 Result += "\n";
1372
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001373 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1374 ? IDecl->getImplDeclIVars()
1375 : CDecl->getIntfDeclIvars();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001376 Result += "\t,{{\"";
1377 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001378 Result += "\", \"";
1379 std::string StrEncoding;
1380 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1381 Result += StrEncoding;
1382 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001383 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1384 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001385 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001386 Result += "\t ,{\"";
1387 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001388 Result += "\", \"";
1389 std::string StrEncoding;
1390 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1391 Result += StrEncoding;
1392 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001393 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1394 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001395 }
1396
1397 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001398 }
1399
1400 // Build _objc_method_list for class's instance methods if needed
1401 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1402 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001403 true,
1404 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001405
1406 // Build _objc_method_list for class's class methods if needed
1407 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001408 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001409 false,
1410 "", IDecl->getName(), Result);
1411
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001412 // Protocols referenced in class declaration?
1413 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1414 CDecl->getNumIntfRefProtocols(),
1415 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001416 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001417
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001418
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001419 // Declaration of class/meta-class metadata
1420 /* struct _objc_class {
1421 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001422 const char *super_class_name;
1423 char *name;
1424 long version;
1425 long info;
1426 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001427 struct _objc_ivar_list *ivars;
1428 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001429 struct objc_cache *cache;
1430 struct objc_protocol_list *protocols;
1431 const char *ivar_layout;
1432 struct _objc_class_ext *ext;
1433 };
1434 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001435 static bool objc_class = false;
1436 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001437 Result += "\nstruct _objc_class {\n";
1438 Result += "\tstruct _objc_class *isa;\n";
1439 Result += "\tconst char *super_class_name;\n";
1440 Result += "\tchar *name;\n";
1441 Result += "\tlong version;\n";
1442 Result += "\tlong info;\n";
1443 Result += "\tlong instance_size;\n";
1444 Result += "\tstruct _objc_ivar_list *ivars;\n";
1445 Result += "\tstruct _objc_method_list *methods;\n";
1446 Result += "\tstruct objc_cache *cache;\n";
1447 Result += "\tstruct _objc_protocol_list *protocols;\n";
1448 Result += "\tconst char *ivar_layout;\n";
1449 Result += "\tstruct _objc_class_ext *ext;\n";
1450 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001451 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001452 }
1453
1454 // Meta-class metadata generation.
1455 ObjcInterfaceDecl *RootClass = 0;
1456 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1457 while (SuperClass) {
1458 RootClass = SuperClass;
1459 SuperClass = SuperClass->getSuperClass();
1460 }
1461 SuperClass = CDecl->getSuperClass();
1462
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001463 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1464 Result += CDecl->getName();
1465 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1466 "{\n\t(struct _objc_class *)\"";
1467 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1468 Result += "\"";
1469
1470 if (SuperClass) {
1471 Result += ", \"";
1472 Result += SuperClass->getName();
1473 Result += "\", \"";
1474 Result += CDecl->getName();
1475 Result += "\"";
1476 }
1477 else {
1478 Result += ", 0, \"";
1479 Result += CDecl->getName();
1480 Result += "\"";
1481 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001482 // TODO: 'ivars' field for root class is currently set to 0.
1483 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001484 Result += ", 0,2, sizeof(struct _objc_class), 0";
1485 if (CDecl->getNumClassMethods() > 0) {
1486 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1487 Result += CDecl->getName();
1488 Result += "\n";
1489 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001490 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001491 Result += ", 0\n";
1492 if (CDecl->getNumIntfRefProtocols() > 0) {
1493 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1494 Result += CDecl->getName();
1495 Result += ",0,0\n";
1496 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001497 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001498 Result += "\t,0,0,0,0\n";
1499 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001500
1501 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001502 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1503 Result += CDecl->getName();
1504 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1505 "{\n\t&_OBJC_METACLASS_";
1506 Result += CDecl->getName();
1507 if (SuperClass) {
1508 Result += ", \"";
1509 Result += SuperClass->getName();
1510 Result += "\", \"";
1511 Result += CDecl->getName();
1512 Result += "\"";
1513 }
1514 else {
1515 Result += ", 0, \"";
1516 Result += CDecl->getName();
1517 Result += "\"";
1518 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001519 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001520 Result += ", 0,1";
1521 if (!ObjcSynthesizedStructs.count(CDecl))
1522 Result += ",0";
1523 else {
1524 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001525 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001526 Result += CDecl->getName();
1527 Result += ")";
1528 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001529 if (NumIvars > 0) {
1530 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1531 Result += CDecl->getName();
1532 Result += "\n\t";
1533 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001534 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001535 Result += ",0";
1536 if (IDecl->getNumInstanceMethods() > 0) {
1537 Result += ", &_OBJC_INSTANCE_METHODS_";
1538 Result += CDecl->getName();
1539 Result += ", 0\n\t";
1540 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001541 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001542 Result += ",0,0";
1543 if (CDecl->getNumIntfRefProtocols() > 0) {
1544 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1545 Result += CDecl->getName();
1546 Result += ", 0,0\n";
1547 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001548 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001549 Result += ",0,0,0\n";
1550 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001551}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001552
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001553void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001554 int ClsDefCount = ClassImplementation.size();
1555 int CatDefCount = CategoryImplementation.size();
1556 if (ClsDefCount == 0 && CatDefCount == 0)
1557 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001558
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001559 // TODO: This is temporary until we decide how to access objc types in a
1560 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001561 Result += "#include <Objc/objc.h>\n";
1562 // This is needed for use of offsetof
1563 Result += "#include <stddef.h>\n";
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001564
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001565 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001566 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001567 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001568
1569 // For each implemented category, write out all its meta data.
1570 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001571 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001572
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001573 // Write objc_symtab metadata
1574 /*
1575 struct _objc_symtab
1576 {
1577 long sel_ref_cnt;
1578 SEL *refs;
1579 short cls_def_cnt;
1580 short cat_def_cnt;
1581 void *defs[cls_def_cnt + cat_def_cnt];
1582 };
1583 */
1584
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001585 Result += "\nstruct _objc_symtab {\n";
1586 Result += "\tlong sel_ref_cnt;\n";
1587 Result += "\tSEL *refs;\n";
1588 Result += "\tshort cls_def_cnt;\n";
1589 Result += "\tshort cat_def_cnt;\n";
1590 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1591 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001592
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001593 Result += "static struct _objc_symtab "
1594 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1595 Result += "\t0, 0, " + utostr(ClsDefCount)
1596 + ", " + utostr(CatDefCount) + "\n";
1597 for (int i = 0; i < ClsDefCount; i++) {
1598 Result += "\t,&_OBJC_CLASS_";
1599 Result += ClassImplementation[i]->getName();
1600 Result += "\n";
1601 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001602
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001603 for (int i = 0; i < CatDefCount; i++) {
1604 Result += "\t,&_OBJC_CATEGORY_";
1605 Result += CategoryImplementation[i]->getClassInterface()->getName();
1606 Result += "_";
1607 Result += CategoryImplementation[i]->getName();
1608 Result += "\n";
1609 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001610
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001611 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001612
1613 // Write objc_module metadata
1614
1615 /*
1616 struct _objc_module {
1617 long version;
1618 long size;
1619 const char *name;
1620 struct _objc_symtab *symtab;
1621 }
1622 */
1623
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001624 Result += "\nstruct _objc_module {\n";
1625 Result += "\tlong version;\n";
1626 Result += "\tlong size;\n";
1627 Result += "\tconst char *name;\n";
1628 Result += "\tstruct _objc_symtab *symtab;\n";
1629 Result += "};\n\n";
1630 Result += "static struct _objc_module "
1631 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001632 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1633 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001634 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001635}
Chris Lattner311ff022007-10-16 22:36:42 +00001636