blob: 68ba314c11612e6c400efd49e9fe53b6f69d0d42 [file] [log] [blame]
Steve Naroff44e81222008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnerb429ae42007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb429ae42007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremenek79b50cb2008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner569faa62007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff1c46cf12008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman6da15102008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattner673f2bd2008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000031using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000033
Steve Naroff1c46cf12008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattnerb429ae42007-10-11 00:43:27 +000038namespace {
Steve Naroff44e81222008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000046 SourceManager *SM;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner569faa62007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Narofffef037c2008-03-27 22:29:16 +000051
Ted Kremenek42730c52008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff04eaa192008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek42730c52008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffe9780582007-10-23 23:50:29 +000060
Steve Naroff47e7fa22008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffe9780582007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000074
Steve Naroff0add5d22007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroff0add5d22007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000078
Fariborz Jahanian22277422008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff764c1ae2007-11-15 10:28:18 +000082 // Needed for super.
Steve Naroff38a9e3f2008-10-27 17:20:55 +000083 ObjCMethodDecl *CurMethodDef;
Steve Naroff764c1ae2007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000086
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Narofffef037c2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff38a9e3f2008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Narofffef037c2008-03-27 22:29:16 +000099
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
107 FunctionDecl *CurFunctionDef;
Steve Naroff80c54752008-10-29 18:15:37 +0000108 VarDecl *GlobalVarDecl;
109
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000110 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +0000111 public:
Ted Kremenek79b50cb2008-05-31 20:11:04 +0000112 virtual void Initialize(ASTContext &context);
113
114 virtual void InitializeTU(TranslationUnit &TU) {
115 TU.SetOwnsDecls(false);
116 Initialize(TU.getContext());
117 }
Chris Lattner12499682008-01-31 19:38:44 +0000118
Chris Lattner569faa62007-10-11 18:38:32 +0000119
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000120 // Top Level Driver code.
121 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000122 void HandleDeclInMainFile(Decl *D);
Steve Naroff44e81222008-04-14 22:03:09 +0000123 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000124 Diagnostic &D, const LangOptions &LOpts);
Ted Kremenekcab0b0c2008-08-08 04:15:52 +0000125
126 ~RewriteObjC() {}
127
128 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerb1548372008-01-31 19:37:57 +0000129
130 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattner6216f292008-01-31 19:42:41 +0000131 // If replacement succeeded or warning disabled return with no warning.
132 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerb1548372008-01-31 19:37:57 +0000133 return;
134
Chris Lattner6948ae62008-11-18 07:04:44 +0000135 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
136 << Old->getSourceRange();
Chris Lattnerb1548372008-01-31 19:37:57 +0000137 }
138
Steve Narofffef037c2008-03-27 22:29:16 +0000139 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
140 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000141 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000142 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000143 SilenceRewriteMacroWarning)
144 return;
145
146 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
147 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000148
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000149 void RemoveText(SourceLocation Loc, unsigned StrLen) {
150 // If removal succeeded or warning disabled return with no warning.
151 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
152 return;
153
154 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
155 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000156
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000157 void ReplaceText(SourceLocation Start, unsigned OrigLength,
158 const char *NewStr, unsigned NewLength) {
159 // If removal succeeded or warning disabled return with no warning.
160 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
161 SilenceRewriteMacroWarning)
162 return;
163
164 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
165 }
166
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000167 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000168 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000169 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000170 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000171 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroff110be842008-12-01 20:33:01 +0000172 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID);
Ted Kremenek42730c52008-01-07 19:49:32 +0000173 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000174 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000175 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
176 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
177 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
178 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
179 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattnercffe3662008-03-16 21:23:50 +0000180 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000181 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000182 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000183 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000184 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000185 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000186 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000187 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000188 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000189
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000190 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000191 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000192 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000193 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff296b74f2007-11-05 14:50:49 +0000194 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000195 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000196 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000197 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000198 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000199 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000200 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
201 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
202 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000203 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
204 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000205 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
206 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000207 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000208 Stmt *RewriteBreakStmt(BreakStmt *S);
209 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000210 void SynthCountByEnumWithState(std::string &buf);
211
Steve Naroff02a82aa2007-10-30 23:14:51 +0000212 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000213 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000214 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000215 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000216 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000217 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000218 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000219 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000220 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000221 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000222
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000223 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000224 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000225 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000226
Ted Kremenek42730c52008-01-07 19:49:32 +0000227 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000228 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000229
Ted Kremenek42730c52008-01-07 19:49:32 +0000230 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
231 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000232 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000233 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000234 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000235 const char *ClassName,
236 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000237
Chris Lattner0be08822008-07-21 21:32:27 +0000238 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
239 &Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000240 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000241 const char *ClassName,
242 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000243 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000244 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000245 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
246 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000247 std::string &Result);
Steve Naroff21658f62008-11-13 20:07:04 +0000248 void RewriteImplementations();
249 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000250
251 // Block rewriting.
252 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
253 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
254
255 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
256 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
257
Steve Naroff80c54752008-10-29 18:15:37 +0000258 // Block specific rewrite rules.
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000259 void RewriteBlockCall(CallExpr *Exp);
260 void RewriteBlockPointerDecl(NamedDecl *VD);
261 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
262 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
263
264 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
265 const char *funcName, std::string Tag);
266 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
267 const char *funcName, std::string Tag);
268 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
269 bool hasCopyDisposeHelpers);
Steve Naroff85eb17b2008-10-30 10:07:53 +0000270 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000271 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
272 const char *FunName);
273
274 void CollectBlockDeclRefInfo(BlockExpr *Exp);
275 void GetBlockCallExprs(Stmt *S);
276 void GetBlockDeclRefExprs(Stmt *S);
277
278 // We avoid calling Type::isBlockPointerType(), since it operates on the
279 // canonical type. We only care if the top-level type is a closure pointer.
280 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
281
282 // FIXME: This predicate seems like it would be useful to add to ASTContext.
283 bool isObjCType(QualType T) {
284 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
285 return false;
286
287 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
288
289 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
290 OCT == Context->getCanonicalType(Context->getObjCClassType()))
291 return true;
292
293 if (const PointerType *PT = OCT->getAsPointerType()) {
294 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
295 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
296 return true;
297 }
298 return false;
299 }
300 bool PointerTypeTakesAnyBlockArguments(QualType QT);
301 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroff7f1412d2008-11-03 23:29:32 +0000302 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +0000303
304 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff80c54752008-10-29 18:15:37 +0000305 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000306 };
307}
308
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000309void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
310 NamedDecl *D) {
311 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
312 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
313 E = fproto->arg_type_end(); I && (I != E); ++I)
314 if (isBlockPointerType(*I)) {
315 // All the args are checked/rewritten. Don't call twice!
316 RewriteBlockPointerDecl(D);
317 break;
318 }
319 }
320}
321
322void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
323 const PointerType *PT = funcType->getAsPointerType();
324 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
325 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
326}
327
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000328static bool IsHeaderFile(const std::string &Filename) {
329 std::string::size_type DotPos = Filename.rfind('.');
330
331 if (DotPos == std::string::npos) {
332 // no file extension
333 return false;
334 }
335
336 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
337 // C header: .h
338 // C++ header: .hh or .H;
339 return Ext == "h" || Ext == "hh" || Ext == "H";
340}
341
Steve Naroff44e81222008-04-14 22:03:09 +0000342RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000343 Diagnostic &D, const LangOptions &LOpts)
344 : Diags(D), LangOpts(LOpts) {
345 IsHeader = IsHeaderFile(inFile);
346 InFileName = inFile;
347 OutFileName = outFile;
348 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
349 "rewriting sub-expression within a macro (may not be correct)");
350}
351
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000352ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000353 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000354 Diagnostic &Diags,
355 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000356 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000357}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000358
Steve Naroff44e81222008-04-14 22:03:09 +0000359void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000360 Context = &context;
361 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000362 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000363 MsgSendFunctionDecl = 0;
364 MsgSendSuperFunctionDecl = 0;
365 MsgSendStretFunctionDecl = 0;
366 MsgSendSuperStretFunctionDecl = 0;
367 MsgSendFpretFunctionDecl = 0;
368 GetClassFunctionDecl = 0;
369 GetMetaClassFunctionDecl = 0;
370 SelGetUidFunctionDecl = 0;
371 CFStringFunctionDecl = 0;
372 GetProtocolFunctionDecl = 0;
373 ConstantStringClassReference = 0;
374 NSStringRecord = 0;
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000375 CurMethodDef = 0;
376 CurFunctionDef = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000377 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000378 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000379 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000380 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000381 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000382
383 // Get the ID and start/end of the main file.
384 MainFileID = SM->getMainFileID();
385 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
386 MainFileStart = MainBuf->getBufferStart();
387 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000388
Chris Lattner12499682008-01-31 19:38:44 +0000389 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000390
Chris Lattner12499682008-01-31 19:38:44 +0000391 // declaring objc_selector outside the parameter list removes a silly
392 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000393 if (IsHeader)
394 Preamble = "#pragma once\n";
395 Preamble += "struct objc_selector; struct objc_class;\n";
396 Preamble += "#ifndef OBJC_SUPER\n";
397 Preamble += "struct objc_super { struct objc_object *object; ";
398 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000399 if (LangOpts.Microsoft) {
400 // Add a constructor for creating temporary objects.
Steve Narofffef037c2008-03-27 22:29:16 +0000401 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
402 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000403 }
Steve Narofffef037c2008-03-27 22:29:16 +0000404 Preamble += "};\n";
405 Preamble += "#define OBJC_SUPER\n";
406 Preamble += "#endif\n";
407 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
408 Preamble += "typedef struct objc_object Protocol;\n";
409 Preamble += "#define _REWRITER_typedef_Protocol\n";
410 Preamble += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000411 if (LangOpts.Microsoft)
Steve Naroff618c6a42008-05-06 22:45:19 +0000412 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
413 else
414 Preamble += "#define __OBJC_RW_EXTERN extern\n";
415 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000416 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000417 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000418 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000419 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000420 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000421 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000422 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff31316a12008-05-08 22:02:18 +0000423 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000424 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroffa9636222008-05-08 17:52:16 +0000425 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000426 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000427 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000428 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000429 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
430 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
431 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
432 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
433 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000434 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000435 // @synchronized hooks.
436 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
437 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000438 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000439 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
440 Preamble += "struct __objcFastEnumerationState {\n\t";
441 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000442 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000443 Preamble += "unsigned long *mutationsPtr;\n\t";
444 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff37157242008-06-02 20:23:21 +0000445 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000446 Preamble += "#define __FASTENUMERATIONSTATE\n";
447 Preamble += "#endif\n";
448 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
449 Preamble += "struct __NSConstantStringImpl {\n";
450 Preamble += " int *isa;\n";
451 Preamble += " int flags;\n";
452 Preamble += " char *str;\n";
453 Preamble += " long length;\n";
454 Preamble += "};\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000455 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
456 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
457 Preamble += "#else\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000458 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000459 Preamble += "#endif\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000460 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
461 Preamble += "#endif\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000462 // Blocks preamble.
463 Preamble += "#ifndef BLOCK_IMPL\n";
464 Preamble += "#define BLOCK_IMPL\n";
465 Preamble += "struct __block_impl {\n";
466 Preamble += " void *isa;\n";
467 Preamble += " int Flags;\n";
468 Preamble += " int Size;\n";
469 Preamble += " void *FuncPtr;\n";
470 Preamble += "};\n";
471 Preamble += "enum {\n";
472 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
473 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
474 Preamble += "};\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000475 Preamble += "// Runtime copy/destroy helper functions\n";
476 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
477 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
478 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
479 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
480 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
481 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
482 Preamble += "#endif\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000483 if (LangOpts.Microsoft) {
484 Preamble += "#undef __OBJC_RW_EXTERN\n";
485 Preamble += "#define __attribute__(X)\n";
486 }
Chris Lattner12499682008-01-31 19:38:44 +0000487}
488
489
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000490//===----------------------------------------------------------------------===//
491// Top Level Driver Code
492//===----------------------------------------------------------------------===//
493
Steve Naroff44e81222008-04-14 22:03:09 +0000494void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000495 // Two cases: either the decl could be in the main file, or it could be in a
496 // #included file. If the former, rewrite it now. If the later, check to see
497 // if we rewrote the #include/#import.
498 SourceLocation Loc = D->getLocation();
499 Loc = SM->getLogicalLoc(Loc);
500
501 // If this is for a builtin, ignore it.
502 if (Loc.isInvalid()) return;
503
Steve Naroffe9780582007-10-23 23:50:29 +0000504 // Look for built-in declarations that we need to refer during the rewrite.
505 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000506 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000507 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000508 // declared in <Foundation/NSString.h>
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000509 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000510 ConstantStringClassReference = FVD;
511 return;
512 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000513 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000514 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000515 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000516 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000517 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000518 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000519 } else if (ObjCForwardProtocolDecl *FP =
520 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000521 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000522 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000523 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000524 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000525 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000526}
527
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000528//===----------------------------------------------------------------------===//
529// Syntactic (non-AST) Rewriting Code
530//===----------------------------------------------------------------------===//
531
Steve Naroff44e81222008-04-14 22:03:09 +0000532void RewriteObjC::RewriteInclude() {
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000533 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
534 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
535 const char *MainBufStart = MainBuf.first;
536 const char *MainBufEnd = MainBuf.second;
537 size_t ImportLen = strlen("import");
538 size_t IncludeLen = strlen("include");
539
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000540 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000541 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
542 if (*BufPtr == '#') {
543 if (++BufPtr == MainBufEnd)
544 return;
545 while (*BufPtr == ' ' || *BufPtr == '\t')
546 if (++BufPtr == MainBufEnd)
547 return;
548 if (!strncmp(BufPtr, "import", ImportLen)) {
549 // replace import with include
550 SourceLocation ImportLoc =
551 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000552 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000553 BufPtr += ImportLen;
554 }
555 }
556 }
Chris Lattner74db1682007-10-16 21:07:07 +0000557}
558
Steve Naroff44e81222008-04-14 22:03:09 +0000559void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000560 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
561 const char *MainBufStart = MainBuf.first;
562 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000563
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000564 // Loop over the whole file, looking for tabs.
565 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
566 if (*BufPtr != '\t')
567 continue;
568
569 // Okay, we found a tab. This tab will turn into at least one character,
570 // but it depends on which 'virtual column' it is in. Compute that now.
571 unsigned VCol = 0;
572 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
573 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
574 ++VCol;
575
576 // Okay, now that we know the virtual column, we know how many spaces to
577 // insert. We assume 8-character tab-stops.
578 unsigned Spaces = 8-(VCol & 7);
579
580 // Get the location of the tab.
581 SourceLocation TabLoc =
582 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
583
584 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000585 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000586 }
Chris Lattner569faa62007-10-11 18:38:32 +0000587}
588
Steve Naroff121ed222008-12-02 15:48:25 +0000589static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
590 ObjCIvarDecl *OID) {
591 std::string S;
592 S = "((struct ";
593 S += ClassDecl->getIdentifier()->getName();
594 S += "_IMPL *)self)->";
595 S += OID->getNameAsCString();
596 return S;
597}
598
Steve Naroff110be842008-12-01 20:33:01 +0000599void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID) {
600 SourceLocation startLoc = PID->getLocStart();
601 InsertText(startLoc, "// ", 3);
Steve Naroff121ed222008-12-02 15:48:25 +0000602 const char *startBuf = SM->getCharacterData(startLoc);
603 assert((*startBuf == '@') && "bogus @synthesize location");
604 const char *semiBuf = strchr(startBuf, ';');
605 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
606 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
607
608 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
609 return; // FIXME: is this correct?
610
611 // Generate the 'getter' function.
Steve Naroff121ed222008-12-02 15:48:25 +0000612 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff121ed222008-12-02 15:48:25 +0000613 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff121ed222008-12-02 15:48:25 +0000614 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000615
616 if (!OID)
617 return;
618
619 std::string Getr;
620 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
621 Getr += "{ ";
622 // Synthesize an explicit cast to gain access to the ivar.
623 Getr += "return " + getIvarAccessString(ClassDecl, OID);
624 Getr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000625 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
626
627 if (PD->isReadOnly())
628 return;
629
630 // Generate the 'setter' function.
631 std::string Setr;
632 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff121ed222008-12-02 15:48:25 +0000633 Setr += "{ ";
Steve Naroff1e7b7962008-12-02 16:05:55 +0000634 // Synthesize an explicit cast to initialize the ivar.
635 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
636 Setr += OID->getNameAsCString();
637 Setr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000638 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroff110be842008-12-01 20:33:01 +0000639}
Chris Lattner569faa62007-10-11 18:38:32 +0000640
Steve Naroff44e81222008-04-14 22:03:09 +0000641void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000642 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000643 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000644
645 // Get the start location and compute the semi location.
646 SourceLocation startLoc = ClassDecl->getLocation();
647 const char *startBuf = SM->getCharacterData(startLoc);
648 const char *semiPtr = strchr(startBuf, ';');
649
650 // Translate to typedef's that forward reference structs with the same name
651 // as the class. As a convenience, we include the original declaration
652 // as a comment.
653 std::string typedefString;
654 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000655 typedefString.append(startBuf, semiPtr-startBuf+1);
656 typedefString += "\n";
657 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000658 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000659 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000660 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000661 typedefString += "\n";
662 typedefString += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000663 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000664 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000665 typedefString += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000666 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000667 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000668 }
669
670 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000671 ReplaceText(startLoc, semiPtr-startBuf+1,
672 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000673}
674
Steve Naroff44e81222008-04-14 22:03:09 +0000675void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000676 SourceLocation LocStart = Method->getLocStart();
677 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000678
Steve Naroff2ce399a2007-12-14 23:37:57 +0000679 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff99f50fe2008-10-21 13:37:27 +0000680 InsertText(LocStart, "#if 0\n", 6);
681 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000682 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000683 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000684 }
685}
686
Steve Naroff44e81222008-04-14 22:03:09 +0000687void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000688{
Chris Lattnercffe3662008-03-16 21:23:50 +0000689 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000690 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000691 SourceLocation Loc = Property->getLocation();
692
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000693 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000694
695 // FIXME: handle properties that are declared across multiple lines.
696 }
697}
698
Steve Naroff44e81222008-04-14 22:03:09 +0000699void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000700 SourceLocation LocStart = CatDecl->getLocStart();
701
702 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000703 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000704
Ted Kremenek42730c52008-01-07 19:49:32 +0000705 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000706 E = CatDecl->instmeth_end(); I != E; ++I)
707 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000708 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000709 E = CatDecl->classmeth_end(); I != E; ++I)
710 RewriteMethodDeclaration(*I);
711
Steve Naroff667f1682007-10-30 13:30:57 +0000712 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000713 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000714}
715
Steve Naroff44e81222008-04-14 22:03:09 +0000716void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000717 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000718
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000719 SourceLocation LocStart = PDecl->getLocStart();
720
721 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000722 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000723
Ted Kremenek42730c52008-01-07 19:49:32 +0000724 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000725 E = PDecl->instmeth_end(); I != E; ++I)
726 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000727 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000728 E = PDecl->classmeth_end(); I != E; ++I)
729 RewriteMethodDeclaration(*I);
730
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000731 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000732 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000733 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000734
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000735 // Must comment out @optional/@required
736 const char *startBuf = SM->getCharacterData(LocStart);
737 const char *endBuf = SM->getCharacterData(LocEnd);
738 for (const char *p = startBuf; p < endBuf; p++) {
739 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
740 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000741 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000742 ReplaceText(OptionalLoc, strlen("@optional"),
743 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000744
745 }
746 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
747 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000748 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000749 ReplaceText(OptionalLoc, strlen("@required"),
750 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000751
752 }
753 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000754}
755
Steve Naroff44e81222008-04-14 22:03:09 +0000756void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000757 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000758 if (LocStart.isInvalid())
759 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000760 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000761 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000762}
763
Steve Naroff44e81222008-04-14 22:03:09 +0000764void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000765 std::string &ResultStr) {
Steve Naroff6449c6c2008-10-30 12:09:33 +0000766 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff91044cf2008-07-16 14:40:40 +0000767 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000768 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000769 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000770 ResultStr += "id";
Steve Naroff91044cf2008-07-16 14:40:40 +0000771 else if (OMD->getResultType()->isFunctionPointerType()) {
772 // needs special handling, since pointer-to-functions have special
773 // syntax (where a decaration models use).
774 QualType retType = OMD->getResultType();
775 if (const PointerType* PT = retType->getAsPointerType()) {
776 QualType PointeeTy = PT->getPointeeType();
777 if ((FPRetType = PointeeTy->getAsFunctionType())) {
778 ResultStr += FPRetType->getResultType().getAsString();
779 ResultStr += "(*";
780 }
781 }
782 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000783 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000784 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000785
786 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000787 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000788
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000789 if (OMD->isInstance())
790 NameStr += "_I_";
791 else
792 NameStr += "_C_";
793
Chris Lattner271d4c22008-11-24 05:29:24 +0000794 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000795 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000796
797 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000798 if (ObjCCategoryImplDecl *CID =
799 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000800 NameStr += CID->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000801 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000802 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000803 // Append selector names, replacing ':' with '_'
Chris Lattner3a8f2942008-11-24 03:33:13 +0000804 {
805 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000806 int len = selString.size();
807 for (int i = 0; i < len; i++)
808 if (selString[i] == ':')
809 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000810 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000811 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000812 // Remember this name for metadata emission
813 MethodInternalNames[OMD] = NameStr;
814 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000815
816 // Rewrite arguments
817 ResultStr += "(";
818
819 // invisible arguments
820 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000821 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000822 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000823 if (!LangOpts.Microsoft) {
824 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
825 ResultStr += "struct ";
826 }
827 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattner271d4c22008-11-24 05:29:24 +0000828 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +0000829 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000830 }
831 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000832 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000833
834 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000835 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000836 ResultStr += " _cmd";
837
838 // Method arguments.
Chris Lattner685d7922008-03-16 01:07:14 +0000839 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000840 ParmVarDecl *PDecl = OMD->getParamDecl(i);
841 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000842 if (PDecl->getType()->isObjCQualifiedIdType()) {
843 ResultStr += "id ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000844 ResultStr += PDecl->getNameAsString();
Steve Naroff133dfda2008-04-18 21:13:19 +0000845 } else {
Chris Lattner271d4c22008-11-24 05:29:24 +0000846 std::string Name = PDecl->getNameAsString();
Steve Naroff4e2ae512008-10-30 14:45:29 +0000847 if (isBlockPointerType(PDecl->getType())) {
848 // Make sure we convert "t (^)(...)" to "t (*)(...)".
849 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
850 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
851 } else
852 PDecl->getType().getAsStringInternal(Name);
Steve Naroff133dfda2008-04-18 21:13:19 +0000853 ResultStr += Name;
854 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000855 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000856 if (OMD->isVariadic())
857 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000858 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000859
Steve Naroff91044cf2008-07-16 14:40:40 +0000860 if (FPRetType) {
861 ResultStr += ")"; // close the precedence "scope" for "*".
862
863 // Now, emit the argument types (if any).
864 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
865 ResultStr += "(";
866 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
867 if (i) ResultStr += ", ";
868 std::string ParamStr = FT->getArgType(i).getAsString();
869 ResultStr += ParamStr;
870 }
871 if (FT->isVariadic()) {
872 if (FT->getNumArgs()) ResultStr += ", ";
873 ResultStr += "...";
874 }
875 ResultStr += ")";
876 } else {
877 ResultStr += "()";
878 }
879 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000880}
Steve Naroff44e81222008-04-14 22:03:09 +0000881void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000882 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
883 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000884
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000885 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000886 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000887 else
Chris Lattner6216f292008-01-31 19:42:41 +0000888 InsertText(CID->getLocStart(), "// ", 3);
Steve Naroff21658f62008-11-13 20:07:04 +0000889
Ted Kremenek42730c52008-01-07 19:49:32 +0000890 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000891 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
892 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000893 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000894 ObjCMethodDecl *OMD = *I;
895 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000896 SourceLocation LocStart = OMD->getLocStart();
897 SourceLocation LocEnd = OMD->getBody()->getLocStart();
898
899 const char *startBuf = SM->getCharacterData(LocStart);
900 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000901 ReplaceText(LocStart, endBuf-startBuf,
902 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000903 }
904
Ted Kremenek42730c52008-01-07 19:49:32 +0000905 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000906 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
907 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000908 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000909 ObjCMethodDecl *OMD = *I;
910 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000911 SourceLocation LocStart = OMD->getLocStart();
912 SourceLocation LocEnd = OMD->getBody()->getLocStart();
913
914 const char *startBuf = SM->getCharacterData(LocStart);
915 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000916 ReplaceText(LocStart, endBuf-startBuf,
917 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000918 }
Steve Naroff110be842008-12-01 20:33:01 +0000919 for (ObjCCategoryImplDecl::propimpl_iterator
920 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
921 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
922 RewritePropertyImplDecl(*I);
923 }
924
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000925 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000926 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000927 else
Chris Lattner6216f292008-01-31 19:42:41 +0000928 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000929}
930
Steve Naroff44e81222008-04-14 22:03:09 +0000931void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000932 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000933 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000934 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000935 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000936 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000937 ResultStr += "\n";
938 ResultStr += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000939 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000940 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000941 ResultStr += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000942 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000943 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000944 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000945 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000946 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000947 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000948
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000949 RewriteProperties(ClassDecl->getNumPropertyDecl(),
950 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000951 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000952 E = ClassDecl->instmeth_end(); I != E; ++I)
953 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000954 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000955 E = ClassDecl->classmeth_end(); I != E; ++I)
956 RewriteMethodDeclaration(*I);
957
Steve Naroff1ccf4632007-10-30 03:43:13 +0000958 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000959 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000960}
961
Chris Lattner343c82b2008-05-23 20:40:52 +0000962Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
963 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000964 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000965 if (CurMethodDef) {
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000966 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000967 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
968 // lookup which class implements the instance variable.
969 ObjCInterfaceDecl *clsDeclared = 0;
970 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
971 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
972
973 // Synthesize an explicit cast to gain access to the ivar.
974 std::string RecName = clsDeclared->getIdentifier()->getName();
975 RecName += "_IMPL";
976 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000977 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +0000978 SourceLocation(), II);
Steve Naroffa9636222008-05-08 17:52:16 +0000979 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
980 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor035d0882008-10-28 15:36:24 +0000981 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroff7f1412d2008-11-03 23:29:32 +0000982 SourceLocation(), SourceLocation());
Steve Naroffa9636222008-05-08 17:52:16 +0000983 // Don't forget the parens to enforce the proper binding.
Chris Lattner343c82b2008-05-23 20:40:52 +0000984 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
985 IV->getBase()->getLocEnd(),
986 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +0000987 if (IV->isFreeIvar() &&
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000988 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner343c82b2008-05-23 20:40:52 +0000989 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
990 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +0000991 ReplaceStmt(IV, ME);
992 delete IV;
993 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +0000994 }
Chris Lattner343c82b2008-05-23 20:40:52 +0000995
996 ReplaceStmt(IV->getBase(), PE);
997 // Cannot delete IV->getBase(), since PE points to it.
998 // Replace the old base with the cast. This is important when doing
999 // embedded rewrites. For example, [newInv->_container addObject:0].
1000 IV->setBase(PE);
1001 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +00001002 }
Steve Naroffe6155362008-04-18 21:55:08 +00001003 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +00001004 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1005
1006 // Explicit ivar refs need to have a cast inserted.
1007 // FIXME: consider sharing some of this code with the code above.
1008 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +00001009 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001010 // lookup which class implements the instance variable.
1011 ObjCInterfaceDecl *clsDeclared = 0;
Steve Naroffa9636222008-05-08 17:52:16 +00001012 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001013 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1014
1015 // Synthesize an explicit cast to gain access to the ivar.
1016 std::string RecName = clsDeclared->getIdentifier()->getName();
1017 RecName += "_IMPL";
1018 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001019 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001020 SourceLocation(), II);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001021 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1022 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor035d0882008-10-28 15:36:24 +00001023 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroff7f1412d2008-11-03 23:29:32 +00001024 SourceLocation(), SourceLocation());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001025 // Don't forget the parens to enforce the proper binding.
Chris Lattner3cca6612008-05-28 16:38:23 +00001026 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1027 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001028 ReplaceStmt(IV->getBase(), PE);
1029 // Cannot delete IV->getBase(), since PE points to it.
1030 // Replace the old base with the cast. This is important when doing
1031 // embedded rewrites. For example, [newInv->_container addObject:0].
1032 IV->setBase(PE);
1033 return IV;
1034 }
Steve Naroff292b7b92007-11-15 11:33:00 +00001035 }
Steve Naroffe6155362008-04-18 21:55:08 +00001036 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +00001037}
1038
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001039/// SynthCountByEnumWithState - To print:
1040/// ((unsigned int (*)
1041/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1042/// (void *)objc_msgSend)((id)l_collection,
1043/// sel_registerName(
1044/// "countByEnumeratingWithState:objects:count:"),
1045/// &enumState,
1046/// (id *)items, (unsigned int)16)
1047///
Steve Naroff44e81222008-04-14 22:03:09 +00001048void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001049 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1050 "id *, unsigned int))(void *)objc_msgSend)";
1051 buf += "\n\t\t";
1052 buf += "((id)l_collection,\n\t\t";
1053 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1054 buf += "\n\t\t";
1055 buf += "&enumState, "
1056 "(id *)items, (unsigned int)16)";
1057}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001058
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001059/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1060/// statement to exit to its outer synthesized loop.
1061///
Steve Naroff44e81222008-04-14 22:03:09 +00001062Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001063 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1064 return S;
1065 // replace break with goto __break_label
1066 std::string buf;
1067
1068 SourceLocation startLoc = S->getLocStart();
1069 buf = "goto __break_label_";
1070 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001071 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001072
1073 return 0;
1074}
1075
1076/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1077/// statement to continue with its inner synthesized loop.
1078///
Steve Naroff44e81222008-04-14 22:03:09 +00001079Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001080 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1081 return S;
1082 // replace continue with goto __continue_label
1083 std::string buf;
1084
1085 SourceLocation startLoc = S->getLocStart();
1086 buf = "goto __continue_label_";
1087 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001088 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001089
1090 return 0;
1091}
1092
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001093/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001094/// It rewrites:
1095/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001096
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001097/// Into:
1098/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001099/// type elem;
1100/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001101/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001102/// id l_collection = (id)collection;
1103/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1104/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001105/// if (limit) {
1106/// unsigned long startMutations = *enumState.mutationsPtr;
1107/// do {
1108/// unsigned long counter = 0;
1109/// do {
1110/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001111/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001112/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001113/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001114/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001115/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001116/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1117/// objects:items count:16]);
1118/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001119/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001120/// }
1121/// else
1122/// elem = nil;
1123/// }
1124///
Steve Naroff44e81222008-04-14 22:03:09 +00001125Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001126 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001127 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1128 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1129 "ObjCForCollectionStmt Statement stack mismatch");
1130 assert(!ObjCBcLabelNo.empty() &&
1131 "ObjCForCollectionStmt - Label No stack empty");
1132
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001133 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001134 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001135 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001136 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001137 std::string buf;
1138 buf = "\n{\n\t";
1139 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1140 // type elem;
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001141 ScopedDecl* D = DS->getSolitaryDecl();
1142 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001143 elementTypeAsString = ElementType.getAsString();
1144 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001145 buf += " ";
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001146 elementName = D->getNameAsCString();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001147 buf += elementName;
1148 buf += ";\n\t";
1149 }
Chris Lattner690c2872008-04-08 05:52:18 +00001150 else {
1151 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001152 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001153 elementTypeAsString
1154 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001155 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001156
1157 // struct __objcFastEnumerationState enumState = { 0 };
1158 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1159 // id items[16];
1160 buf += "id items[16];\n\t";
1161 // id l_collection = (id)
1162 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001163 // Find start location of 'collection' the hard way!
1164 const char *startCollectionBuf = startBuf;
1165 startCollectionBuf += 3; // skip 'for'
1166 startCollectionBuf = strchr(startCollectionBuf, '(');
1167 startCollectionBuf++; // skip '('
1168 // find 'in' and skip it.
1169 while (*startCollectionBuf != ' ' ||
1170 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1171 (*(startCollectionBuf+3) != ' ' &&
1172 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1173 startCollectionBuf++;
1174 startCollectionBuf += 3;
1175
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001176 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001177 ReplaceText(startLoc, startCollectionBuf - startBuf,
1178 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001179 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001180 SourceLocation rightParenLoc = S->getRParenLoc();
1181 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1182 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001183 buf = ";\n\t";
1184
1185 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1186 // objects:items count:16];
1187 // which is synthesized into:
1188 // unsigned int limit =
1189 // ((unsigned int (*)
1190 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1191 // (void *)objc_msgSend)((id)l_collection,
1192 // sel_registerName(
1193 // "countByEnumeratingWithState:objects:count:"),
1194 // (struct __objcFastEnumerationState *)&state,
1195 // (id *)items, (unsigned int)16);
1196 buf += "unsigned long limit =\n\t\t";
1197 SynthCountByEnumWithState(buf);
1198 buf += ";\n\t";
1199 /// if (limit) {
1200 /// unsigned long startMutations = *enumState.mutationsPtr;
1201 /// do {
1202 /// unsigned long counter = 0;
1203 /// do {
1204 /// if (startMutations != *enumState.mutationsPtr)
1205 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001206 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001207 buf += "if (limit) {\n\t";
1208 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1209 buf += "do {\n\t\t";
1210 buf += "unsigned long counter = 0;\n\t\t";
1211 buf += "do {\n\t\t\t";
1212 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1213 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1214 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001215 buf += " = (";
1216 buf += elementTypeAsString;
1217 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001218 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001219 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001220
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001221 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001222 /// } while (counter < limit);
1223 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1224 /// objects:items count:16]);
1225 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001226 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001227 /// }
1228 /// else
1229 /// elem = nil;
1230 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001231 ///
1232 buf = ";\n\t";
1233 buf += "__continue_label_";
1234 buf += utostr(ObjCBcLabelNo.back());
1235 buf += ": ;";
1236 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001237 buf += "} while (counter < limit);\n\t";
1238 buf += "} while (limit = ";
1239 SynthCountByEnumWithState(buf);
1240 buf += ");\n\t";
1241 buf += elementName;
1242 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001243 buf += "__break_label_";
1244 buf += utostr(ObjCBcLabelNo.back());
1245 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001246 buf += "}\n\t";
1247 buf += "else\n\t\t";
1248 buf += elementName;
1249 buf += " = nil;\n";
1250 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001251
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001252 // Insert all these *after* the statement body.
Steve Naroff5f238fe2008-07-21 18:26:02 +00001253 if (isa<CompoundStmt>(S->getBody())) {
1254 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1255 InsertText(endBodyLoc, buf.c_str(), buf.size());
1256 } else {
1257 /* Need to treat single statements specially. For example:
1258 *
1259 * for (A *a in b) if (stuff()) break;
1260 * for (A *a in b) xxxyy;
1261 *
1262 * The following code simply scans ahead to the semi to find the actual end.
1263 */
1264 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1265 const char *semiBuf = strchr(stmtBuf, ';');
1266 assert(semiBuf && "Can't find ';'");
1267 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1268 InsertText(endBodyLoc, buf.c_str(), buf.size());
1269 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001270 Stmts.pop_back();
1271 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001272 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001273}
1274
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001275/// RewriteObjCSynchronizedStmt -
1276/// This routine rewrites @synchronized(expr) stmt;
1277/// into:
1278/// objc_sync_enter(expr);
1279/// @try stmt @finally { objc_sync_exit(expr); }
1280///
Steve Naroff44e81222008-04-14 22:03:09 +00001281Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001282 // Get the start location and compute the semi location.
1283 SourceLocation startLoc = S->getLocStart();
1284 const char *startBuf = SM->getCharacterData(startLoc);
1285
1286 assert((*startBuf == '@') && "bogus @synchronized location");
1287
1288 std::string buf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001289 buf = "objc_sync_enter((id)";
1290 const char *lparenBuf = startBuf;
1291 while (*lparenBuf != '(') lparenBuf++;
1292 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroff027cd0b2008-08-19 13:04:19 +00001293 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1294 // the sync expression is typically a message expression that's already
1295 // been rewritten! (which implies the SourceLocation's are invalid).
1296 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001297 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroff027cd0b2008-08-19 13:04:19 +00001298 while (*endBuf != ')') endBuf--;
1299 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001300 buf = ");\n";
1301 // declare a new scope with two variables, _stack and _rethrow.
1302 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1303 buf += "int buf[18/*32-bit i386*/];\n";
1304 buf += "char *pointers[4];} _stack;\n";
1305 buf += "id volatile _rethrow = 0;\n";
1306 buf += "objc_exception_try_enter(&_stack);\n";
1307 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001308 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001309 startLoc = S->getSynchBody()->getLocEnd();
1310 startBuf = SM->getCharacterData(startLoc);
1311
Steve Naroff027cd0b2008-08-19 13:04:19 +00001312 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001313 SourceLocation lastCurlyLoc = startLoc;
1314 buf = "}\nelse {\n";
1315 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1316 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001317 buf += " objc_sync_exit(";
Douglas Gregor035d0882008-10-28 15:36:24 +00001318 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00001319 S->getSynchExpr(),
1320 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00001321 SourceLocation(), SourceLocation());
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001322 std::string syncExprBufS;
1323 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroffc1656a62008-08-21 13:03:03 +00001324 syncExpr->printPretty(syncExprBuf);
Steve Naroff17919b52008-07-16 19:47:39 +00001325 buf += syncExprBuf.str();
1326 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001327 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1328 buf += "}\n";
1329 buf += "}";
1330
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001331 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001332 return 0;
1333}
1334
Steve Naroff44e81222008-04-14 22:03:09 +00001335Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001336 // Get the start location and compute the semi location.
1337 SourceLocation startLoc = S->getLocStart();
1338 const char *startBuf = SM->getCharacterData(startLoc);
1339
1340 assert((*startBuf == '@') && "bogus @try location");
1341
1342 std::string buf;
1343 // declare a new scope with two variables, _stack and _rethrow.
1344 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1345 buf += "int buf[18/*32-bit i386*/];\n";
1346 buf += "char *pointers[4];} _stack;\n";
1347 buf += "id volatile _rethrow = 0;\n";
1348 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001349 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001350
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001351 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001352
1353 startLoc = S->getTryBody()->getLocEnd();
1354 startBuf = SM->getCharacterData(startLoc);
1355
1356 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001357
Steve Naroffe9f69842007-11-07 04:08:17 +00001358 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001359 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1360 if (catchList) {
1361 startLoc = startLoc.getFileLocWithOffset(1);
1362 buf = " /* @catch begin */ else {\n";
1363 buf += " id _caught = objc_exception_extract(&_stack);\n";
1364 buf += " objc_exception_try_enter (&_stack);\n";
1365 buf += " if (_setjmp(_stack.buf))\n";
1366 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1367 buf += " else { /* @catch continue */";
1368
1369 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff36269d22008-09-09 19:59:12 +00001370 } else { /* no catch list */
1371 buf = "}\nelse {\n";
1372 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1373 buf += "}";
1374 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff9d0ff352008-07-16 15:31:30 +00001375 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001376 bool sawIdTypedCatch = false;
1377 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001378 while (catchList) {
1379 Stmt *catchStmt = catchList->getCatchParamStmt();
1380
1381 if (catchList == S->getCatchStmts())
1382 buf = "if ("; // we are generating code for the first catch clause
1383 else
1384 buf = "else if (";
1385 startLoc = catchList->getLocStart();
1386 startBuf = SM->getCharacterData(startLoc);
1387
1388 assert((*startBuf == '@') && "bogus @catch location");
1389
1390 const char *lParenLoc = strchr(startBuf, '(');
1391
Steve Naroff397c4ce2008-02-01 22:08:12 +00001392 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001393 // Now rewrite the body...
1394 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001395 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1396 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001397 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1398 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001399 assert((*bodyBuf == '{') && "bogus @catch body location");
1400
1401 buf += "1) { id _tmp = _caught;";
1402 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1403 buf.c_str(), buf.size());
1404 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek91034202008-10-06 22:39:38 +00001405 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001406 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001407 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001408 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001409 sawIdTypedCatch = true;
1410 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001411 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001412
Ted Kremenek42730c52008-01-07 19:49:32 +00001413 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001414 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001415 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00001416 buf += cls->getDecl()->getNameAsString();
Steve Naroffd3287d82007-11-07 18:43:40 +00001417 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001418 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001419 }
1420 }
1421 // Now rewrite the body...
1422 lastCatchBody = catchList->getCatchBody();
1423 SourceLocation rParenLoc = catchList->getRParenLoc();
1424 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1425 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1426 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1427 assert((*rParenBuf == ')') && "bogus @catch paren location");
1428 assert((*bodyBuf == '{') && "bogus @catch body location");
1429
1430 buf = " = _caught;";
1431 // Here we replace ") {" with "= _caught;" (which initializes and
1432 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001433 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001434 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001435 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001436 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001437 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001438 catchList = catchList->getNextCatchStmt();
1439 }
1440 // Complete the catch list...
1441 if (lastCatchBody) {
1442 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001443 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1444 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001445
Steve Naroff31325c12008-09-11 15:29:03 +00001446 // Insert the last (implicit) else clause *before* the right curly brace.
1447 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1448 buf = "} /* last catch end */\n";
1449 buf += "else {\n";
1450 buf += " _rethrow = _caught;\n";
1451 buf += " objc_exception_try_exit(&_stack);\n";
1452 buf += "} } /* @catch end */\n";
1453 if (!S->getFinallyStmt())
1454 buf += "}\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001455 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001456
1457 // Set lastCurlyLoc
1458 lastCurlyLoc = lastCatchBody->getLocEnd();
1459 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001460 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001461 startLoc = finalStmt->getLocStart();
1462 startBuf = SM->getCharacterData(startLoc);
1463 assert((*startBuf == '@') && "bogus @finally start");
1464
1465 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001466 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001467
1468 Stmt *body = finalStmt->getFinallyBody();
1469 SourceLocation startLoc = body->getLocStart();
1470 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001471 assert(*SM->getCharacterData(startLoc) == '{' &&
1472 "bogus @finally body location");
1473 assert(*SM->getCharacterData(endLoc) == '}' &&
1474 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001475
1476 startLoc = startLoc.getFileLocWithOffset(1);
1477 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001478 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001479 endLoc = endLoc.getFileLocWithOffset(-1);
1480 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001481 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001482
1483 // Set lastCurlyLoc
1484 lastCurlyLoc = body->getLocEnd();
Steve Naroff31325c12008-09-11 15:29:03 +00001485 } else { /* no finally clause - make sure we synthesize an implicit one */
1486 buf = "{ /* implicit finally clause */\n";
1487 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1488 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1489 buf += "}";
1490 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001491 }
1492 // Now emit the final closing curly brace...
1493 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1494 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001495 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001496 return 0;
1497}
1498
Steve Naroff44e81222008-04-14 22:03:09 +00001499Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001500 return 0;
1501}
1502
Steve Naroff44e81222008-04-14 22:03:09 +00001503Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001504 return 0;
1505}
1506
Chris Lattnerb1548372008-01-31 19:37:57 +00001507// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001508// the throw expression is typically a message expression that's already
1509// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001510Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001511 // Get the start location and compute the semi location.
1512 SourceLocation startLoc = S->getLocStart();
1513 const char *startBuf = SM->getCharacterData(startLoc);
1514
1515 assert((*startBuf == '@') && "bogus @throw location");
1516
1517 std::string buf;
1518 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001519 if (S->getThrowExpr())
1520 buf = "objc_exception_throw(";
1521 else // add an implicit argument
1522 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001523
1524 // handle "@ throw" correctly.
1525 const char *wBuf = strchr(startBuf, 'w');
1526 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1527 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1528
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001529 const char *semiBuf = strchr(startBuf, ';');
1530 assert((*semiBuf == ';') && "@throw: can't find ';'");
1531 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1532 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001533 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001534 return 0;
1535}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001536
Steve Naroff44e81222008-04-14 22:03:09 +00001537Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001538 // Create a new string expression.
1539 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001540 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001541 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001542 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1543 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001544 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001545 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001546
Chris Lattner4478db92007-11-30 22:53:43 +00001547 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001548 delete Exp;
1549 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001550}
1551
Steve Naroff44e81222008-04-14 22:03:09 +00001552Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff296b74f2007-11-05 14:50:49 +00001553 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1554 // Create a call to sel_registerName("selName").
1555 llvm::SmallVector<Expr*, 8> SelExprs;
1556 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner3a8f2942008-11-24 03:33:13 +00001557 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1558 Exp->getSelector().getAsString().size(),
Steve Naroff296b74f2007-11-05 14:50:49 +00001559 false, argType, SourceLocation(),
1560 SourceLocation()));
1561 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1562 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001563 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001564 delete Exp;
1565 return SelExp;
1566}
1567
Steve Naroff44e81222008-04-14 22:03:09 +00001568CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001569 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001570 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001571 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001572
1573 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001574 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001575
1576 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001577 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregor70d26122008-11-12 17:17:38 +00001578 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1579 /*isLvalue=*/false);
Steve Naroffe9780582007-10-23 23:50:29 +00001580
1581 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001582
Steve Naroff71226032007-10-24 22:48:43 +00001583 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1584}
1585
Steve Naroffc8a92d12007-11-01 13:24:47 +00001586static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1587 const char *&startRef, const char *&endRef) {
1588 while (startBuf < endBuf) {
1589 if (*startBuf == '<')
1590 startRef = startBuf; // mark the start.
1591 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001592 if (startRef && *startRef == '<') {
1593 endRef = startBuf; // mark the end.
1594 return true;
1595 }
1596 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001597 }
1598 startBuf++;
1599 }
1600 return false;
1601}
1602
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001603static void scanToNextArgument(const char *&argRef) {
1604 int angle = 0;
1605 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1606 if (*argRef == '<')
1607 angle++;
1608 else if (*argRef == '>')
1609 angle--;
1610 argRef++;
1611 }
1612 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1613}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001614
Steve Naroff44e81222008-04-14 22:03:09 +00001615bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001616
Ted Kremenek42730c52008-01-07 19:49:32 +00001617 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001618 return true;
1619
Steve Naroffc8a92d12007-11-01 13:24:47 +00001620 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001621 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001622 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001623 return true; // we have "Class <Protocol> *".
1624 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001625 return false;
1626}
1627
Steve Naroffd06c88d2008-07-29 18:15:38 +00001628void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1629 QualType Type = E->getType();
1630 if (needToScanForQualifiers(Type)) {
Steve Narofff31ece92008-11-19 21:15:47 +00001631 SourceLocation Loc, EndLoc;
1632
1633 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1634 Loc = ECE->getLParenLoc();
1635 EndLoc = ECE->getRParenLoc();
1636 } else {
1637 Loc = E->getLocStart();
1638 EndLoc = E->getLocEnd();
1639 }
1640 // This will defend against trying to rewrite synthesized expressions.
1641 if (Loc.isInvalid() || EndLoc.isInvalid())
1642 return;
1643
Steve Naroffd06c88d2008-07-29 18:15:38 +00001644 const char *startBuf = SM->getCharacterData(Loc);
Steve Narofff31ece92008-11-19 21:15:47 +00001645 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroffd06c88d2008-07-29 18:15:38 +00001646 const char *startRef = 0, *endRef = 0;
1647 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1648 // Get the locations of the startRef, endRef.
1649 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1650 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1651 // Comment out the protocol references.
1652 InsertText(LessLoc, "/*", 2);
1653 InsertText(GreaterLoc, "*/", 2);
1654 }
1655 }
1656}
1657
Steve Naroff44e81222008-04-14 22:03:09 +00001658void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001659 SourceLocation Loc;
1660 QualType Type;
1661 const FunctionTypeProto *proto = 0;
1662 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1663 Loc = VD->getLocation();
1664 Type = VD->getType();
1665 }
1666 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1667 Loc = FD->getLocation();
1668 // Check for ObjC 'id' and class types that have been adorned with protocol
1669 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1670 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1671 assert(funcType && "missing function type");
1672 proto = dyn_cast<FunctionTypeProto>(funcType);
1673 if (!proto)
1674 return;
1675 Type = proto->getResultType();
1676 }
1677 else
1678 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001679
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001680 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001681 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001682
1683 const char *endBuf = SM->getCharacterData(Loc);
1684 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001685 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001686 startBuf--; // scan backward (from the decl location) for return type.
1687 const char *startRef = 0, *endRef = 0;
1688 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1689 // Get the locations of the startRef, endRef.
1690 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1691 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1692 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001693 InsertText(LessLoc, "/*", 2);
1694 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001695 }
1696 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001697 if (!proto)
1698 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001699 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001700 const char *startBuf = SM->getCharacterData(Loc);
1701 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001702 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1703 if (needToScanForQualifiers(proto->getArgType(i))) {
1704 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001705
Steve Naroffc8a92d12007-11-01 13:24:47 +00001706 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001707 // scan forward (from the decl location) for argument types.
1708 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001709 const char *startRef = 0, *endRef = 0;
1710 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1711 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001712 SourceLocation LessLoc =
1713 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1714 SourceLocation GreaterLoc =
1715 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001716 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001717 InsertText(LessLoc, "/*", 2);
1718 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001719 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001720 startBuf = ++endBuf;
1721 }
1722 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001723 // If the function name is derived from a macro expansion, then the
1724 // argument buffer will not follow the name. Need to speak with Chris.
1725 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001726 startBuf++; // scan forward (from the decl location) for argument types.
1727 startBuf++;
1728 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001729 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001730}
1731
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001732// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001733void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001734 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1735 llvm::SmallVector<QualType, 16> ArgTys;
1736 ArgTys.push_back(Context->getPointerType(
1737 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001738 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001739 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001740 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001741 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001742 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001743 SelGetUidIdent, getFuncType,
1744 FunctionDecl::Extern, false, 0);
1745}
1746
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001747// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001748void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001749 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1750 llvm::SmallVector<QualType, 16> ArgTys;
1751 ArgTys.push_back(Context->getPointerType(
1752 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001753 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001754 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001755 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001756 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001757 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001758 SelGetProtoIdent, getFuncType,
1759 FunctionDecl::Extern, false, 0);
1760}
1761
Steve Naroff44e81222008-04-14 22:03:09 +00001762void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001763 // declared in <objc/objc.h>
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001764 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001765 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001766 return;
1767 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001768 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001769}
1770
Steve Naroffbec4bf52008-03-11 17:37:02 +00001771// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001772void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001773 if (SuperContructorFunctionDecl)
1774 return;
1775 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1776 llvm::SmallVector<QualType, 16> ArgTys;
1777 QualType argT = Context->getObjCIdType();
1778 assert(!argT.isNull() && "Can't find 'id' type");
1779 ArgTys.push_back(argT);
1780 ArgTys.push_back(argT);
1781 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1782 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001783 false, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001784 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001785 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001786 msgSendIdent, msgSendType,
1787 FunctionDecl::Extern, false, 0);
1788}
1789
Steve Naroff02a82aa2007-10-30 23:14:51 +00001790// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001791void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001792 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1793 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001794 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001795 assert(!argT.isNull() && "Can't find 'id' type");
1796 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001797 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001798 assert(!argT.isNull() && "Can't find 'SEL' type");
1799 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001800 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001801 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001802 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001803 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001804 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001805 msgSendIdent, msgSendType,
1806 FunctionDecl::Extern, false, 0);
1807}
1808
Steve Naroff764c1ae2007-11-15 10:28:18 +00001809// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001810void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001811 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1812 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001813 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001814 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001815 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00001816 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1817 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1818 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001819 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001820 assert(!argT.isNull() && "Can't find 'SEL' type");
1821 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001822 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001823 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001824 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001825 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001826 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001827 msgSendIdent, msgSendType,
1828 FunctionDecl::Extern, false, 0);
1829}
1830
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001831// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001832void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001833 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1834 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001835 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001836 assert(!argT.isNull() && "Can't find 'id' type");
1837 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001838 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001839 assert(!argT.isNull() && "Can't find 'SEL' type");
1840 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001841 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001842 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001843 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001844 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001845 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001846 msgSendIdent, msgSendType,
1847 FunctionDecl::Extern, false, 0);
1848}
1849
1850// SynthMsgSendSuperStretFunctionDecl -
1851// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001852void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001853 IdentifierInfo *msgSendIdent =
1854 &Context->Idents.get("objc_msgSendSuper_stret");
1855 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001856 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001857 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001858 &Context->Idents.get("objc_super"));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001859 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1860 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1861 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001862 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001863 assert(!argT.isNull() && "Can't find 'SEL' type");
1864 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001865 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001866 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001867 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001868 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00001869 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001870 msgSendIdent, msgSendType,
1871 FunctionDecl::Extern, false, 0);
1872}
1873
Steve Naroff31316a12008-05-08 22:02:18 +00001874// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001875void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001876 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1877 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001878 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001879 assert(!argT.isNull() && "Can't find 'id' type");
1880 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001881 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001882 assert(!argT.isNull() && "Can't find 'SEL' type");
1883 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00001884 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001885 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001886 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001887 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001888 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001889 msgSendIdent, msgSendType,
1890 FunctionDecl::Extern, false, 0);
1891}
1892
Steve Naroff02a82aa2007-10-30 23:14:51 +00001893// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001894void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001895 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1896 llvm::SmallVector<QualType, 16> ArgTys;
1897 ArgTys.push_back(Context->getPointerType(
1898 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001899 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001900 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001901 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001902 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001903 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001904 getClassIdent, getClassType,
1905 FunctionDecl::Extern, false, 0);
1906}
1907
Steve Naroff3b1caac2007-12-07 03:50:46 +00001908// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001909void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001910 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1911 llvm::SmallVector<QualType, 16> ArgTys;
1912 ArgTys.push_back(Context->getPointerType(
1913 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001914 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001915 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001916 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001917 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001918 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001919 getClassIdent, getClassType,
1920 FunctionDecl::Extern, false, 0);
1921}
1922
Steve Naroff44e81222008-04-14 22:03:09 +00001923Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001924 QualType strType = getConstantStringStructType();
1925
1926 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00001927
1928 std::string tmpName = InFileName;
1929 unsigned i;
1930 for (i=0; i < tmpName.length(); i++) {
1931 char c = tmpName.at(i);
1932 // replace any non alphanumeric characters with '_'.
1933 if (!isalpha(c) && (c < '0' || c > '9'))
1934 tmpName[i] = '_';
1935 }
1936 S += tmpName;
1937 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001938 S += utostr(NumObjCStringLiterals++);
1939
Steve Narofffef037c2008-03-27 22:29:16 +00001940 Preamble += "static __NSConstantStringImpl " + S;
1941 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1942 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00001943 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001944 std::string prettyBufS;
1945 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001946 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00001947 Preamble += prettyBuf.str();
1948 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00001949 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00001950 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001951
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001952 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001953 &Context->Idents.get(S.c_str()), strType,
1954 VarDecl::Static, NULL);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001955 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1956 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1957 Context->getPointerType(DRE->getType()),
1958 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001959 // cast to NSConstantString *
Douglas Gregor035d0882008-10-28 15:36:24 +00001960 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroff7f1412d2008-11-03 23:29:32 +00001961 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001962 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001963 delete Exp;
1964 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001965}
1966
Steve Naroff44e81222008-04-14 22:03:09 +00001967ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001968 // check if we are sending a message to 'super'
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001969 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattnere4650482008-03-15 06:12:44 +00001970
Douglas Gregord8606632008-11-04 14:56:14 +00001971 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
1972 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner4423d372008-06-21 18:04:54 +00001973 assert(PT);
1974 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1975 return IT->getDecl();
1976 }
1977 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001978}
1979
1980// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00001981QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001982 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001983 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001984 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001985 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00001986 QualType FieldTypes[2];
1987
1988 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001989 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001990 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001991 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001992 // Create fields
1993 FieldDecl *FieldDecls[2];
1994
1995 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001996 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001997 FieldTypes[i]);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001998
Ted Kremenek46a837c2008-09-05 17:16:31 +00001999 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002000 }
2001 return Context->getTagDeclType(SuperStructDecl);
2002}
2003
Steve Naroff44e81222008-04-14 22:03:09 +00002004QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002005 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002006 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002007 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002008 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroff47e7fa22008-03-15 00:55:56 +00002009 QualType FieldTypes[4];
2010
2011 // struct objc_object *receiver;
2012 FieldTypes[0] = Context->getObjCIdType();
2013 // int flags;
2014 FieldTypes[1] = Context->IntTy;
2015 // char *str;
2016 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2017 // long length;
2018 FieldTypes[3] = Context->LongTy;
2019 // Create fields
Steve Naroff053ae3f2008-03-27 22:59:54 +00002020 FieldDecl *FieldDecls[4];
Steve Naroff47e7fa22008-03-15 00:55:56 +00002021
2022 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002023 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00002024 FieldTypes[i]);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002025
Ted Kremenek46a837c2008-09-05 17:16:31 +00002026 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002027 }
2028 return Context->getTagDeclType(ConstantStringDecl);
2029}
2030
Steve Naroff44e81222008-04-14 22:03:09 +00002031Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00002032 if (!SelGetUidFunctionDecl)
2033 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002034 if (!MsgSendFunctionDecl)
2035 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002036 if (!MsgSendSuperFunctionDecl)
2037 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002038 if (!MsgSendStretFunctionDecl)
2039 SynthMsgSendStretFunctionDecl();
2040 if (!MsgSendSuperStretFunctionDecl)
2041 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002042 if (!MsgSendFpretFunctionDecl)
2043 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002044 if (!GetClassFunctionDecl)
2045 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002046 if (!GetMetaClassFunctionDecl)
2047 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002048
Steve Naroff764c1ae2007-11-15 10:28:18 +00002049 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002050 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2051 // May need to use objc_msgSend_stret() as well.
2052 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00002053 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002054 QualType resultType = mDecl->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00002055 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002056 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00002057 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002058 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002059 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002060
Steve Naroff71226032007-10-24 22:48:43 +00002061 // Synthesize a call to objc_msgSend().
2062 llvm::SmallVector<Expr*, 8> MsgExprs;
2063 IdentifierInfo *clsName = Exp->getClassName();
2064
2065 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2066 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00002067 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2068 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002069 if (!strcmp(clsName->getName(), "super")) {
2070 MsgSendFlavor = MsgSendSuperFunctionDecl;
2071 if (MsgSendStretFlavor)
2072 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2073 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2074
Ted Kremenek42730c52008-01-07 19:49:32 +00002075 ObjCInterfaceDecl *SuperDecl =
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002076 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002077
2078 llvm::SmallVector<Expr*, 4> InitExprs;
2079
2080 // set the receiver to self, the first argument to all methods.
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002081 InitExprs.push_back(new DeclRefExpr(
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002082 CurMethodDef->getSelfDecl(),
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002083 Context->getObjCIdType(),
2084 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002085 llvm::SmallVector<Expr*, 8> ClsExprs;
2086 QualType argType = Context->getPointerType(Context->CharTy);
2087 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2088 SuperDecl->getIdentifier()->getLength(),
2089 false, argType, SourceLocation(),
2090 SourceLocation()));
2091 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2092 &ClsExprs[0],
2093 ClsExprs.size());
2094 // To turn off a warning, type-cast to 'id'
Douglas Gregor21a04f32008-10-27 19:41:14 +00002095 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor035d0882008-10-28 15:36:24 +00002096 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002097 Cls, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002098 SourceLocation(), SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002099 // struct objc_super
2100 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002101 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002102
Steve Naroffdee066b2008-03-11 18:14:26 +00002103 if (LangOpts.Microsoft) {
2104 SynthSuperContructorFunctionDecl();
2105 // Simulate a contructor call...
2106 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2107 superType, SourceLocation());
2108 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2109 superType, SourceLocation());
2110 } else {
2111 // (struct objc_super) { <exprs from above> }
2112 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2113 &InitExprs[0], InitExprs.size(),
Chris Lattner71ca8c82008-10-26 23:43:26 +00002114 SourceLocation(), false);
2115 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2116 false);
Steve Naroffdee066b2008-03-11 18:14:26 +00002117 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00002118 // struct objc_super *
2119 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2120 Context->getPointerType(SuperRep->getType()),
2121 SourceLocation());
2122 MsgExprs.push_back(Unop);
2123 } else {
2124 llvm::SmallVector<Expr*, 8> ClsExprs;
2125 QualType argType = Context->getPointerType(Context->CharTy);
2126 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2127 clsName->getLength(),
2128 false, argType, SourceLocation(),
2129 SourceLocation()));
2130 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2131 &ClsExprs[0],
2132 ClsExprs.size());
2133 MsgExprs.push_back(Cls);
2134 }
Steve Naroff885e2122007-11-14 23:54:14 +00002135 } else { // instance message.
2136 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002137
Ted Kremenek42730c52008-01-07 19:49:32 +00002138 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002139 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002140 if (MsgSendStretFlavor)
2141 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002142 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2143
2144 llvm::SmallVector<Expr*, 4> InitExprs;
2145
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002146 InitExprs.push_back(
Douglas Gregor035d0882008-10-28 15:36:24 +00002147 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002148 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff23528612008-07-16 22:35:27 +00002149 Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002150 SourceLocation()),
2151 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002152 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002153
2154 llvm::SmallVector<Expr*, 8> ClsExprs;
2155 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002156 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2157 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002158 false, argType, SourceLocation(),
2159 SourceLocation()));
2160 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002161 &ClsExprs[0],
2162 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002163 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002164 InitExprs.push_back(
Douglas Gregor21a04f32008-10-27 19:41:14 +00002165 // set 'super class', using objc_getClass().
Douglas Gregor035d0882008-10-28 15:36:24 +00002166 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002167 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002168 // struct objc_super
2169 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002170 Expr *SuperRep;
2171
2172 if (LangOpts.Microsoft) {
2173 SynthSuperContructorFunctionDecl();
2174 // Simulate a contructor call...
2175 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2176 superType, SourceLocation());
2177 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2178 superType, SourceLocation());
2179 } else {
2180 // (struct objc_super) { <exprs from above> }
2181 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2182 &InitExprs[0], InitExprs.size(),
Chris Lattner71ca8c82008-10-26 23:43:26 +00002183 SourceLocation(), false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00002184 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2185 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002186 // struct objc_super *
2187 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2188 Context->getPointerType(SuperRep->getType()),
2189 SourceLocation());
2190 MsgExprs.push_back(Unop);
2191 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002192 // Remove all type-casts because it may contain objc-style types; e.g.
2193 // Foo<Proto> *.
Douglas Gregor035d0882008-10-28 15:36:24 +00002194 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002195 recExpr = CE->getSubExpr();
Douglas Gregor035d0882008-10-28 15:36:24 +00002196 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002197 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002198 SourceLocation(), SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002199 MsgExprs.push_back(recExpr);
2200 }
Steve Naroff885e2122007-11-14 23:54:14 +00002201 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002202 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002203 llvm::SmallVector<Expr*, 8> SelExprs;
2204 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner3a8f2942008-11-24 03:33:13 +00002205 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2206 Exp->getSelector().getAsString().size(),
Steve Naroff71226032007-10-24 22:48:43 +00002207 false, argType, SourceLocation(),
2208 SourceLocation()));
2209 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2210 &SelExprs[0], SelExprs.size());
2211 MsgExprs.push_back(SelExp);
2212
2213 // Now push any user supplied arguments.
2214 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002215 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002216 // Make all implicit casts explicit...ICE comes in handy:-)
2217 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2218 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor21a04f32008-10-27 19:41:14 +00002219 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002220 ? Context->getObjCIdType()
Douglas Gregor21a04f32008-10-27 19:41:14 +00002221 : ICE->getType();
Steve Naroff7f1412d2008-11-03 23:29:32 +00002222 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002223 }
2224 // Make id<P...> cast into an 'id' cast.
Douglas Gregor035d0882008-10-28 15:36:24 +00002225 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002226 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor035d0882008-10-28 15:36:24 +00002227 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002228 userExpr = CE->getSubExpr();
Douglas Gregor035d0882008-10-28 15:36:24 +00002229 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002230 userExpr, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002231 SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002232 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002233 }
Steve Naroff885e2122007-11-14 23:54:14 +00002234 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002235 // We've transferred the ownership to MsgExprs. Null out the argument in
2236 // the original expression, since we will delete it below.
2237 Exp->setArg(i, 0);
2238 }
Steve Naroff0744c472007-11-04 22:37:50 +00002239 // Generate the funky cast.
2240 CastExpr *cast;
2241 llvm::SmallVector<QualType, 8> ArgTypes;
2242 QualType returnType;
2243
2244 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002245 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2246 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2247 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002248 ArgTypes.push_back(Context->getObjCIdType());
2249 ArgTypes.push_back(Context->getObjCSelType());
2250 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002251 // Push any user argument types.
Chris Lattner685d7922008-03-16 01:07:14 +00002252 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002253 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2254 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002255 : mDecl->getParamDecl(i)->getType();
Steve Naroff66c842f2008-10-29 14:49:46 +00002256 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2257 if (isBlockPointerType(t)) {
2258 const BlockPointerType *BPT = t->getAsBlockPointerType();
2259 t = Context->getPointerType(BPT->getPointeeType());
2260 }
Steve Naroff4242b972007-11-05 14:36:37 +00002261 ArgTypes.push_back(t);
2262 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002263 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2264 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002265 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002266 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002267 }
2268 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002269 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002270
2271 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002272 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2273 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002274
2275 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2276 // If we don't do this cast, we get the following bizarre warning/note:
2277 // xx.m:13: warning: function called through a non-compatible type
2278 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor035d0882008-10-28 15:36:24 +00002279 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002280 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002281 SourceLocation(), SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002282
Steve Naroff0744c472007-11-04 22:37:50 +00002283 // Now do the "normal" pointer to function cast.
2284 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002285 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002286 // If we don't have a method decl, force a variadic cast.
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002287 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroff0744c472007-11-04 22:37:50 +00002288 castType = Context->getPointerType(castType);
Steve Naroff7f1412d2008-11-03 23:29:32 +00002289 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002290
2291 // Don't forget the parens to enforce the proper binding.
2292 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2293
2294 const FunctionType *FT = msgSendType->getAsFunctionType();
2295 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2296 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002297 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002298 if (MsgSendStretFlavor) {
2299 // We have the method which returns a struct/union. Must also generate
2300 // call to objc_msgSend_stret and hang both varieties on a conditional
2301 // expression which dictate which one to envoke depending on size of
2302 // method's return type.
2303
2304 // Create a reference to the objc_msgSend_stret() declaration.
2305 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2306 SourceLocation());
2307 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor035d0882008-10-28 15:36:24 +00002308 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002309 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002310 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002311 // Now do the "normal" pointer to function cast.
2312 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002313 &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002314 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002315 castType = Context->getPointerType(castType);
Steve Naroff7f1412d2008-11-03 23:29:32 +00002316 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002317
2318 // Don't forget the parens to enforce the proper binding.
2319 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2320
2321 FT = msgSendType->getAsFunctionType();
2322 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2323 FT->getResultType(), SourceLocation());
2324
2325 // Build sizeof(returnType)
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002326 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2327 returnType.getAsOpaquePtr(),
2328 Context->getSizeType(),
2329 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002330 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2331 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2332 // For X86 it is more complicated and some kind of target specific routine
2333 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002334 unsigned IntSize =
2335 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002336 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2337 Context->IntTy,
2338 SourceLocation());
2339 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2340 BinaryOperator::LE,
2341 Context->IntTy,
2342 SourceLocation());
2343 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2344 ConditionalOperator *CondExpr =
2345 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002346 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002347 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002348 return ReplacingStmt;
2349}
2350
Steve Naroff44e81222008-04-14 22:03:09 +00002351Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002352 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroffe8efe892008-10-27 20:54:44 +00002353
Steve Naroff71226032007-10-24 22:48:43 +00002354 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002355 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002356
Chris Lattner0021f452007-10-24 16:57:36 +00002357 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002358 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002359}
2360
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002361/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2362/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002363Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002364 if (!GetProtocolFunctionDecl)
2365 SynthGetProtocolFunctionDecl();
2366 // Create a call to objc_getProtocol("ProtocolName").
2367 llvm::SmallVector<Expr*, 8> ProtoExprs;
2368 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002369 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2370 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002371 false, argType, SourceLocation(),
2372 SourceLocation()));
2373 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2374 &ProtoExprs[0],
2375 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002376 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002377 delete Exp;
2378 return ProtoExp;
2379
2380}
2381
Steve Naroffef82b742008-05-31 14:15:04 +00002382bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2383 const char *endBuf) {
2384 while (startBuf < endBuf) {
2385 if (*startBuf == '#') {
2386 // Skip whitespace.
2387 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2388 ;
2389 if (!strncmp(startBuf, "if", strlen("if")) ||
2390 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2391 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2392 !strncmp(startBuf, "define", strlen("define")) ||
2393 !strncmp(startBuf, "undef", strlen("undef")) ||
2394 !strncmp(startBuf, "else", strlen("else")) ||
2395 !strncmp(startBuf, "elif", strlen("elif")) ||
2396 !strncmp(startBuf, "endif", strlen("endif")) ||
2397 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2398 !strncmp(startBuf, "include", strlen("include")) ||
2399 !strncmp(startBuf, "import", strlen("import")) ||
2400 !strncmp(startBuf, "include_next", strlen("include_next")))
2401 return true;
2402 }
2403 startBuf++;
2404 }
2405 return false;
2406}
2407
Ted Kremenek42730c52008-01-07 19:49:32 +00002408/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002409/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002410void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002411 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002412 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002413 assert(CDecl->getNameAsCString() &&
Douglas Gregor24afd4a2008-11-17 14:58:09 +00002414 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002415 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002416 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002417 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002418 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002419 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002420 SourceLocation LocStart = CDecl->getLocStart();
2421 SourceLocation LocEnd = CDecl->getLocEnd();
2422
2423 const char *startBuf = SM->getCharacterData(LocStart);
2424 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002425
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002426 // If no ivars and no root or if its root, directly or indirectly,
2427 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002428 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2429 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002430 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002431 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002432 return;
2433 }
2434
2435 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002436 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002437 Result += "\nstruct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002438 Result += CDecl->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +00002439 if (LangOpts.Microsoft)
2440 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002441
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002442 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002443 const char *cursor = strchr(startBuf, '{');
2444 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002445 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002446 // If the buffer contains preprocessor directives, we do more fine-grained
2447 // rewrites. This is intended to fix code that looks like (which occurs in
2448 // NSURL.h, for example):
2449 //
2450 // #ifdef XYZ
2451 // @interface Foo : NSObject
2452 // #else
2453 // @interface FooBar : NSObject
2454 // #endif
2455 // {
2456 // int i;
2457 // }
2458 // @end
2459 //
2460 // This clause is segregated to avoid breaking the common case.
2461 if (BufferContainsPPDirectives(startBuf, cursor)) {
2462 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2463 CDecl->getClassLoc();
2464 const char *endHeader = SM->getCharacterData(L);
2465 endHeader += Lexer::MeasureTokenLength(L, *SM);
2466
Chris Lattner8bcb5252008-07-21 18:19:38 +00002467 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002468 // advance to the end of the referenced protocols.
2469 while (endHeader < cursor && *endHeader != '>') endHeader++;
2470 endHeader++;
2471 }
2472 // rewrite the original header
2473 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2474 } else {
2475 // rewrite the original header *without* disturbing the '{'
2476 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2477 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002478 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002479 Result = "\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002480 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002481 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002482 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002483 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002484
2485 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002486 SourceLocation OnePastCurly =
2487 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2488 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002489 }
2490 cursor++; // past '{'
2491
2492 // Now comment out any visibility specifiers.
2493 while (cursor < endBuf) {
2494 if (*cursor == '@') {
2495 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002496 // Skip whitespace.
2497 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2498 /*scan*/;
2499
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002500 // FIXME: presence of @public, etc. inside comment results in
2501 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002502 if (!strncmp(cursor, "public", strlen("public")) ||
2503 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002504 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002505 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002506 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002507 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002508 // FIXME: If there are cases where '<' is used in ivar declaration part
2509 // of user code, then scan the ivar list and use needToScanForQualifiers
2510 // for type checking.
2511 else if (*cursor == '<') {
2512 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002513 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002514 cursor = strchr(cursor, '>');
2515 cursor++;
2516 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002517 InsertText(atLoc, " */", 3);
Steve Naroff6449c6c2008-10-30 12:09:33 +00002518 } else if (*cursor == '^') { // rewrite block specifier.
2519 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2520 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002521 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002522 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002523 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002524 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002525 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002526 } else { // we don't have any instance variables - insert super struct.
2527 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2528 Result += " {\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002529 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002530 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002531 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002532 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002533 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002534 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002535 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002536 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002537 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002538}
2539
Ted Kremenek42730c52008-01-07 19:49:32 +00002540// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002541/// class methods.
Steve Naroff44e81222008-04-14 22:03:09 +00002542void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002543 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002544 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002545 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002546 const char *ClassName,
2547 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002548 if (MethodBegin == MethodEnd) return;
2549
Fariborz Jahanian04455192007-10-22 21:41:37 +00002550 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002551 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002552 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002553 SEL _cmd;
2554 char *method_types;
2555 void *_imp;
2556 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002557 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002558 Result += "\nstruct _objc_method {\n";
2559 Result += "\tSEL _cmd;\n";
2560 Result += "\tchar *method_types;\n";
2561 Result += "\tvoid *_imp;\n";
2562 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002563
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002564 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002565 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002566
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002567 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002568
2569 /* struct {
2570 struct _objc_method_list *next_method;
2571 int method_count;
2572 struct _objc_method method_list[];
2573 }
2574 */
2575 Result += "\nstatic struct {\n";
2576 Result += "\tstruct _objc_method_list *next_method;\n";
2577 Result += "\tint method_count;\n";
2578 Result += "\tstruct _objc_method method_list[";
2579 Result += utostr(MethodEnd-MethodBegin);
2580 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002581 Result += prefix;
2582 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2583 Result += "_METHODS_";
2584 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002585 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002586 Result += IsInstanceMethod ? "inst" : "cls";
2587 Result += "_meth\")))= ";
2588 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002589
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002590 Result += "\t,{{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002591 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002592 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002593 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002594 Result += "\", \"";
2595 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002596 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002597 Result += MethodInternalNames[*MethodBegin];
2598 Result += "}\n";
2599 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2600 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002601 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002602 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002603 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002604 Result += "\", \"";
2605 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002606 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002607 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002608 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002609 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002610 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002611}
2612
Ted Kremenek42730c52008-01-07 19:49:32 +00002613/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002614void RewriteObjC::
2615RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2616 const char *prefix,
2617 const char *ClassName,
2618 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002619 static bool objc_protocol_methods = false;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002620 if (Protocols.empty()) return;
2621
2622 for (unsigned i = 0; i != Protocols.size(); i++) {
2623 ObjCProtocolDecl *PDecl = Protocols[i];
2624 // Output struct protocol_methods holder of method selector and type.
2625 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2626 /* struct protocol_methods {
2627 SEL _cmd;
2628 char *method_types;
2629 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002630 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002631 Result += "\nstruct protocol_methods {\n";
2632 Result += "\tSEL _cmd;\n";
2633 Result += "\tchar *method_types;\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002634 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002635
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002636 objc_protocol_methods = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002637 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002638 // Do not synthesize the protocol more than once.
2639 if (ObjCSynthesizedProtocols.count(PDecl))
2640 continue;
2641
2642 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2643 unsigned NumMethods = PDecl->getNumInstanceMethods();
2644 /* struct _objc_protocol_method_list {
2645 int protocol_method_count;
2646 struct protocol_methods protocols[];
2647 }
2648 */
2649 Result += "\nstatic struct {\n";
2650 Result += "\tint protocol_method_count;\n";
2651 Result += "\tstruct protocol_methods protocols[";
2652 Result += utostr(NumMethods);
2653 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002654 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002655 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2656 "{\n\t" + utostr(NumMethods) + "\n";
2657
2658 // Output instance methods declared in this protocol.
2659 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2660 E = PDecl->instmeth_end(); I != E; ++I) {
2661 if (I == PDecl->instmeth_begin())
2662 Result += "\t ,{{(SEL)\"";
2663 else
2664 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002665 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002666 std::string MethodTypeString;
2667 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2668 Result += "\", \"";
2669 Result += MethodTypeString;
2670 Result += "\"}\n";
2671 }
2672 Result += "\t }\n};\n";
2673 }
2674
2675 // Output class methods declared in this protocol.
2676 int NumMethods = PDecl->getNumClassMethods();
2677 if (NumMethods > 0) {
2678 /* struct _objc_protocol_method_list {
2679 int protocol_method_count;
2680 struct protocol_methods protocols[];
2681 }
2682 */
2683 Result += "\nstatic struct {\n";
2684 Result += "\tint protocol_method_count;\n";
2685 Result += "\tstruct protocol_methods protocols[";
2686 Result += utostr(NumMethods);
2687 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002688 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002689 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2690 "{\n\t";
2691 Result += utostr(NumMethods);
2692 Result += "\n";
2693
2694 // Output instance methods declared in this protocol.
2695 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2696 E = PDecl->classmeth_end(); I != E; ++I) {
2697 if (I == PDecl->classmeth_begin())
2698 Result += "\t ,{{(SEL)\"";
2699 else
2700 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002701 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002702 std::string MethodTypeString;
2703 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2704 Result += "\", \"";
2705 Result += MethodTypeString;
2706 Result += "\"}\n";
2707 }
2708 Result += "\t }\n};\n";
2709 }
2710
2711 // Output:
2712 /* struct _objc_protocol {
2713 // Objective-C 1.0 extensions
2714 struct _objc_protocol_extension *isa;
2715 char *protocol_name;
2716 struct _objc_protocol **protocol_list;
2717 struct _objc_protocol_method_list *instance_methods;
2718 struct _objc_protocol_method_list *class_methods;
2719 };
Steve Naroff27429432008-03-12 01:06:30 +00002720 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002721 static bool objc_protocol = false;
2722 if (!objc_protocol) {
2723 Result += "\nstruct _objc_protocol {\n";
2724 Result += "\tstruct _objc_protocol_extension *isa;\n";
2725 Result += "\tchar *protocol_name;\n";
2726 Result += "\tstruct _objc_protocol **protocol_list;\n";
2727 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2728 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2729 Result += "};\n";
2730
2731 objc_protocol = true;
2732 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002733
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002734 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002735 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002736 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2737 "{\n\t0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00002738 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002739 Result += "\", 0, ";
2740 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2741 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002742 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002743 Result += ", ";
2744 }
2745 else
2746 Result += "0, ";
2747 if (PDecl->getNumClassMethods() > 0) {
2748 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002749 Result += PDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002750 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002751 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002752 else
2753 Result += "0\n";
2754 Result += "};\n";
2755
2756 // Mark this protocol as having been generated.
2757 if (!ObjCSynthesizedProtocols.insert(PDecl))
2758 assert(false && "protocol already synthesized");
2759 }
2760 // Output the top lovel protocol meta-data for the class.
2761 /* struct _objc_protocol_list {
2762 struct _objc_protocol_list *next;
2763 int protocol_count;
2764 struct _objc_protocol *class_protocols[];
2765 }
2766 */
2767 Result += "\nstatic struct {\n";
2768 Result += "\tstruct _objc_protocol_list *next;\n";
2769 Result += "\tint protocol_count;\n";
2770 Result += "\tstruct _objc_protocol *class_protocols[";
2771 Result += utostr(Protocols.size());
2772 Result += "];\n} _OBJC_";
2773 Result += prefix;
2774 Result += "_PROTOCOLS_";
2775 Result += ClassName;
2776 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2777 "{\n\t0, ";
2778 Result += utostr(Protocols.size());
2779 Result += "\n";
2780
2781 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002782 Result += Protocols[0]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002783 Result += " \n";
2784
2785 for (unsigned i = 1; i != Protocols.size(); i++) {
2786 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002787 Result += Protocols[i]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002788 Result += "\n";
2789 }
2790 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002791}
2792
Ted Kremenek42730c52008-01-07 19:49:32 +00002793/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002794/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00002795void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002796 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002797 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002798 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002799 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002800 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2801 CDecl = CDecl->getNextClassCategory())
2802 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2803 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002804
Chris Lattner271d4c22008-11-24 05:29:24 +00002805 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00002806 FullCategoryName += '_';
Chris Lattner271d4c22008-11-24 05:29:24 +00002807 FullCategoryName += IDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00002808
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002809 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002810 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002811 true, "CATEGORY_", FullCategoryName.c_str(),
2812 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002813
2814 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002815 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002816 false, "CATEGORY_", FullCategoryName.c_str(),
2817 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002818
2819 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002820 // Null CDecl is case of a category implementation with no category interface
2821 if (CDecl)
Chris Lattner0be08822008-07-21 21:32:27 +00002822 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002823 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002824
2825 /* struct _objc_category {
2826 char *category_name;
2827 char *class_name;
2828 struct _objc_method_list *instance_methods;
2829 struct _objc_method_list *class_methods;
2830 struct _objc_protocol_list *protocols;
2831 // Objective-C 1.0 extensions
2832 uint32_t size; // sizeof (struct _objc_category)
2833 struct _objc_property_list *instance_properties; // category's own
2834 // @property decl.
2835 };
2836 */
2837
2838 static bool objc_category = false;
2839 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002840 Result += "\nstruct _objc_category {\n";
2841 Result += "\tchar *category_name;\n";
2842 Result += "\tchar *class_name;\n";
2843 Result += "\tstruct _objc_method_list *instance_methods;\n";
2844 Result += "\tstruct _objc_method_list *class_methods;\n";
2845 Result += "\tstruct _objc_protocol_list *protocols;\n";
2846 Result += "\tunsigned int size;\n";
2847 Result += "\tstruct _objc_property_list *instance_properties;\n";
2848 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002849 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002850 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002851 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2852 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002853 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00002854 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002855 Result += "\"\n\t, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00002856 Result += ClassDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002857 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002858
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002859 if (IDecl->getNumInstanceMethods() > 0) {
2860 Result += "\t, (struct _objc_method_list *)"
2861 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2862 Result += FullCategoryName;
2863 Result += "\n";
2864 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002865 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002866 Result += "\t, 0\n";
2867 if (IDecl->getNumClassMethods() > 0) {
2868 Result += "\t, (struct _objc_method_list *)"
2869 "&_OBJC_CATEGORY_CLASS_METHODS_";
2870 Result += FullCategoryName;
2871 Result += "\n";
2872 }
2873 else
2874 Result += "\t, 0\n";
2875
Chris Lattner0be08822008-07-21 21:32:27 +00002876 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002877 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2878 Result += FullCategoryName;
2879 Result += "\n";
2880 }
2881 else
2882 Result += "\t, 0\n";
2883 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002884}
2885
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002886/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2887/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00002888void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00002889 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002890 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00002891 if (ivar->isBitField()) {
2892 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2893 // place all bitfields at offset 0.
2894 Result += "0";
2895 } else {
2896 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002897 Result += IDecl->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00002898 if (LangOpts.Microsoft)
2899 Result += "_IMPL";
2900 Result += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002901 Result += ivar->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00002902 Result += ")";
2903 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002904}
2905
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002906//===----------------------------------------------------------------------===//
2907// Meta Data Emission
2908//===----------------------------------------------------------------------===//
2909
Steve Naroff44e81222008-04-14 22:03:09 +00002910void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002911 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002912 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002913
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002914 // Explictly declared @interface's are already synthesized.
2915 if (CDecl->ImplicitInterfaceDecl()) {
2916 // FIXME: Implementation of a class with no @interface (legacy) doese not
2917 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002918 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002919 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002920
Chris Lattnerc7b06752007-12-12 07:56:42 +00002921 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00002922 unsigned NumIvars = !IDecl->ivar_empty()
2923 ? IDecl->ivar_size()
2924 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002925 if (NumIvars > 0) {
2926 static bool objc_ivar = false;
2927 if (!objc_ivar) {
2928 /* struct _objc_ivar {
2929 char *ivar_name;
2930 char *ivar_type;
2931 int ivar_offset;
2932 };
2933 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002934 Result += "\nstruct _objc_ivar {\n";
2935 Result += "\tchar *ivar_name;\n";
2936 Result += "\tchar *ivar_type;\n";
2937 Result += "\tint ivar_offset;\n";
2938 Result += "};\n";
2939
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002940 objc_ivar = true;
2941 }
2942
Steve Naroffc723eec2008-03-11 00:12:29 +00002943 /* struct {
2944 int ivar_count;
2945 struct _objc_ivar ivar_list[nIvars];
2946 };
2947 */
2948 Result += "\nstatic struct {\n";
2949 Result += "\tint ivar_count;\n";
2950 Result += "\tstruct _objc_ivar ivar_list[";
2951 Result += utostr(NumIvars);
2952 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002953 Result += IDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002954 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002955 "{\n\t";
2956 Result += utostr(NumIvars);
2957 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002958
Ted Kremenek42730c52008-01-07 19:49:32 +00002959 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00002960 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00002961 IVI = IDecl->ivar_begin();
2962 IVE = IDecl->ivar_end();
2963 } else {
2964 IVI = CDecl->ivar_begin();
2965 IVE = CDecl->ivar_end();
2966 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002967 Result += "\t,{{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00002968 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002969 Result += "\", \"";
2970 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002971 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002972 Result += StrEncoding;
2973 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002974 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002975 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002976 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002977 Result += "\t ,{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00002978 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002979 Result += "\", \"";
2980 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002981 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002982 Result += StrEncoding;
2983 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002984 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002985 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002986 }
2987
2988 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002989 }
2990
2991 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002992 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002993 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002994
2995 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002996 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002997 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002998
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002999 // Protocols referenced in class declaration?
Chris Lattner0be08822008-07-21 21:32:27 +00003000 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003001 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003002
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003003
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003004 // Declaration of class/meta-class metadata
3005 /* struct _objc_class {
3006 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003007 const char *super_class_name;
3008 char *name;
3009 long version;
3010 long info;
3011 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003012 struct _objc_ivar_list *ivars;
3013 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003014 struct objc_cache *cache;
3015 struct objc_protocol_list *protocols;
3016 const char *ivar_layout;
3017 struct _objc_class_ext *ext;
3018 };
3019 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003020 static bool objc_class = false;
3021 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003022 Result += "\nstruct _objc_class {\n";
3023 Result += "\tstruct _objc_class *isa;\n";
3024 Result += "\tconst char *super_class_name;\n";
3025 Result += "\tchar *name;\n";
3026 Result += "\tlong version;\n";
3027 Result += "\tlong info;\n";
3028 Result += "\tlong instance_size;\n";
3029 Result += "\tstruct _objc_ivar_list *ivars;\n";
3030 Result += "\tstruct _objc_method_list *methods;\n";
3031 Result += "\tstruct objc_cache *cache;\n";
3032 Result += "\tstruct _objc_protocol_list *protocols;\n";
3033 Result += "\tconst char *ivar_layout;\n";
3034 Result += "\tstruct _objc_class_ext *ext;\n";
3035 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003036 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003037 }
3038
3039 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003040 ObjCInterfaceDecl *RootClass = 0;
3041 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003042 while (SuperClass) {
3043 RootClass = SuperClass;
3044 SuperClass = SuperClass->getSuperClass();
3045 }
3046 SuperClass = CDecl->getSuperClass();
3047
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003048 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003049 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003050 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003051 "{\n\t(struct _objc_class *)\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003052 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003053 Result += "\"";
3054
3055 if (SuperClass) {
3056 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003057 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003058 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003059 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003060 Result += "\"";
3061 }
3062 else {
3063 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003064 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003065 Result += "\"";
3066 }
Ted Kremenek42730c52008-01-07 19:49:32 +00003067 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003068 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003069 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00003070 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003071 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003072 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003073 Result += "\n";
3074 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003075 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003076 Result += ", 0\n";
Chris Lattner8bcb5252008-07-21 18:19:38 +00003077 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff27429432008-03-12 01:06:30 +00003078 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003079 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003080 Result += ",0,0\n";
3081 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003082 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003083 Result += "\t,0,0,0,0\n";
3084 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003085
3086 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003087 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003088 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003089 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003090 "{\n\t&_OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003091 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003092 if (SuperClass) {
3093 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003094 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003095 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003096 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003097 Result += "\"";
3098 }
3099 else {
3100 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003101 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003102 Result += "\"";
3103 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003104 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003105 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003106 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003107 Result += ",0";
3108 else {
3109 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003110 Result += ",sizeof(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003111 Result += CDecl->getNameAsString();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003112 if (LangOpts.Microsoft)
3113 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003114 Result += ")";
3115 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003116 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003117 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003118 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003119 Result += "\n\t";
3120 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003121 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003122 Result += ",0";
3123 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003124 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003125 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003126 Result += ", 0\n\t";
3127 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003128 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003129 Result += ",0,0";
Chris Lattner8bcb5252008-07-21 18:19:38 +00003130 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff27429432008-03-12 01:06:30 +00003131 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003132 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003133 Result += ", 0,0\n";
3134 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003135 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003136 Result += ",0,0,0\n";
3137 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003138}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003139
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003140/// RewriteImplementations - This routine rewrites all method implementations
3141/// and emits meta-data.
3142
Steve Naroff21658f62008-11-13 20:07:04 +00003143void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003144 int ClsDefCount = ClassImplementation.size();
3145 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003146
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003147 // Rewrite implemented methods
3148 for (int i = 0; i < ClsDefCount; i++)
3149 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003150
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003151 for (int i = 0; i < CatDefCount; i++)
3152 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Naroff21658f62008-11-13 20:07:04 +00003153}
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003154
Steve Naroff21658f62008-11-13 20:07:04 +00003155void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3156 int ClsDefCount = ClassImplementation.size();
3157 int CatDefCount = CategoryImplementation.size();
3158
Steve Naroff5bf10222008-05-07 21:23:49 +00003159 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003160 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003161 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003162 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003163 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003164
3165 // For each implemented category, write out all its meta data.
3166 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003167 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003168
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003169 // Write objc_symtab metadata
3170 /*
3171 struct _objc_symtab
3172 {
3173 long sel_ref_cnt;
3174 SEL *refs;
3175 short cls_def_cnt;
3176 short cat_def_cnt;
3177 void *defs[cls_def_cnt + cat_def_cnt];
3178 };
3179 */
3180
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003181 Result += "\nstruct _objc_symtab {\n";
3182 Result += "\tlong sel_ref_cnt;\n";
3183 Result += "\tSEL *refs;\n";
3184 Result += "\tshort cls_def_cnt;\n";
3185 Result += "\tshort cat_def_cnt;\n";
3186 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3187 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003188
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003189 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003190 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003191 Result += "\t0, 0, " + utostr(ClsDefCount)
3192 + ", " + utostr(CatDefCount) + "\n";
3193 for (int i = 0; i < ClsDefCount; i++) {
3194 Result += "\t,&_OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003195 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003196 Result += "\n";
3197 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003198
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003199 for (int i = 0; i < CatDefCount; i++) {
3200 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003201 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003202 Result += "_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003203 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003204 Result += "\n";
3205 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003206
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003207 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003208
3209 // Write objc_module metadata
3210
3211 /*
3212 struct _objc_module {
3213 long version;
3214 long size;
3215 const char *name;
3216 struct _objc_symtab *symtab;
3217 }
3218 */
3219
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003220 Result += "\nstruct _objc_module {\n";
3221 Result += "\tlong version;\n";
3222 Result += "\tlong size;\n";
3223 Result += "\tconst char *name;\n";
3224 Result += "\tstruct _objc_symtab *symtab;\n";
3225 Result += "};\n\n";
3226 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003227 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003228 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3229 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003230 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003231
3232 if (LangOpts.Microsoft) {
3233 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003234 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003235 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3236 Result += "&_OBJC_MODULES;\n";
3237 Result += "#pragma data_seg(pop)\n\n";
3238 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003239}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003240
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003241std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3242 const char *funcName,
3243 std::string Tag) {
3244 const FunctionType *AFT = CE->getFunctionType();
3245 QualType RT = AFT->getResultType();
3246 std::string StructRef = "struct " + Tag;
3247 std::string S = "static " + RT.getAsString() + " __" +
3248 funcName + "_" + "block_func_" + utostr(i);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003249
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003250 BlockDecl *BD = CE->getBlockDecl();
3251
3252 if (isa<FunctionTypeNoProto>(AFT)) {
3253 S += "()";
3254 } else if (BD->param_empty()) {
3255 S += "(" + StructRef + " *__cself)";
3256 } else {
3257 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3258 assert(FT && "SynthesizeBlockFunc: No function proto");
3259 S += '(';
3260 // first add the implicit argument.
3261 S += StructRef + " *__cself, ";
3262 std::string ParamStr;
3263 for (BlockDecl::param_iterator AI = BD->param_begin(),
3264 E = BD->param_end(); AI != E; ++AI) {
3265 if (AI != BD->param_begin()) S += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003266 ParamStr = (*AI)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003267 (*AI)->getType().getAsStringInternal(ParamStr);
3268 S += ParamStr;
3269 }
3270 if (FT->isVariadic()) {
3271 if (!BD->param_empty()) S += ", ";
3272 S += "...";
3273 }
3274 S += ')';
3275 }
3276 S += " {\n";
3277
3278 // Create local declarations to avoid rewriting all closure decl ref exprs.
3279 // First, emit a declaration for all "by ref" decls.
3280 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3281 E = BlockByRefDecls.end(); I != E; ++I) {
3282 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003283 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003284 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003285 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003286 }
3287 // Next, emit a declaration for all "by copy" declarations.
3288 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3289 E = BlockByCopyDecls.end(); I != E; ++I) {
3290 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003291 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003292 // Handle nested closure invocation. For example:
3293 //
3294 // void (^myImportedClosure)(void);
3295 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3296 //
3297 // void (^anotherClosure)(void);
3298 // anotherClosure = ^(void) {
3299 // myImportedClosure(); // import and invoke the closure
3300 // };
3301 //
3302 if (isBlockPointerType((*I)->getType()))
3303 S += "struct __block_impl *";
3304 else
3305 (*I)->getType().getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003306 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003307 }
3308 std::string RewrittenStr = RewrittenBlockExprs[CE];
3309 const char *cstr = RewrittenStr.c_str();
3310 while (*cstr++ != '{') ;
3311 S += cstr;
3312 S += "\n";
3313 return S;
3314}
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003315
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003316std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3317 const char *funcName,
3318 std::string Tag) {
3319 std::string StructRef = "struct " + Tag;
3320 std::string S = "static void __";
3321
3322 S += funcName;
3323 S += "_block_copy_" + utostr(i);
3324 S += "(" + StructRef;
3325 S += "*dst, " + StructRef;
3326 S += "*src) {";
3327 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3328 E = ImportedBlockDecls.end(); I != E; ++I) {
3329 S += "_Block_copy_assign(&dst->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003330 S += (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003331 S += ", src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003332 S += (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003333 S += ");}";
3334 }
3335 S += "\nstatic void __";
3336 S += funcName;
3337 S += "_block_dispose_" + utostr(i);
3338 S += "(" + StructRef;
3339 S += "*src) {";
3340 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3341 E = ImportedBlockDecls.end(); I != E; ++I) {
3342 S += "_Block_destroy(src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003343 S += (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003344 S += ");";
3345 }
3346 S += "}\n";
3347 return S;
3348}
3349
3350std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3351 bool hasCopyDisposeHelpers) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003352 std::string S = "\nstruct " + Tag;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003353 std::string Constructor = " " + Tag;
3354
3355 S += " {\n struct __block_impl impl;\n";
3356
3357 if (hasCopyDisposeHelpers)
3358 S += " void *copy;\n void *dispose;\n";
3359
3360 Constructor += "(void *fp";
3361
3362 if (hasCopyDisposeHelpers)
3363 Constructor += ", void *copyHelp, void *disposeHelp";
3364
3365 if (BlockDeclRefs.size()) {
3366 // Output all "by copy" declarations.
3367 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3368 E = BlockByCopyDecls.end(); I != E; ++I) {
3369 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003370 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003371 std::string ArgName = "_" + FieldName;
3372 // Handle nested closure invocation. For example:
3373 //
3374 // void (^myImportedBlock)(void);
3375 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3376 //
3377 // void (^anotherBlock)(void);
3378 // anotherBlock = ^(void) {
3379 // myImportedBlock(); // import and invoke the closure
3380 // };
3381 //
3382 if (isBlockPointerType((*I)->getType())) {
3383 S += "struct __block_impl *";
3384 Constructor += ", void *" + ArgName;
3385 } else {
3386 (*I)->getType().getAsStringInternal(FieldName);
3387 (*I)->getType().getAsStringInternal(ArgName);
3388 Constructor += ", " + ArgName;
3389 }
3390 S += FieldName + ";\n";
3391 }
3392 // Output all "by ref" declarations.
3393 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3394 E = BlockByRefDecls.end(); I != E; ++I) {
3395 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003396 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003397 std::string ArgName = "_" + FieldName;
3398 // Handle nested closure invocation. For example:
3399 //
3400 // void (^myImportedBlock)(void);
3401 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3402 //
3403 // void (^anotherBlock)(void);
3404 // anotherBlock = ^(void) {
3405 // myImportedBlock(); // import and invoke the closure
3406 // };
3407 //
3408 if (isBlockPointerType((*I)->getType())) {
3409 S += "struct __block_impl *";
3410 Constructor += ", void *" + ArgName;
3411 } else {
3412 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3413 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3414 Constructor += ", " + ArgName;
3415 }
3416 S += FieldName + "; // by ref\n";
3417 }
3418 // Finish writing the constructor.
3419 // FIXME: handle NSConcreteGlobalBlock.
3420 Constructor += ", int flags=0) {\n";
3421 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3422 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3423
3424 if (hasCopyDisposeHelpers)
3425 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3426
3427 // Initialize all "by copy" arguments.
3428 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3429 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003430 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003431 Constructor += " ";
3432 if (isBlockPointerType((*I)->getType()))
3433 Constructor += Name + " = (struct __block_impl *)_";
3434 else
3435 Constructor += Name + " = _";
3436 Constructor += Name + ";\n";
3437 }
3438 // Initialize all "by ref" arguments.
3439 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3440 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003441 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003442 Constructor += " ";
3443 if (isBlockPointerType((*I)->getType()))
3444 Constructor += Name + " = (struct __block_impl *)_";
3445 else
3446 Constructor += Name + " = _";
3447 Constructor += Name + ";\n";
3448 }
3449 } else {
3450 // Finish writing the constructor.
3451 // FIXME: handle NSConcreteGlobalBlock.
3452 Constructor += ", int flags=0) {\n";
3453 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3454 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3455 if (hasCopyDisposeHelpers)
3456 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3457 }
3458 Constructor += " ";
3459 Constructor += "}\n";
3460 S += Constructor;
3461 S += "};\n";
3462 return S;
3463}
3464
3465void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3466 const char *FunName) {
3467 // Insert closures that were part of the function.
3468 for (unsigned i = 0; i < Blocks.size(); i++) {
3469
3470 CollectBlockDeclRefInfo(Blocks[i]);
3471
3472 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3473
3474 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3475 ImportedBlockDecls.size() > 0);
3476
3477 InsertText(FunLocStart, CI.c_str(), CI.size());
3478
3479 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3480
3481 InsertText(FunLocStart, CF.c_str(), CF.size());
3482
3483 if (ImportedBlockDecls.size()) {
3484 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3485 InsertText(FunLocStart, HF.c_str(), HF.size());
3486 }
3487
3488 BlockDeclRefs.clear();
3489 BlockByRefDecls.clear();
3490 BlockByCopyDecls.clear();
3491 BlockCallExprs.clear();
3492 ImportedBlockDecls.clear();
3493 }
3494 Blocks.clear();
3495 RewrittenBlockExprs.clear();
3496}
3497
3498void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3499 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003500 const char *FuncName = FD->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003501
3502 SynthesizeBlockLiterals(FunLocStart, FuncName);
3503}
3504
3505void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003506 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3507 //SourceLocation FunLocStart = MD->getLocStart();
3508 // FIXME: This hack works around a bug in Rewrite.InsertText().
3509 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner3a8f2942008-11-24 03:33:13 +00003510 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003511 // Convert colons to underscores.
3512 std::string::size_type loc = 0;
3513 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3514 FuncName.replace(loc, 1, "_");
3515
3516 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3517}
3518
3519void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3520 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3521 CI != E; ++CI)
3522 if (*CI) {
3523 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3524 GetBlockDeclRefExprs(CBE->getBody());
3525 else
3526 GetBlockDeclRefExprs(*CI);
3527 }
3528 // Handle specific things.
3529 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3530 // FIXME: Handle enums.
3531 if (!isa<FunctionDecl>(CDRE->getDecl()))
3532 BlockDeclRefs.push_back(CDRE);
3533 return;
3534}
3535
3536void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3537 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3538 CI != E; ++CI)
3539 if (*CI) {
3540 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3541 GetBlockCallExprs(CBE->getBody());
3542 else
3543 GetBlockCallExprs(*CI);
3544 }
3545
3546 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3547 if (CE->getCallee()->getType()->isBlockPointerType()) {
3548 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3549 }
3550 }
3551 return;
3552}
3553
Steve Naroff85eb17b2008-10-30 10:07:53 +00003554Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003555 // Navigate to relevant type information.
3556 const char *closureName = 0;
3557 const BlockPointerType *CPT = 0;
3558
3559 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003560 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003561 CPT = DRE->getType()->getAsBlockPointerType();
3562 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003563 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003564 CPT = CDRE->getType()->getAsBlockPointerType();
3565 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003566 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003567 CPT = MExpr->getType()->getAsBlockPointerType();
3568 } else {
3569 assert(1 && "RewriteBlockClass: Bad type");
3570 }
3571 assert(CPT && "RewriteBlockClass: Bad type");
3572 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3573 assert(FT && "RewriteBlockClass: Bad type");
3574 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3575 // FTP will be null for closures that don't take arguments.
3576
Steve Naroff85eb17b2008-10-30 10:07:53 +00003577 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3578 SourceLocation(),
3579 &Context->Idents.get("__block_impl"));
3580 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003581
Steve Naroff85eb17b2008-10-30 10:07:53 +00003582 // Generate a funky cast.
3583 llvm::SmallVector<QualType, 8> ArgTypes;
3584
3585 // Push the block argument type.
3586 ArgTypes.push_back(PtrBlock);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003587 if (FTP) {
3588 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff85eb17b2008-10-30 10:07:53 +00003589 E = FTP->arg_type_end(); I && (I != E); ++I) {
3590 QualType t = *I;
3591 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3592 if (isBlockPointerType(t)) {
3593 const BlockPointerType *BPT = t->getAsBlockPointerType();
3594 t = Context->getPointerType(BPT->getPointeeType());
3595 }
3596 ArgTypes.push_back(t);
3597 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003598 }
Steve Naroff85eb17b2008-10-30 10:07:53 +00003599 // Now do the pointer to function cast.
3600 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3601 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3602
3603 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003604
Steve Naroff7f1412d2008-11-03 23:29:32 +00003605 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003606 // Don't forget the parens to enforce the proper binding.
3607 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3608 //PE->dump();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003609
Steve Naroff85eb17b2008-10-30 10:07:53 +00003610 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3611 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3612 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3613
Steve Naroff7f1412d2008-11-03 23:29:32 +00003614 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003615 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3616
3617 llvm::SmallVector<Expr*, 8> BlkExprs;
3618 // Add the implicit argument.
3619 BlkExprs.push_back(BlkCast);
3620 // Add the user arguments.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003621 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3622 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003623 BlkExprs.push_back(*I);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003624 }
Steve Naroff85eb17b2008-10-30 10:07:53 +00003625 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3626 return CE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003627}
3628
3629void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003630 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3631 ReplaceStmt(Exp, BlockCall);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003632}
3633
3634void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3635 // FIXME: Add more elaborate code generation required by the ABI.
3636 InsertText(BDRE->getLocStart(), "*", 1);
3637}
3638
Steve Naroff7f1412d2008-11-03 23:29:32 +00003639void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3640 SourceLocation LocStart = CE->getLParenLoc();
3641 SourceLocation LocEnd = CE->getRParenLoc();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003642
3643 // Need to avoid trying to rewrite synthesized casts.
3644 if (LocStart.isInvalid())
3645 return;
Steve Naroff1c53c022008-11-03 11:20:24 +00003646 // Need to avoid trying to rewrite casts contained in macros.
3647 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3648 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003649
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003650 const char *startBuf = SM->getCharacterData(LocStart);
3651 const char *endBuf = SM->getCharacterData(LocEnd);
3652
3653 // advance the location to startArgList.
3654 const char *argPtr = startBuf;
3655
3656 while (*argPtr++ && (argPtr < endBuf)) {
3657 switch (*argPtr) {
3658 case '^':
3659 // Replace the '^' with '*'.
3660 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3661 ReplaceText(LocStart, 1, "*", 1);
3662 break;
3663 }
3664 }
3665 return;
3666}
3667
3668void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3669 SourceLocation DeclLoc = FD->getLocation();
3670 unsigned parenCount = 0;
3671
3672 // We have 1 or more arguments that have closure pointers.
3673 const char *startBuf = SM->getCharacterData(DeclLoc);
3674 const char *startArgList = strchr(startBuf, '(');
3675
3676 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3677
3678 parenCount++;
3679 // advance the location to startArgList.
3680 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3681 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3682
3683 const char *argPtr = startArgList;
3684
3685 while (*argPtr++ && parenCount) {
3686 switch (*argPtr) {
3687 case '^':
3688 // Replace the '^' with '*'.
3689 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3690 ReplaceText(DeclLoc, 1, "*", 1);
3691 break;
3692 case '(':
3693 parenCount++;
3694 break;
3695 case ')':
3696 parenCount--;
3697 break;
3698 }
3699 }
3700 return;
3701}
3702
3703bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3704 const FunctionTypeProto *FTP;
3705 const PointerType *PT = QT->getAsPointerType();
3706 if (PT) {
3707 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3708 } else {
3709 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3710 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3711 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3712 }
3713 if (FTP) {
3714 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3715 E = FTP->arg_type_end(); I != E; ++I)
3716 if (isBlockPointerType(*I))
3717 return true;
3718 }
3719 return false;
3720}
3721
3722void RewriteObjC::GetExtentOfArgList(const char *Name,
3723 const char *&LParen, const char *&RParen) {
3724 const char *argPtr = strchr(Name, '(');
3725 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3726
3727 LParen = argPtr; // output the start.
3728 argPtr++; // skip past the left paren.
3729 unsigned parenCount = 1;
3730
3731 while (*argPtr && parenCount) {
3732 switch (*argPtr) {
3733 case '(': parenCount++; break;
3734 case ')': parenCount--; break;
3735 default: break;
3736 }
3737 if (parenCount) argPtr++;
3738 }
3739 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3740 RParen = argPtr; // output the end
3741}
3742
3743void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3744 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3745 RewriteBlockPointerFunctionArgs(FD);
3746 return;
3747 }
3748 // Handle Variables and Typedefs.
3749 SourceLocation DeclLoc = ND->getLocation();
3750 QualType DeclT;
3751 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3752 DeclT = VD->getType();
3753 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3754 DeclT = TDD->getUnderlyingType();
3755 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3756 DeclT = FD->getType();
3757 else
3758 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3759
3760 const char *startBuf = SM->getCharacterData(DeclLoc);
3761 const char *endBuf = startBuf;
3762 // scan backward (from the decl location) for the end of the previous decl.
3763 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3764 startBuf--;
3765
3766 // *startBuf != '^' if we are dealing with a pointer to function that
3767 // may take block argument types (which will be handled below).
3768 if (*startBuf == '^') {
3769 // Replace the '^' with '*', computing a negative offset.
3770 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3771 ReplaceText(DeclLoc, 1, "*", 1);
3772 }
3773 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3774 // Replace the '^' with '*' for arguments.
3775 DeclLoc = ND->getLocation();
3776 startBuf = SM->getCharacterData(DeclLoc);
3777 const char *argListBegin, *argListEnd;
3778 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3779 while (argListBegin < argListEnd) {
3780 if (*argListBegin == '^') {
3781 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3782 ReplaceText(CaretLoc, 1, "*", 1);
3783 }
3784 argListBegin++;
3785 }
3786 }
3787 return;
3788}
3789
3790void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3791 // Add initializers for any closure decl refs.
3792 GetBlockDeclRefExprs(Exp->getBody());
3793 if (BlockDeclRefs.size()) {
3794 // Unique all "by copy" declarations.
3795 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3796 if (!BlockDeclRefs[i]->isByRef())
3797 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3798 // Unique all "by ref" declarations.
3799 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3800 if (BlockDeclRefs[i]->isByRef()) {
3801 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3802 }
3803 // Find any imported blocks...they will need special attention.
3804 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3805 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroffe59c8b12008-11-13 17:40:07 +00003806 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003807 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3808 }
3809 }
3810}
3811
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003812FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3813 IdentifierInfo *ID = &Context->Idents.get(name);
3814 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3815 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3816 ID, FType, FunctionDecl::Extern, false, 0);
3817}
3818
Steve Naroff80c54752008-10-29 18:15:37 +00003819Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003820 Blocks.push_back(Exp);
3821
3822 CollectBlockDeclRefInfo(Exp);
3823 std::string FuncName;
3824
3825 if (CurFunctionDef)
Chris Lattner3a8f2942008-11-24 03:33:13 +00003826 FuncName = CurFunctionDef->getNameAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003827 else if (CurMethodDef) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00003828 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003829 // Convert colons to underscores.
3830 std::string::size_type loc = 0;
3831 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3832 FuncName.replace(loc, 1, "_");
Steve Naroff80c54752008-10-29 18:15:37 +00003833 } else if (GlobalVarDecl)
Chris Lattner271d4c22008-11-24 05:29:24 +00003834 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003835
3836 std::string BlockNumber = utostr(Blocks.size()-1);
3837
3838 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3839 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3840
3841 // Get a pointer to the function type so we can cast appropriately.
3842 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3843
3844 FunctionDecl *FD;
3845 Expr *NewRep;
3846
3847 // Simulate a contructor call...
3848 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3849 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3850
3851 llvm::SmallVector<Expr*, 4> InitExprs;
3852
Steve Naroffd0419d62008-10-29 21:23:59 +00003853 // Initialize the block function.
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003854 FD = SynthBlockInitFunctionDecl(Func.c_str());
3855 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3856 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroff7f1412d2008-11-03 23:29:32 +00003857 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003858 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003859
3860 if (ImportedBlockDecls.size()) {
3861 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00003862 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3863 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3864 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroff7f1412d2008-11-03 23:29:32 +00003865 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00003866 InitExprs.push_back(castExpr);
3867
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003868 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00003869 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3870 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3871 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroff7f1412d2008-11-03 23:29:32 +00003872 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00003873 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003874 }
3875 // Add initializers for any closure decl refs.
3876 if (BlockDeclRefs.size()) {
Steve Naroffd0419d62008-10-29 21:23:59 +00003877 Expr *Exp;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003878 // Output all "by copy" declarations.
3879 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3880 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003881 if (isObjCType((*I)->getType())) {
Steve Naroffd0419d62008-10-29 21:23:59 +00003882 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003883 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Naroffd0419d62008-10-29 21:23:59 +00003884 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003885 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003886 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Naroffd0419d62008-10-29 21:23:59 +00003887 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3888 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroff7f1412d2008-11-03 23:29:32 +00003889 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003890 } else {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003891 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Naroffd0419d62008-10-29 21:23:59 +00003892 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003893 }
Steve Naroffd0419d62008-10-29 21:23:59 +00003894 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003895 }
3896 // Output all "by ref" declarations.
3897 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3898 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003899 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Naroffd0419d62008-10-29 21:23:59 +00003900 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3901 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3902 Context->getPointerType(Exp->getType()),
3903 SourceLocation());
Steve Naroff362c7562008-11-14 21:36:12 +00003904 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003905 }
3906 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003907 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3908 FType, SourceLocation());
3909 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3910 Context->getPointerType(NewRep->getType()),
3911 SourceLocation());
Steve Naroff7f1412d2008-11-03 23:29:32 +00003912 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003913 BlockDeclRefs.clear();
3914 BlockByRefDecls.clear();
3915 BlockByCopyDecls.clear();
3916 ImportedBlockDecls.clear();
3917 return NewRep;
3918}
3919
3920//===----------------------------------------------------------------------===//
3921// Function Body / Expression rewriting
3922//===----------------------------------------------------------------------===//
3923
3924Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3925 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3926 isa<DoStmt>(S) || isa<ForStmt>(S))
3927 Stmts.push_back(S);
3928 else if (isa<ObjCForCollectionStmt>(S)) {
3929 Stmts.push_back(S);
3930 ObjCBcLabelNo.push_back(++BcLabelCount);
3931 }
3932
3933 SourceRange OrigStmtRange = S->getSourceRange();
3934
3935 // Perform a bottom up rewrite of all children.
3936 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3937 CI != E; ++CI)
3938 if (*CI) {
3939 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3940 if (newStmt)
3941 *CI = newStmt;
3942 }
3943
3944 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
3945 // Rewrite the block body in place.
3946 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
3947
3948 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff80c54752008-10-29 18:15:37 +00003949 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
3950 RewrittenBlockExprs[BE] = Str;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003951
3952 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
3953 //blockTranscribed->dump();
Steve Naroff80c54752008-10-29 18:15:37 +00003954 ReplaceStmt(S, blockTranscribed);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003955 return blockTranscribed;
3956 }
3957 // Handle specific things.
3958 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
3959 return RewriteAtEncode(AtEncode);
3960
3961 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
3962 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
3963
3964 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
3965 return RewriteAtSelector(AtSelector);
3966
3967 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
3968 return RewriteObjCStringLiteral(AtString);
3969
3970 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
3971 // Before we rewrite it, put the original message expression in a comment.
3972 SourceLocation startLoc = MessExpr->getLocStart();
3973 SourceLocation endLoc = MessExpr->getLocEnd();
3974
3975 const char *startBuf = SM->getCharacterData(startLoc);
3976 const char *endBuf = SM->getCharacterData(endLoc);
3977
3978 std::string messString;
3979 messString += "// ";
3980 messString.append(startBuf, endBuf-startBuf+1);
3981 messString += "\n";
3982
3983 // FIXME: Missing definition of
3984 // InsertText(clang::SourceLocation, char const*, unsigned int).
3985 // InsertText(startLoc, messString.c_str(), messString.size());
3986 // Tried this, but it didn't work either...
3987 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
3988 return RewriteMessageExpr(MessExpr);
3989 }
3990
3991 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
3992 return RewriteObjCTryStmt(StmtTry);
3993
3994 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
3995 return RewriteObjCSynchronizedStmt(StmtTry);
3996
3997 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
3998 return RewriteObjCThrowStmt(StmtThrow);
3999
4000 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4001 return RewriteObjCProtocolExpr(ProtocolExp);
4002
4003 if (ObjCForCollectionStmt *StmtForCollection =
4004 dyn_cast<ObjCForCollectionStmt>(S))
4005 return RewriteObjCForCollectionStmt(StmtForCollection,
4006 OrigStmtRange.getEnd());
4007 if (BreakStmt *StmtBreakStmt =
4008 dyn_cast<BreakStmt>(S))
4009 return RewriteBreakStmt(StmtBreakStmt);
4010 if (ContinueStmt *StmtContinueStmt =
4011 dyn_cast<ContinueStmt>(S))
4012 return RewriteContinueStmt(StmtContinueStmt);
4013
4014 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4015 // and cast exprs.
4016 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4017 // FIXME: What we're doing here is modifying the type-specifier that
4018 // precedes the first Decl. In the future the DeclGroup should have
4019 // a separate type-specifier that we can rewrite.
4020 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4021
4022 // Blocks rewrite rules.
4023 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4024 DI != DE; ++DI) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004025 ScopedDecl *SD = *DI;
4026 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4027 if (isBlockPointerType(ND->getType()))
4028 RewriteBlockPointerDecl(ND);
4029 else if (ND->getType()->isFunctionPointerType())
4030 CheckFunctionPointerDecl(ND->getType(), ND);
4031 }
4032 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4033 if (isBlockPointerType(TD->getUnderlyingType()))
4034 RewriteBlockPointerDecl(TD);
4035 else if (TD->getUnderlyingType()->isFunctionPointerType())
4036 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4037 }
4038 }
4039 }
4040
4041 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4042 RewriteObjCQualifiedInterfaceTypes(CE);
4043
4044 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4045 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4046 assert(!Stmts.empty() && "Statement stack is empty");
4047 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4048 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4049 && "Statement stack mismatch");
4050 Stmts.pop_back();
4051 }
4052 // Handle blocks rewriting.
4053 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4054 if (BDRE->isByRef())
4055 RewriteBlockDeclRefExpr(BDRE);
4056 }
4057 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00004058 if (CE->getCallee()->getType()->isBlockPointerType()) {
4059 Stmt *BlockCall = SynthesizeBlockCall(CE);
4060 ReplaceStmt(S, BlockCall);
4061 return BlockCall;
4062 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004063 }
Steve Naroff7f1412d2008-11-03 23:29:32 +00004064 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004065 RewriteCastExpr(CE);
4066 }
4067#if 0
4068 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4069 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4070 // Get the new text.
4071 std::string SStr;
4072 llvm::raw_string_ostream Buf(SStr);
4073 Replacement->printPretty(Buf);
4074 const std::string &Str = Buf.str();
4075
4076 printf("CAST = %s\n", &Str[0]);
4077 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4078 delete S;
4079 return Replacement;
4080 }
4081#endif
4082 // Return this stmt unmodified.
4083 return S;
4084}
4085
4086/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4087/// main file of the input.
4088void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4089 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4090 // Since function prototypes don't have ParmDecl's, we check the function
4091 // prototype. This enables us to rewrite function declarations and
4092 // definitions using the same code.
4093 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4094
4095 if (Stmt *Body = FD->getBody()) {
4096 CurFunctionDef = FD;
4097 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4098 // This synthesizes and inserts the block "impl" struct, invoke function,
4099 // and any copy/dispose helper functions.
4100 InsertBlockLiteralsWithinFunction(FD);
4101 CurFunctionDef = 0;
4102 }
4103 return;
4104 }
4105 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4106 if (Stmt *Body = MD->getBody()) {
4107 //Body->dump();
4108 CurMethodDef = MD;
4109 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4110 InsertBlockLiteralsWithinMethod(MD);
4111 CurMethodDef = 0;
4112 }
4113 }
4114 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4115 ClassImplementation.push_back(CI);
4116 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4117 CategoryImplementation.push_back(CI);
4118 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4119 RewriteForwardClassDecl(CD);
4120 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4121 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff80c54752008-10-29 18:15:37 +00004122 if (isBlockPointerType(VD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004123 RewriteBlockPointerDecl(VD);
Steve Naroff80c54752008-10-29 18:15:37 +00004124 else if (VD->getType()->isFunctionPointerType()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004125 CheckFunctionPointerDecl(VD->getType(), VD);
4126 if (VD->getInit()) {
Steve Naroff7f1412d2008-11-03 23:29:32 +00004127 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004128 RewriteCastExpr(CE);
4129 }
4130 }
4131 }
Steve Naroff80c54752008-10-29 18:15:37 +00004132 if (VD->getInit()) {
4133 GlobalVarDecl = VD;
4134 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Douglas Gregor24afd4a2008-11-17 14:58:09 +00004135 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004136 VD->getNameAsCString());
Steve Naroff80c54752008-10-29 18:15:37 +00004137 GlobalVarDecl = 0;
4138
4139 // This is needed for blocks.
Steve Naroff7f1412d2008-11-03 23:29:32 +00004140 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff80c54752008-10-29 18:15:37 +00004141 RewriteCastExpr(CE);
4142 }
4143 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004144 return;
4145 }
4146 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4147 if (isBlockPointerType(TD->getUnderlyingType()))
4148 RewriteBlockPointerDecl(TD);
4149 else if (TD->getUnderlyingType()->isFunctionPointerType())
4150 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4151 return;
4152 }
4153 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4154 if (RD->isDefinition()) {
4155 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4156 e = RD->field_end(); i != e; ++i) {
4157 FieldDecl *FD = *i;
4158 if (isBlockPointerType(FD->getType()))
4159 RewriteBlockPointerDecl(FD);
4160 }
4161 }
4162 return;
4163 }
4164 // Nothing yet.
4165}
4166
4167void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4168 // Get the top-level buffer that this corresponds to.
4169
4170 // Rewrite tabs if we care.
4171 //RewriteTabs();
4172
4173 if (Diags.hasErrorOccurred())
4174 return;
4175
4176 // Create the output file.
4177
4178 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4179 llvm::raw_ostream *OutFile;
4180 if (OutFileName == "-") {
4181 OutFile = &llvm::outs();
4182 } else if (!OutFileName.empty()) {
4183 std::string Err;
Daniel Dunbar8fc9ba62008-11-13 05:09:21 +00004184 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004185 OwnedStream.reset(OutFile);
4186 } else if (InFileName == "-") {
4187 OutFile = &llvm::outs();
4188 } else {
4189 llvm::sys::Path Path(InFileName);
4190 Path.eraseSuffix();
4191 Path.appendSuffix("cpp");
4192 std::string Err;
Daniel Dunbar8fc9ba62008-11-13 05:09:21 +00004193 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004194 OwnedStream.reset(OutFile);
4195 }
4196
4197 RewriteInclude();
4198
4199 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4200 Preamble.c_str(), Preamble.size(), false);
4201
Steve Naroff901d8fd2008-11-14 14:10:01 +00004202 if (ClassImplementation.size() || CategoryImplementation.size())
4203 RewriteImplementations();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004204
4205 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4206 // we are done.
4207 if (const RewriteBuffer *RewriteBuf =
4208 Rewrite.getRewriteBufferFor(MainFileID)) {
4209 //printf("Changed:\n");
4210 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4211 } else {
4212 fprintf(stderr, "No changes\n");
4213 }
Steve Naroff21658f62008-11-13 20:07:04 +00004214
Steve Naroff901d8fd2008-11-14 14:10:01 +00004215 if (ClassImplementation.size() || CategoryImplementation.size()) {
4216 // Rewrite Objective-c meta data*
4217 std::string ResultStr;
4218 SynthesizeMetaDataIntoBuffer(ResultStr);
4219 // Emit metadata.
4220 *OutFile << ResultStr;
4221 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004222 OutFile->flush();
4223}
4224