blob: 68ad0e6583b38af32cc42c2be3f956080a2db887 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Steve Naroff0113c9d2008-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 Lattner77cd2a02007-10-11 00:43:27 +000038namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattner01c57482007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000046 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000051
Ted Kremeneka526c5c2008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000083 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff54055232008-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 Naroffba92b2e2008-03-27 22:29:16 +000099
Steve Naroff54055232008-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 Naroff8e2f57a2008-10-29 18:15:37 +0000108 VarDecl *GlobalVarDecl;
109
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000110 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000111 public:
Ted Kremeneke3a61982008-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 Lattner9e13c2e2008-01-31 19:38:44 +0000118
Chris Lattner8a12c272007-10-11 18:38:32 +0000119
Chris Lattnerf04da132007-10-24 17:06:59 +0000120 // Top Level Driver code.
121 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000122 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000123 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000124 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000125
126 ~RewriteObjC() {}
127
128 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000129
130 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000131 // If replacement succeeded or warning disabled return with no warning.
132 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000133 return;
134
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000135 SourceRange Range = Old->getSourceRange();
136 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
137 0, 0, &Range, 1);
138 }
139
Steve Naroffba92b2e2008-03-27 22:29:16 +0000140 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
141 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000142 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000143 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000144 SilenceRewriteMacroWarning)
145 return;
146
147 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
148 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000149
Chris Lattneraadaf782008-01-31 19:51:04 +0000150 void RemoveText(SourceLocation Loc, unsigned StrLen) {
151 // If removal succeeded or warning disabled return with no warning.
152 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
153 return;
154
155 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
156 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000157
Chris Lattneraadaf782008-01-31 19:51:04 +0000158 void ReplaceText(SourceLocation Start, unsigned OrigLength,
159 const char *NewStr, unsigned NewLength) {
160 // If removal succeeded or warning disabled return with no warning.
161 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
162 SilenceRewriteMacroWarning)
163 return;
164
165 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
166 }
167
Chris Lattnerf04da132007-10-24 17:06:59 +0000168 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000169 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000170 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000171 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000172 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
173 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000174 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-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 Lattner55d13b42008-03-16 21:23:50 +0000180 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000181 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000182 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000183 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000184 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000185 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000186 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000187 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000188 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000189
Chris Lattnerf04da132007-10-24 17:06:59 +0000190 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000191 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000192 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000193 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000194 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000195 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000196 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000197 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000199 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000200 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
201 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
202 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000203 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
204 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000205 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
206 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000207 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000208 Stmt *RewriteBreakStmt(BreakStmt *S);
209 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000210 void SynthCountByEnumWithState(std::string &buf);
211
Steve Naroff09b266e2007-10-30 23:14:51 +0000212 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000213 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000214 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000215 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000216 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000217 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000218 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000219 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000220 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000221 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000222
Chris Lattnerf04da132007-10-24 17:06:59 +0000223 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000224 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000225 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000226
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000227 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000228 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000229
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000230 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
231 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000232 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000233 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000234 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000235 const char *ClassName,
236 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000237
Chris Lattner780f3292008-07-21 21:32:27 +0000238 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
239 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000240 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000241 const char *ClassName,
242 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000243 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000244 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000245 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
246 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000247 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000248 void RewriteImplementations(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000249
250 // Block rewriting.
251 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
252 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
253
254 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
255 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
256
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000257 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000258 void RewriteBlockCall(CallExpr *Exp);
259 void RewriteBlockPointerDecl(NamedDecl *VD);
260 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
261 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
262
263 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
264 const char *funcName, std::string Tag);
265 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
266 const char *funcName, std::string Tag);
267 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
268 bool hasCopyDisposeHelpers);
269 std::string SynthesizeBlockCall(CallExpr *Exp);
270 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
271 const char *FunName);
272
273 void CollectBlockDeclRefInfo(BlockExpr *Exp);
274 void GetBlockCallExprs(Stmt *S);
275 void GetBlockDeclRefExprs(Stmt *S);
276
277 // We avoid calling Type::isBlockPointerType(), since it operates on the
278 // canonical type. We only care if the top-level type is a closure pointer.
279 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
280
281 // FIXME: This predicate seems like it would be useful to add to ASTContext.
282 bool isObjCType(QualType T) {
283 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
284 return false;
285
286 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
287
288 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
289 OCT == Context->getCanonicalType(Context->getObjCClassType()))
290 return true;
291
292 if (const PointerType *PT = OCT->getAsPointerType()) {
293 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
294 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
295 return true;
296 }
297 return false;
298 }
299 bool PointerTypeTakesAnyBlockArguments(QualType QT);
300 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
301 void RewriteCastExpr(CastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000302
303 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000304 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000305 };
306}
307
Steve Naroff54055232008-10-27 17:20:55 +0000308void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
309 NamedDecl *D) {
310 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
311 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
312 E = fproto->arg_type_end(); I && (I != E); ++I)
313 if (isBlockPointerType(*I)) {
314 // All the args are checked/rewritten. Don't call twice!
315 RewriteBlockPointerDecl(D);
316 break;
317 }
318 }
319}
320
321void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
322 const PointerType *PT = funcType->getAsPointerType();
323 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
324 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
325}
326
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000327static bool IsHeaderFile(const std::string &Filename) {
328 std::string::size_type DotPos = Filename.rfind('.');
329
330 if (DotPos == std::string::npos) {
331 // no file extension
332 return false;
333 }
334
335 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
336 // C header: .h
337 // C++ header: .hh or .H;
338 return Ext == "h" || Ext == "hh" || Ext == "H";
339}
340
Steve Naroffb29b4272008-04-14 22:03:09 +0000341RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000342 Diagnostic &D, const LangOptions &LOpts)
343 : Diags(D), LangOpts(LOpts) {
344 IsHeader = IsHeaderFile(inFile);
345 InFileName = inFile;
346 OutFileName = outFile;
347 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
348 "rewriting sub-expression within a macro (may not be correct)");
349}
350
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000351ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000352 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000353 Diagnostic &Diags,
354 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000355 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000356}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000357
Steve Naroffb29b4272008-04-14 22:03:09 +0000358void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000359 Context = &context;
360 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000361 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000362 MsgSendFunctionDecl = 0;
363 MsgSendSuperFunctionDecl = 0;
364 MsgSendStretFunctionDecl = 0;
365 MsgSendSuperStretFunctionDecl = 0;
366 MsgSendFpretFunctionDecl = 0;
367 GetClassFunctionDecl = 0;
368 GetMetaClassFunctionDecl = 0;
369 SelGetUidFunctionDecl = 0;
370 CFStringFunctionDecl = 0;
371 GetProtocolFunctionDecl = 0;
372 ConstantStringClassReference = 0;
373 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000374 CurMethodDef = 0;
375 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000376 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000377 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000378 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000379 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000380 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000381
382 // Get the ID and start/end of the main file.
383 MainFileID = SM->getMainFileID();
384 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
385 MainFileStart = MainBuf->getBufferStart();
386 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000387
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000388 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000389
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000390 // declaring objc_selector outside the parameter list removes a silly
391 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000392 if (IsHeader)
393 Preamble = "#pragma once\n";
394 Preamble += "struct objc_selector; struct objc_class;\n";
395 Preamble += "#ifndef OBJC_SUPER\n";
396 Preamble += "struct objc_super { struct objc_object *object; ";
397 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000398 if (LangOpts.Microsoft) {
399 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000400 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
401 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000402 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000403 Preamble += "};\n";
404 Preamble += "#define OBJC_SUPER\n";
405 Preamble += "#endif\n";
406 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
407 Preamble += "typedef struct objc_object Protocol;\n";
408 Preamble += "#define _REWRITER_typedef_Protocol\n";
409 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000410 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000411 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
412 else
413 Preamble += "#define __OBJC_RW_EXTERN extern\n";
414 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000415 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000416 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000417 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000418 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000419 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000420 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000421 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000422 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000423 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000424 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000425 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000426 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000427 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000428 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
429 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
430 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
431 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
432 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000433 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000434 // @synchronized hooks.
435 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
436 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000437 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000438 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
439 Preamble += "struct __objcFastEnumerationState {\n\t";
440 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000441 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000442 Preamble += "unsigned long *mutationsPtr;\n\t";
443 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000444 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000445 Preamble += "#define __FASTENUMERATIONSTATE\n";
446 Preamble += "#endif\n";
447 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
448 Preamble += "struct __NSConstantStringImpl {\n";
449 Preamble += " int *isa;\n";
450 Preamble += " int flags;\n";
451 Preamble += " char *str;\n";
452 Preamble += " long length;\n";
453 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000454 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
455 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
456 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000457 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000458 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000459 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
460 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000461 // Blocks preamble.
462 Preamble += "#ifndef BLOCK_IMPL\n";
463 Preamble += "#define BLOCK_IMPL\n";
464 Preamble += "struct __block_impl {\n";
465 Preamble += " void *isa;\n";
466 Preamble += " int Flags;\n";
467 Preamble += " int Size;\n";
468 Preamble += " void *FuncPtr;\n";
469 Preamble += "};\n";
470 Preamble += "enum {\n";
471 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
472 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
473 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000474 Preamble += "// Runtime copy/destroy helper functions\n";
475 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
476 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
477 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
478 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
479 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
480 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
481 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000482 if (LangOpts.Microsoft) {
483 Preamble += "#undef __OBJC_RW_EXTERN\n";
484 Preamble += "#define __attribute__(X)\n";
485 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000486}
487
488
Chris Lattnerf04da132007-10-24 17:06:59 +0000489//===----------------------------------------------------------------------===//
490// Top Level Driver Code
491//===----------------------------------------------------------------------===//
492
Steve Naroffb29b4272008-04-14 22:03:09 +0000493void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000494 // Two cases: either the decl could be in the main file, or it could be in a
495 // #included file. If the former, rewrite it now. If the later, check to see
496 // if we rewrote the #include/#import.
497 SourceLocation Loc = D->getLocation();
498 Loc = SM->getLogicalLoc(Loc);
499
500 // If this is for a builtin, ignore it.
501 if (Loc.isInvalid()) return;
502
Steve Naroffebf2b562007-10-23 23:50:29 +0000503 // Look for built-in declarations that we need to refer during the rewrite.
504 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000505 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000506 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000507 // declared in <Foundation/NSString.h>
508 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
509 ConstantStringClassReference = FVD;
510 return;
511 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000512 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000513 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000514 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000515 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000516 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000517 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000518 } else if (ObjCForwardProtocolDecl *FP =
519 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000520 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000521 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000522 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000523 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000524 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000525}
526
Chris Lattnerf04da132007-10-24 17:06:59 +0000527//===----------------------------------------------------------------------===//
528// Syntactic (non-AST) Rewriting Code
529//===----------------------------------------------------------------------===//
530
Steve Naroffb29b4272008-04-14 22:03:09 +0000531void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000532 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
533 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
534 const char *MainBufStart = MainBuf.first;
535 const char *MainBufEnd = MainBuf.second;
536 size_t ImportLen = strlen("import");
537 size_t IncludeLen = strlen("include");
538
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000539 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000540 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
541 if (*BufPtr == '#') {
542 if (++BufPtr == MainBufEnd)
543 return;
544 while (*BufPtr == ' ' || *BufPtr == '\t')
545 if (++BufPtr == MainBufEnd)
546 return;
547 if (!strncmp(BufPtr, "import", ImportLen)) {
548 // replace import with include
549 SourceLocation ImportLoc =
550 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000551 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000552 BufPtr += ImportLen;
553 }
554 }
555 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000556}
557
Steve Naroffb29b4272008-04-14 22:03:09 +0000558void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000559 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
560 const char *MainBufStart = MainBuf.first;
561 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000562
Chris Lattnerf04da132007-10-24 17:06:59 +0000563 // Loop over the whole file, looking for tabs.
564 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
565 if (*BufPtr != '\t')
566 continue;
567
568 // Okay, we found a tab. This tab will turn into at least one character,
569 // but it depends on which 'virtual column' it is in. Compute that now.
570 unsigned VCol = 0;
571 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
572 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
573 ++VCol;
574
575 // Okay, now that we know the virtual column, we know how many spaces to
576 // insert. We assume 8-character tab-stops.
577 unsigned Spaces = 8-(VCol & 7);
578
579 // Get the location of the tab.
580 SourceLocation TabLoc =
581 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
582
583 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000584 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000585 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000586}
587
588
Steve Naroffb29b4272008-04-14 22:03:09 +0000589void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000590 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000591 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000592
593 // Get the start location and compute the semi location.
594 SourceLocation startLoc = ClassDecl->getLocation();
595 const char *startBuf = SM->getCharacterData(startLoc);
596 const char *semiPtr = strchr(startBuf, ';');
597
598 // Translate to typedef's that forward reference structs with the same name
599 // as the class. As a convenience, we include the original declaration
600 // as a comment.
601 std::string typedefString;
602 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000603 typedefString.append(startBuf, semiPtr-startBuf+1);
604 typedefString += "\n";
605 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000606 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000607 typedefString += "#ifndef _REWRITER_typedef_";
608 typedefString += ForwardDecl->getName();
609 typedefString += "\n";
610 typedefString += "#define _REWRITER_typedef_";
611 typedefString += ForwardDecl->getName();
612 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000613 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000614 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000615 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000616 }
617
618 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000619 ReplaceText(startLoc, semiPtr-startBuf+1,
620 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000621}
622
Steve Naroffb29b4272008-04-14 22:03:09 +0000623void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000624 SourceLocation LocStart = Method->getLocStart();
625 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000626
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000627 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000628 InsertText(LocStart, "#if 0\n", 6);
629 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000630 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000631 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000632 }
633}
634
Steve Naroffb29b4272008-04-14 22:03:09 +0000635void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000636{
Chris Lattner55d13b42008-03-16 21:23:50 +0000637 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000638 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000639 SourceLocation Loc = Property->getLocation();
640
Chris Lattneraadaf782008-01-31 19:51:04 +0000641 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000642
643 // FIXME: handle properties that are declared across multiple lines.
644 }
645}
646
Steve Naroffb29b4272008-04-14 22:03:09 +0000647void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000648 SourceLocation LocStart = CatDecl->getLocStart();
649
650 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000651 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000652
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000653 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000654 E = CatDecl->instmeth_end(); I != E; ++I)
655 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000656 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000657 E = CatDecl->classmeth_end(); I != E; ++I)
658 RewriteMethodDeclaration(*I);
659
Steve Naroff423cb562007-10-30 13:30:57 +0000660 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000661 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000662}
663
Steve Naroffb29b4272008-04-14 22:03:09 +0000664void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000665 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000666
Steve Naroff752d6ef2007-10-30 16:42:30 +0000667 SourceLocation LocStart = PDecl->getLocStart();
668
669 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000670 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000671
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000672 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000673 E = PDecl->instmeth_end(); I != E; ++I)
674 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000675 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000676 E = PDecl->classmeth_end(); I != E; ++I)
677 RewriteMethodDeclaration(*I);
678
Steve Naroff752d6ef2007-10-30 16:42:30 +0000679 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000680 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000681 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000682
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000683 // Must comment out @optional/@required
684 const char *startBuf = SM->getCharacterData(LocStart);
685 const char *endBuf = SM->getCharacterData(LocEnd);
686 for (const char *p = startBuf; p < endBuf; p++) {
687 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
688 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000689 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000690 ReplaceText(OptionalLoc, strlen("@optional"),
691 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000692
693 }
694 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
695 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000696 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000697 ReplaceText(OptionalLoc, strlen("@required"),
698 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000699
700 }
701 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000702}
703
Steve Naroffb29b4272008-04-14 22:03:09 +0000704void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000705 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000706 if (LocStart.isInvalid())
707 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000708 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000709 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000710}
711
Steve Naroffb29b4272008-04-14 22:03:09 +0000712void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000713 std::string &ResultStr) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000714 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000715 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000717 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000718 else if (OMD->getResultType()->isFunctionPointerType()) {
719 // needs special handling, since pointer-to-functions have special
720 // syntax (where a decaration models use).
721 QualType retType = OMD->getResultType();
722 if (const PointerType* PT = retType->getAsPointerType()) {
723 QualType PointeeTy = PT->getPointeeType();
724 if ((FPRetType = PointeeTy->getAsFunctionType())) {
725 ResultStr += FPRetType->getResultType().getAsString();
726 ResultStr += "(*";
727 }
728 }
729 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000730 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000731 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000732
733 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000734 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000735
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000736 if (OMD->isInstance())
737 NameStr += "_I_";
738 else
739 NameStr += "_C_";
740
741 NameStr += OMD->getClassInterface()->getName();
742 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000743
744 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000745 if (ObjCCategoryImplDecl *CID =
746 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000747 NameStr += CID->getName();
748 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000749 }
Steve Naroff563b8282008-04-04 22:23:44 +0000750 // Append selector names, replacing ':' with '_'
751 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000752 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000753 else {
754 std::string selString = OMD->getSelector().getName();
755 int len = selString.size();
756 for (int i = 0; i < len; i++)
757 if (selString[i] == ':')
758 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000759 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000760 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000761 // Remember this name for metadata emission
762 MethodInternalNames[OMD] = NameStr;
763 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000764
765 // Rewrite arguments
766 ResultStr += "(";
767
768 // invisible arguments
769 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000770 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000771 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000772 if (!LangOpts.Microsoft) {
773 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
774 ResultStr += "struct ";
775 }
776 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000777 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000778 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000779 }
780 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000781 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000782
783 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000784 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000785 ResultStr += " _cmd";
786
787 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000788 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000789 ParmVarDecl *PDecl = OMD->getParamDecl(i);
790 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000791 if (PDecl->getType()->isObjCQualifiedIdType()) {
792 ResultStr += "id ";
793 ResultStr += PDecl->getName();
794 } else {
795 std::string Name = PDecl->getName();
796 PDecl->getType().getAsStringInternal(Name);
797 ResultStr += Name;
798 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000799 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000800 if (OMD->isVariadic())
801 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000802 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000803
Steve Naroff76e429d2008-07-16 14:40:40 +0000804 if (FPRetType) {
805 ResultStr += ")"; // close the precedence "scope" for "*".
806
807 // Now, emit the argument types (if any).
808 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
809 ResultStr += "(";
810 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
811 if (i) ResultStr += ", ";
812 std::string ParamStr = FT->getArgType(i).getAsString();
813 ResultStr += ParamStr;
814 }
815 if (FT->isVariadic()) {
816 if (FT->getNumArgs()) ResultStr += ", ";
817 ResultStr += "...";
818 }
819 ResultStr += ")";
820 } else {
821 ResultStr += "()";
822 }
823 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000824}
Steve Naroffb29b4272008-04-14 22:03:09 +0000825void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000826 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
827 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000828
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000829 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000830 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000831 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000832 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000833
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000834 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000835 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
836 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000837 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000838 ObjCMethodDecl *OMD = *I;
839 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000840 SourceLocation LocStart = OMD->getLocStart();
841 SourceLocation LocEnd = OMD->getBody()->getLocStart();
842
843 const char *startBuf = SM->getCharacterData(LocStart);
844 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000845 ReplaceText(LocStart, endBuf-startBuf,
846 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000847 }
848
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000849 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000850 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
851 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000852 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000853 ObjCMethodDecl *OMD = *I;
854 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000855 SourceLocation LocStart = OMD->getLocStart();
856 SourceLocation LocEnd = OMD->getBody()->getLocStart();
857
858 const char *startBuf = SM->getCharacterData(LocStart);
859 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000860 ReplaceText(LocStart, endBuf-startBuf,
861 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000862 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000863 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000864 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000865 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000866 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000867}
868
Steve Naroffb29b4272008-04-14 22:03:09 +0000869void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000870 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000871 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000872 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000873 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000874 ResultStr += ClassDecl->getName();
875 ResultStr += "\n";
876 ResultStr += "#define _REWRITER_typedef_";
877 ResultStr += ClassDecl->getName();
878 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000879 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000880 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000881 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000882 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000883 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000884 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000885 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000886
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000887 RewriteProperties(ClassDecl->getNumPropertyDecl(),
888 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000889 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000890 E = ClassDecl->instmeth_end(); I != E; ++I)
891 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000892 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000893 E = ClassDecl->classmeth_end(); I != E; ++I)
894 RewriteMethodDeclaration(*I);
895
Steve Naroff2feac5e2007-10-30 03:43:13 +0000896 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000897 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000898}
899
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000900Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
901 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000902 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +0000903 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +0000904 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000905 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
906 // lookup which class implements the instance variable.
907 ObjCInterfaceDecl *clsDeclared = 0;
908 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
909 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
910
911 // Synthesize an explicit cast to gain access to the ivar.
912 std::string RecName = clsDeclared->getIdentifier()->getName();
913 RecName += "_IMPL";
914 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000915 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000916 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +0000917 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
918 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000919 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Douglas Gregor49badde2008-10-27 19:41:14 +0000920 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +0000921 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000922 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
923 IV->getBase()->getLocEnd(),
924 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000925 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +0000926 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000927 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
928 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000929 ReplaceStmt(IV, ME);
930 delete IV;
931 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000932 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000933
934 ReplaceStmt(IV->getBase(), PE);
935 // Cannot delete IV->getBase(), since PE points to it.
936 // Replace the old base with the cast. This is important when doing
937 // embedded rewrites. For example, [newInv->_container addObject:0].
938 IV->setBase(PE);
939 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000940 }
Steve Naroff84472a82008-04-18 21:55:08 +0000941 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000942 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
943
944 // Explicit ivar refs need to have a cast inserted.
945 // FIXME: consider sharing some of this code with the code above.
946 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000947 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000948 // lookup which class implements the instance variable.
949 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000950 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000951 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
952
953 // Synthesize an explicit cast to gain access to the ivar.
954 std::string RecName = clsDeclared->getIdentifier()->getName();
955 RecName += "_IMPL";
956 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000957 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000958 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +0000959 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
960 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000961 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Douglas Gregor49badde2008-10-27 19:41:14 +0000962 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +0000963 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +0000964 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
965 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +0000966 ReplaceStmt(IV->getBase(), PE);
967 // Cannot delete IV->getBase(), since PE points to it.
968 // Replace the old base with the cast. This is important when doing
969 // embedded rewrites. For example, [newInv->_container addObject:0].
970 IV->setBase(PE);
971 return IV;
972 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000973 }
Steve Naroff84472a82008-04-18 21:55:08 +0000974 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000975}
976
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000977/// SynthCountByEnumWithState - To print:
978/// ((unsigned int (*)
979/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
980/// (void *)objc_msgSend)((id)l_collection,
981/// sel_registerName(
982/// "countByEnumeratingWithState:objects:count:"),
983/// &enumState,
984/// (id *)items, (unsigned int)16)
985///
Steve Naroffb29b4272008-04-14 22:03:09 +0000986void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000987 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
988 "id *, unsigned int))(void *)objc_msgSend)";
989 buf += "\n\t\t";
990 buf += "((id)l_collection,\n\t\t";
991 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
992 buf += "\n\t\t";
993 buf += "&enumState, "
994 "(id *)items, (unsigned int)16)";
995}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000996
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000997/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
998/// statement to exit to its outer synthesized loop.
999///
Steve Naroffb29b4272008-04-14 22:03:09 +00001000Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001001 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1002 return S;
1003 // replace break with goto __break_label
1004 std::string buf;
1005
1006 SourceLocation startLoc = S->getLocStart();
1007 buf = "goto __break_label_";
1008 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001009 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001010
1011 return 0;
1012}
1013
1014/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1015/// statement to continue with its inner synthesized loop.
1016///
Steve Naroffb29b4272008-04-14 22:03:09 +00001017Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001018 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1019 return S;
1020 // replace continue with goto __continue_label
1021 std::string buf;
1022
1023 SourceLocation startLoc = S->getLocStart();
1024 buf = "goto __continue_label_";
1025 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001026 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001027
1028 return 0;
1029}
1030
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001031/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001032/// It rewrites:
1033/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001034
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001035/// Into:
1036/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001037/// type elem;
1038/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001039/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001040/// id l_collection = (id)collection;
1041/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1042/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001043/// if (limit) {
1044/// unsigned long startMutations = *enumState.mutationsPtr;
1045/// do {
1046/// unsigned long counter = 0;
1047/// do {
1048/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001049/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001050/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001051/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001052/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001053/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001054/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1055/// objects:items count:16]);
1056/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001057/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001058/// }
1059/// else
1060/// elem = nil;
1061/// }
1062///
Steve Naroffb29b4272008-04-14 22:03:09 +00001063Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001064 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001065 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1066 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1067 "ObjCForCollectionStmt Statement stack mismatch");
1068 assert(!ObjCBcLabelNo.empty() &&
1069 "ObjCForCollectionStmt - Label No stack empty");
1070
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001071 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001072 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001073 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001074 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001075 std::string buf;
1076 buf = "\n{\n\t";
1077 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1078 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001079 ScopedDecl* D = DS->getSolitaryDecl();
1080 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001081 elementTypeAsString = ElementType.getAsString();
1082 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001083 buf += " ";
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001084 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001085 buf += elementName;
1086 buf += ";\n\t";
1087 }
Chris Lattner06767512008-04-08 05:52:18 +00001088 else {
1089 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001090 elementName = DR->getDecl()->getName();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001091 elementTypeAsString
1092 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001093 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001094
1095 // struct __objcFastEnumerationState enumState = { 0 };
1096 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1097 // id items[16];
1098 buf += "id items[16];\n\t";
1099 // id l_collection = (id)
1100 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001101 // Find start location of 'collection' the hard way!
1102 const char *startCollectionBuf = startBuf;
1103 startCollectionBuf += 3; // skip 'for'
1104 startCollectionBuf = strchr(startCollectionBuf, '(');
1105 startCollectionBuf++; // skip '('
1106 // find 'in' and skip it.
1107 while (*startCollectionBuf != ' ' ||
1108 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1109 (*(startCollectionBuf+3) != ' ' &&
1110 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1111 startCollectionBuf++;
1112 startCollectionBuf += 3;
1113
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001114 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001115 ReplaceText(startLoc, startCollectionBuf - startBuf,
1116 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001117 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001118 SourceLocation rightParenLoc = S->getRParenLoc();
1119 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1120 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001121 buf = ";\n\t";
1122
1123 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1124 // objects:items count:16];
1125 // which is synthesized into:
1126 // unsigned int limit =
1127 // ((unsigned int (*)
1128 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1129 // (void *)objc_msgSend)((id)l_collection,
1130 // sel_registerName(
1131 // "countByEnumeratingWithState:objects:count:"),
1132 // (struct __objcFastEnumerationState *)&state,
1133 // (id *)items, (unsigned int)16);
1134 buf += "unsigned long limit =\n\t\t";
1135 SynthCountByEnumWithState(buf);
1136 buf += ";\n\t";
1137 /// if (limit) {
1138 /// unsigned long startMutations = *enumState.mutationsPtr;
1139 /// do {
1140 /// unsigned long counter = 0;
1141 /// do {
1142 /// if (startMutations != *enumState.mutationsPtr)
1143 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001144 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001145 buf += "if (limit) {\n\t";
1146 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1147 buf += "do {\n\t\t";
1148 buf += "unsigned long counter = 0;\n\t\t";
1149 buf += "do {\n\t\t\t";
1150 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1151 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1152 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001153 buf += " = (";
1154 buf += elementTypeAsString;
1155 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001156 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001157 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001158
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001159 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001160 /// } while (counter < limit);
1161 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1162 /// objects:items count:16]);
1163 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001164 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001165 /// }
1166 /// else
1167 /// elem = nil;
1168 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001169 ///
1170 buf = ";\n\t";
1171 buf += "__continue_label_";
1172 buf += utostr(ObjCBcLabelNo.back());
1173 buf += ": ;";
1174 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001175 buf += "} while (counter < limit);\n\t";
1176 buf += "} while (limit = ";
1177 SynthCountByEnumWithState(buf);
1178 buf += ");\n\t";
1179 buf += elementName;
1180 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001181 buf += "__break_label_";
1182 buf += utostr(ObjCBcLabelNo.back());
1183 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001184 buf += "}\n\t";
1185 buf += "else\n\t\t";
1186 buf += elementName;
1187 buf += " = nil;\n";
1188 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001189
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001190 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001191 if (isa<CompoundStmt>(S->getBody())) {
1192 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1193 InsertText(endBodyLoc, buf.c_str(), buf.size());
1194 } else {
1195 /* Need to treat single statements specially. For example:
1196 *
1197 * for (A *a in b) if (stuff()) break;
1198 * for (A *a in b) xxxyy;
1199 *
1200 * The following code simply scans ahead to the semi to find the actual end.
1201 */
1202 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1203 const char *semiBuf = strchr(stmtBuf, ';');
1204 assert(semiBuf && "Can't find ';'");
1205 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1206 InsertText(endBodyLoc, buf.c_str(), buf.size());
1207 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001208 Stmts.pop_back();
1209 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001210 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001211}
1212
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001213/// RewriteObjCSynchronizedStmt -
1214/// This routine rewrites @synchronized(expr) stmt;
1215/// into:
1216/// objc_sync_enter(expr);
1217/// @try stmt @finally { objc_sync_exit(expr); }
1218///
Steve Naroffb29b4272008-04-14 22:03:09 +00001219Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001220 // Get the start location and compute the semi location.
1221 SourceLocation startLoc = S->getLocStart();
1222 const char *startBuf = SM->getCharacterData(startLoc);
1223
1224 assert((*startBuf == '@') && "bogus @synchronized location");
1225
1226 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001227 buf = "objc_sync_enter((id)";
1228 const char *lparenBuf = startBuf;
1229 while (*lparenBuf != '(') lparenBuf++;
1230 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001231 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1232 // the sync expression is typically a message expression that's already
1233 // been rewritten! (which implies the SourceLocation's are invalid).
1234 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001235 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001236 while (*endBuf != ')') endBuf--;
1237 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001238 buf = ");\n";
1239 // declare a new scope with two variables, _stack and _rethrow.
1240 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1241 buf += "int buf[18/*32-bit i386*/];\n";
1242 buf += "char *pointers[4];} _stack;\n";
1243 buf += "id volatile _rethrow = 0;\n";
1244 buf += "objc_exception_try_enter(&_stack);\n";
1245 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001246 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001247 startLoc = S->getSynchBody()->getLocEnd();
1248 startBuf = SM->getCharacterData(startLoc);
1249
Steve Naroffc7089f12008-08-19 13:04:19 +00001250 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001251 SourceLocation lastCurlyLoc = startLoc;
1252 buf = "}\nelse {\n";
1253 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1254 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001255 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001256 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001257 S->getSynchExpr(),
1258 Context->getObjCIdType(),
1259 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001260 std::string syncExprBufS;
1261 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001262 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001263 buf += syncExprBuf.str();
1264 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001265 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1266 buf += "}\n";
1267 buf += "}";
1268
Chris Lattneraadaf782008-01-31 19:51:04 +00001269 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001270 return 0;
1271}
1272
Steve Naroffb29b4272008-04-14 22:03:09 +00001273Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001274 // Get the start location and compute the semi location.
1275 SourceLocation startLoc = S->getLocStart();
1276 const char *startBuf = SM->getCharacterData(startLoc);
1277
1278 assert((*startBuf == '@') && "bogus @try location");
1279
1280 std::string buf;
1281 // declare a new scope with two variables, _stack and _rethrow.
1282 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1283 buf += "int buf[18/*32-bit i386*/];\n";
1284 buf += "char *pointers[4];} _stack;\n";
1285 buf += "id volatile _rethrow = 0;\n";
1286 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001287 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001288
Chris Lattneraadaf782008-01-31 19:51:04 +00001289 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001290
1291 startLoc = S->getTryBody()->getLocEnd();
1292 startBuf = SM->getCharacterData(startLoc);
1293
1294 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001295
Steve Naroff75730982007-11-07 04:08:17 +00001296 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001297 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1298 if (catchList) {
1299 startLoc = startLoc.getFileLocWithOffset(1);
1300 buf = " /* @catch begin */ else {\n";
1301 buf += " id _caught = objc_exception_extract(&_stack);\n";
1302 buf += " objc_exception_try_enter (&_stack);\n";
1303 buf += " if (_setjmp(_stack.buf))\n";
1304 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1305 buf += " else { /* @catch continue */";
1306
1307 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001308 } else { /* no catch list */
1309 buf = "}\nelse {\n";
1310 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1311 buf += "}";
1312 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001313 }
Steve Naroff75730982007-11-07 04:08:17 +00001314 bool sawIdTypedCatch = false;
1315 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001316 while (catchList) {
1317 Stmt *catchStmt = catchList->getCatchParamStmt();
1318
1319 if (catchList == S->getCatchStmts())
1320 buf = "if ("; // we are generating code for the first catch clause
1321 else
1322 buf = "else if (";
1323 startLoc = catchList->getLocStart();
1324 startBuf = SM->getCharacterData(startLoc);
1325
1326 assert((*startBuf == '@') && "bogus @catch location");
1327
1328 const char *lParenLoc = strchr(startBuf, '(');
1329
Steve Naroffbe4b3332008-02-01 22:08:12 +00001330 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001331 // Now rewrite the body...
1332 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001333 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1334 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001335 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1336 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001337 assert((*bodyBuf == '{') && "bogus @catch body location");
1338
1339 buf += "1) { id _tmp = _caught;";
1340 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1341 buf.c_str(), buf.size());
1342 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001343 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001344 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001345 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001346 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001347 sawIdTypedCatch = true;
1348 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001349 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001350
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001351 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001352 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001353 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001354 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001355 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001356 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001357 }
1358 }
1359 // Now rewrite the body...
1360 lastCatchBody = catchList->getCatchBody();
1361 SourceLocation rParenLoc = catchList->getRParenLoc();
1362 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1363 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1364 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1365 assert((*rParenBuf == ')') && "bogus @catch paren location");
1366 assert((*bodyBuf == '{') && "bogus @catch body location");
1367
1368 buf = " = _caught;";
1369 // Here we replace ") {" with "= _caught;" (which initializes and
1370 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001371 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001372 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001373 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001374 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001375 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001376 catchList = catchList->getNextCatchStmt();
1377 }
1378 // Complete the catch list...
1379 if (lastCatchBody) {
1380 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001381 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1382 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001383
Steve Naroff378f47a2008-09-11 15:29:03 +00001384 // Insert the last (implicit) else clause *before* the right curly brace.
1385 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1386 buf = "} /* last catch end */\n";
1387 buf += "else {\n";
1388 buf += " _rethrow = _caught;\n";
1389 buf += " objc_exception_try_exit(&_stack);\n";
1390 buf += "} } /* @catch end */\n";
1391 if (!S->getFinallyStmt())
1392 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001393 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001394
1395 // Set lastCurlyLoc
1396 lastCurlyLoc = lastCatchBody->getLocEnd();
1397 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001398 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001399 startLoc = finalStmt->getLocStart();
1400 startBuf = SM->getCharacterData(startLoc);
1401 assert((*startBuf == '@') && "bogus @finally start");
1402
1403 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001404 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001405
1406 Stmt *body = finalStmt->getFinallyBody();
1407 SourceLocation startLoc = body->getLocStart();
1408 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001409 assert(*SM->getCharacterData(startLoc) == '{' &&
1410 "bogus @finally body location");
1411 assert(*SM->getCharacterData(endLoc) == '}' &&
1412 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001413
1414 startLoc = startLoc.getFileLocWithOffset(1);
1415 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001416 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001417 endLoc = endLoc.getFileLocWithOffset(-1);
1418 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001419 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001420
1421 // Set lastCurlyLoc
1422 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001423 } else { /* no finally clause - make sure we synthesize an implicit one */
1424 buf = "{ /* implicit finally clause */\n";
1425 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1426 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1427 buf += "}";
1428 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001429 }
1430 // Now emit the final closing curly brace...
1431 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1432 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001433 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001434 return 0;
1435}
1436
Steve Naroffb29b4272008-04-14 22:03:09 +00001437Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001438 return 0;
1439}
1440
Steve Naroffb29b4272008-04-14 22:03:09 +00001441Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001442 return 0;
1443}
1444
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001445// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001446// the throw expression is typically a message expression that's already
1447// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001448Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001449 // Get the start location and compute the semi location.
1450 SourceLocation startLoc = S->getLocStart();
1451 const char *startBuf = SM->getCharacterData(startLoc);
1452
1453 assert((*startBuf == '@') && "bogus @throw location");
1454
1455 std::string buf;
1456 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001457 if (S->getThrowExpr())
1458 buf = "objc_exception_throw(";
1459 else // add an implicit argument
1460 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001461
1462 // handle "@ throw" correctly.
1463 const char *wBuf = strchr(startBuf, 'w');
1464 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1465 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1466
Steve Naroff2bd03922007-11-07 15:32:26 +00001467 const char *semiBuf = strchr(startBuf, ';');
1468 assert((*semiBuf == ';') && "@throw: can't find ';'");
1469 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1470 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001471 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001472 return 0;
1473}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001474
Steve Naroffb29b4272008-04-14 22:03:09 +00001475Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001476 // Create a new string expression.
1477 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001478 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001479 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001480 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1481 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001482 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001483 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001484
Chris Lattner07506182007-11-30 22:53:43 +00001485 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001486 delete Exp;
1487 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001488}
1489
Steve Naroffb29b4272008-04-14 22:03:09 +00001490Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001491 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1492 // Create a call to sel_registerName("selName").
1493 llvm::SmallVector<Expr*, 8> SelExprs;
1494 QualType argType = Context->getPointerType(Context->CharTy);
1495 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1496 Exp->getSelector().getName().size(),
1497 false, argType, SourceLocation(),
1498 SourceLocation()));
1499 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1500 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001501 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001502 delete Exp;
1503 return SelExp;
1504}
1505
Steve Naroffb29b4272008-04-14 22:03:09 +00001506CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001507 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001508 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001509 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001510
1511 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001512 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001513
1514 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001515 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001516 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1517
1518 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001519
Steve Naroff934f2762007-10-24 22:48:43 +00001520 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1521}
1522
Steve Naroffd5255f52007-11-01 13:24:47 +00001523static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1524 const char *&startRef, const char *&endRef) {
1525 while (startBuf < endBuf) {
1526 if (*startBuf == '<')
1527 startRef = startBuf; // mark the start.
1528 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001529 if (startRef && *startRef == '<') {
1530 endRef = startBuf; // mark the end.
1531 return true;
1532 }
1533 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001534 }
1535 startBuf++;
1536 }
1537 return false;
1538}
1539
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001540static void scanToNextArgument(const char *&argRef) {
1541 int angle = 0;
1542 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1543 if (*argRef == '<')
1544 angle++;
1545 else if (*argRef == '>')
1546 angle--;
1547 argRef++;
1548 }
1549 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1550}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001551
Steve Naroffb29b4272008-04-14 22:03:09 +00001552bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001553
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001554 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001555 return true;
1556
Steve Naroffd5255f52007-11-01 13:24:47 +00001557 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001558 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001559 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001560 return true; // we have "Class <Protocol> *".
1561 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001562 return false;
1563}
1564
Steve Naroff4f95b752008-07-29 18:15:38 +00001565void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1566 QualType Type = E->getType();
1567 if (needToScanForQualifiers(Type)) {
1568 SourceLocation Loc = E->getLocStart();
1569 const char *startBuf = SM->getCharacterData(Loc);
1570 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1571 const char *startRef = 0, *endRef = 0;
1572 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1573 // Get the locations of the startRef, endRef.
1574 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1575 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1576 // Comment out the protocol references.
1577 InsertText(LessLoc, "/*", 2);
1578 InsertText(GreaterLoc, "*/", 2);
1579 }
1580 }
1581}
1582
Steve Naroffb29b4272008-04-14 22:03:09 +00001583void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001584 SourceLocation Loc;
1585 QualType Type;
1586 const FunctionTypeProto *proto = 0;
1587 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1588 Loc = VD->getLocation();
1589 Type = VD->getType();
1590 }
1591 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1592 Loc = FD->getLocation();
1593 // Check for ObjC 'id' and class types that have been adorned with protocol
1594 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1595 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1596 assert(funcType && "missing function type");
1597 proto = dyn_cast<FunctionTypeProto>(funcType);
1598 if (!proto)
1599 return;
1600 Type = proto->getResultType();
1601 }
1602 else
1603 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001604
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001605 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001606 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001607
1608 const char *endBuf = SM->getCharacterData(Loc);
1609 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001610 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001611 startBuf--; // scan backward (from the decl location) for return type.
1612 const char *startRef = 0, *endRef = 0;
1613 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1614 // Get the locations of the startRef, endRef.
1615 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1616 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1617 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001618 InsertText(LessLoc, "/*", 2);
1619 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001620 }
1621 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001622 if (!proto)
1623 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001624 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001625 const char *startBuf = SM->getCharacterData(Loc);
1626 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001627 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1628 if (needToScanForQualifiers(proto->getArgType(i))) {
1629 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001630
Steve Naroffd5255f52007-11-01 13:24:47 +00001631 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001632 // scan forward (from the decl location) for argument types.
1633 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001634 const char *startRef = 0, *endRef = 0;
1635 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1636 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001637 SourceLocation LessLoc =
1638 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1639 SourceLocation GreaterLoc =
1640 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001641 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001642 InsertText(LessLoc, "/*", 2);
1643 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001644 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001645 startBuf = ++endBuf;
1646 }
1647 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001648 // If the function name is derived from a macro expansion, then the
1649 // argument buffer will not follow the name. Need to speak with Chris.
1650 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001651 startBuf++; // scan forward (from the decl location) for argument types.
1652 startBuf++;
1653 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001654 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001655}
1656
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001657// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001658void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001659 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1660 llvm::SmallVector<QualType, 16> ArgTys;
1661 ArgTys.push_back(Context->getPointerType(
1662 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001663 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001664 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001665 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001666 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001667 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001668 SelGetUidIdent, getFuncType,
1669 FunctionDecl::Extern, false, 0);
1670}
1671
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001672// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001673void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001674 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1675 llvm::SmallVector<QualType, 16> ArgTys;
1676 ArgTys.push_back(Context->getPointerType(
1677 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001678 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001679 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001680 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001681 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001682 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001683 SelGetProtoIdent, getFuncType,
1684 FunctionDecl::Extern, false, 0);
1685}
1686
Steve Naroffb29b4272008-04-14 22:03:09 +00001687void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001688 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001689 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001690 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001691 return;
1692 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001693 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001694}
1695
Steve Naroffc0a123c2008-03-11 17:37:02 +00001696// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001697void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001698 if (SuperContructorFunctionDecl)
1699 return;
1700 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1701 llvm::SmallVector<QualType, 16> ArgTys;
1702 QualType argT = Context->getObjCIdType();
1703 assert(!argT.isNull() && "Can't find 'id' type");
1704 ArgTys.push_back(argT);
1705 ArgTys.push_back(argT);
1706 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1707 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001708 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001709 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001710 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001711 msgSendIdent, msgSendType,
1712 FunctionDecl::Extern, false, 0);
1713}
1714
Steve Naroff09b266e2007-10-30 23:14:51 +00001715// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001716void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001717 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1718 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001719 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001720 assert(!argT.isNull() && "Can't find 'id' type");
1721 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001722 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001723 assert(!argT.isNull() && "Can't find 'SEL' type");
1724 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001725 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001726 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001727 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001728 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001729 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001730 msgSendIdent, msgSendType,
1731 FunctionDecl::Extern, false, 0);
1732}
1733
Steve Naroff874e2322007-11-15 10:28:18 +00001734// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001735void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001736 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1737 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001738 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001739 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001740 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001741 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1742 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1743 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001744 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001745 assert(!argT.isNull() && "Can't find 'SEL' type");
1746 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001747 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001748 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001749 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001750 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001751 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001752 msgSendIdent, msgSendType,
1753 FunctionDecl::Extern, false, 0);
1754}
1755
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001756// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001757void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001758 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1759 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001760 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001761 assert(!argT.isNull() && "Can't find 'id' type");
1762 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001763 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001764 assert(!argT.isNull() && "Can't find 'SEL' type");
1765 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001766 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001767 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001768 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001769 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001770 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001771 msgSendIdent, msgSendType,
1772 FunctionDecl::Extern, false, 0);
1773}
1774
1775// SynthMsgSendSuperStretFunctionDecl -
1776// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001777void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001778 IdentifierInfo *msgSendIdent =
1779 &Context->Idents.get("objc_msgSendSuper_stret");
1780 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001781 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001782 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001783 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001784 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1785 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1786 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001787 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001788 assert(!argT.isNull() && "Can't find 'SEL' type");
1789 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001790 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001791 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001792 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001793 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001794 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001795 msgSendIdent, msgSendType,
1796 FunctionDecl::Extern, false, 0);
1797}
1798
Steve Naroff1284db82008-05-08 22:02:18 +00001799// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001800void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001801 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1802 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001803 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001804 assert(!argT.isNull() && "Can't find 'id' type");
1805 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001806 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001807 assert(!argT.isNull() && "Can't find 'SEL' type");
1808 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001809 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001810 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001811 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001812 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001813 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001814 msgSendIdent, msgSendType,
1815 FunctionDecl::Extern, false, 0);
1816}
1817
Steve Naroff09b266e2007-10-30 23:14:51 +00001818// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001819void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001820 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1821 llvm::SmallVector<QualType, 16> ArgTys;
1822 ArgTys.push_back(Context->getPointerType(
1823 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001824 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001825 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001826 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001827 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001828 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001829 getClassIdent, getClassType,
1830 FunctionDecl::Extern, false, 0);
1831}
1832
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001833// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001834void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001835 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1836 llvm::SmallVector<QualType, 16> ArgTys;
1837 ArgTys.push_back(Context->getPointerType(
1838 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001839 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001840 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001841 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001842 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001843 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001844 getClassIdent, getClassType,
1845 FunctionDecl::Extern, false, 0);
1846}
1847
Steve Naroffb29b4272008-04-14 22:03:09 +00001848Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001849 QualType strType = getConstantStringStructType();
1850
1851 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001852
1853 std::string tmpName = InFileName;
1854 unsigned i;
1855 for (i=0; i < tmpName.length(); i++) {
1856 char c = tmpName.at(i);
1857 // replace any non alphanumeric characters with '_'.
1858 if (!isalpha(c) && (c < '0' || c > '9'))
1859 tmpName[i] = '_';
1860 }
1861 S += tmpName;
1862 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001863 S += utostr(NumObjCStringLiterals++);
1864
Steve Naroffba92b2e2008-03-27 22:29:16 +00001865 Preamble += "static __NSConstantStringImpl " + S;
1866 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1867 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001868 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001869 std::string prettyBufS;
1870 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001871 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001872 Preamble += prettyBuf.str();
1873 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001874 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001875 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001876
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001877 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001878 &Context->Idents.get(S.c_str()), strType,
1879 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001880 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1881 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1882 Context->getPointerType(DRE->getType()),
1883 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001884 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001885 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Douglas Gregor49badde2008-10-27 19:41:14 +00001886 Exp->getType(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001887 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001888 delete Exp;
1889 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001890}
1891
Steve Naroffb29b4272008-04-14 22:03:09 +00001892ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001893 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00001894 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001895
Chris Lattnerd9f69102008-08-10 01:53:14 +00001896 if (PredefinedExpr *PDE = dyn_cast<PredefinedExpr>(recExpr))
1897 if (PDE->getIdentType() == PredefinedExpr::ObjCSuper) {
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001898 const PointerType *PT = PDE->getType()->getAsPointerType();
1899 assert(PT);
1900 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1901 return IT->getDecl();
1902 }
1903 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001904}
1905
1906// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001907QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001908 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001909 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001910 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001911 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001912 QualType FieldTypes[2];
1913
1914 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001915 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001916 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001917 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001918 // Create fields
1919 FieldDecl *FieldDecls[2];
1920
1921 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001922 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001923 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001924
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001925 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00001926 }
1927 return Context->getTagDeclType(SuperStructDecl);
1928}
1929
Steve Naroffb29b4272008-04-14 22:03:09 +00001930QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001931 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001932 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001933 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001934 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001935 QualType FieldTypes[4];
1936
1937 // struct objc_object *receiver;
1938 FieldTypes[0] = Context->getObjCIdType();
1939 // int flags;
1940 FieldTypes[1] = Context->IntTy;
1941 // char *str;
1942 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1943 // long length;
1944 FieldTypes[3] = Context->LongTy;
1945 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001946 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001947
1948 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001949 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001950 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001951
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001952 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001953 }
1954 return Context->getTagDeclType(ConstantStringDecl);
1955}
1956
Steve Naroffb29b4272008-04-14 22:03:09 +00001957Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001958 if (!SelGetUidFunctionDecl)
1959 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001960 if (!MsgSendFunctionDecl)
1961 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001962 if (!MsgSendSuperFunctionDecl)
1963 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001964 if (!MsgSendStretFunctionDecl)
1965 SynthMsgSendStretFunctionDecl();
1966 if (!MsgSendSuperStretFunctionDecl)
1967 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001968 if (!MsgSendFpretFunctionDecl)
1969 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001970 if (!GetClassFunctionDecl)
1971 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001972 if (!GetMetaClassFunctionDecl)
1973 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001974
Steve Naroff874e2322007-11-15 10:28:18 +00001975 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001976 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1977 // May need to use objc_msgSend_stret() as well.
1978 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001979 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001980 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00001981 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001982 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00001983 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001984 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001985 }
Steve Naroff874e2322007-11-15 10:28:18 +00001986
Steve Naroff934f2762007-10-24 22:48:43 +00001987 // Synthesize a call to objc_msgSend().
1988 llvm::SmallVector<Expr*, 8> MsgExprs;
1989 IdentifierInfo *clsName = Exp->getClassName();
1990
1991 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1992 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00001993 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
1994 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001995 if (!strcmp(clsName->getName(), "super")) {
1996 MsgSendFlavor = MsgSendSuperFunctionDecl;
1997 if (MsgSendStretFlavor)
1998 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1999 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2000
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002001 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002002 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002003
2004 llvm::SmallVector<Expr*, 4> InitExprs;
2005
2006 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002007 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002008 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002009 Context->getObjCIdType(),
2010 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002011 llvm::SmallVector<Expr*, 8> ClsExprs;
2012 QualType argType = Context->getPointerType(Context->CharTy);
2013 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2014 SuperDecl->getIdentifier()->getLength(),
2015 false, argType, SourceLocation(),
2016 SourceLocation()));
2017 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2018 &ClsExprs[0],
2019 ClsExprs.size());
2020 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002021 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002022 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002023 Cls, Context->getObjCIdType(),
2024 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002025 // struct objc_super
2026 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002027 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002028
Steve Naroff23f41272008-03-11 18:14:26 +00002029 if (LangOpts.Microsoft) {
2030 SynthSuperContructorFunctionDecl();
2031 // Simulate a contructor call...
2032 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2033 superType, SourceLocation());
2034 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2035 superType, SourceLocation());
2036 } else {
2037 // (struct objc_super) { <exprs from above> }
2038 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2039 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002040 SourceLocation(), false);
2041 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2042 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002043 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002044 // struct objc_super *
2045 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2046 Context->getPointerType(SuperRep->getType()),
2047 SourceLocation());
2048 MsgExprs.push_back(Unop);
2049 } else {
2050 llvm::SmallVector<Expr*, 8> ClsExprs;
2051 QualType argType = Context->getPointerType(Context->CharTy);
2052 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2053 clsName->getLength(),
2054 false, argType, SourceLocation(),
2055 SourceLocation()));
2056 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2057 &ClsExprs[0],
2058 ClsExprs.size());
2059 MsgExprs.push_back(Cls);
2060 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002061 } else { // instance message.
2062 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002063
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002064 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002065 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002066 if (MsgSendStretFlavor)
2067 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002068 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2069
2070 llvm::SmallVector<Expr*, 4> InitExprs;
2071
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002072 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002073 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002074 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002075 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002076 SourceLocation()),
2077 Context->getObjCIdType(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002078 SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002079
2080 llvm::SmallVector<Expr*, 8> ClsExprs;
2081 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002082 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2083 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002084 false, argType, SourceLocation(),
2085 SourceLocation()));
2086 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002087 &ClsExprs[0],
2088 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002089 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002090 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002091 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002092 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002093 Cls, Context->getObjCIdType(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002094 // struct objc_super
2095 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002096 Expr *SuperRep;
2097
2098 if (LangOpts.Microsoft) {
2099 SynthSuperContructorFunctionDecl();
2100 // Simulate a contructor call...
2101 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2102 superType, SourceLocation());
2103 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2104 superType, SourceLocation());
2105 } else {
2106 // (struct objc_super) { <exprs from above> }
2107 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2108 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002109 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002110 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2111 }
Steve Naroff874e2322007-11-15 10:28:18 +00002112 // struct objc_super *
2113 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2114 Context->getPointerType(SuperRep->getType()),
2115 SourceLocation());
2116 MsgExprs.push_back(Unop);
2117 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002118 // Remove all type-casts because it may contain objc-style types; e.g.
2119 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002120 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002121 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002122 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002123 Context->getObjCIdType(),
2124 SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002125 MsgExprs.push_back(recExpr);
2126 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002127 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002128 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002129 llvm::SmallVector<Expr*, 8> SelExprs;
2130 QualType argType = Context->getPointerType(Context->CharTy);
2131 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2132 Exp->getSelector().getName().size(),
2133 false, argType, SourceLocation(),
2134 SourceLocation()));
2135 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2136 &SelExprs[0], SelExprs.size());
2137 MsgExprs.push_back(SelExp);
2138
2139 // Now push any user supplied arguments.
2140 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002141 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002142 // Make all implicit casts explicit...ICE comes in handy:-)
2143 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2144 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002145 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002146 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002147 : ICE->getType();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002148 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002149 }
2150 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002151 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002152 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002153 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002154 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002155 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002156 userExpr, Context->getObjCIdType(),
2157 SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002158 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002159 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002160 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002161 // We've transferred the ownership to MsgExprs. Null out the argument in
2162 // the original expression, since we will delete it below.
2163 Exp->setArg(i, 0);
2164 }
Steve Naroffab972d32007-11-04 22:37:50 +00002165 // Generate the funky cast.
2166 CastExpr *cast;
2167 llvm::SmallVector<QualType, 8> ArgTypes;
2168 QualType returnType;
2169
2170 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002171 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2172 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2173 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002174 ArgTypes.push_back(Context->getObjCIdType());
2175 ArgTypes.push_back(Context->getObjCSelType());
2176 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002177 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002178 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002179 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2180 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002181 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002182 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2183 if (isBlockPointerType(t)) {
2184 const BlockPointerType *BPT = t->getAsBlockPointerType();
2185 t = Context->getPointerType(BPT->getPointeeType());
2186 }
Steve Naroff352336b2007-11-05 14:36:37 +00002187 ArgTypes.push_back(t);
2188 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002189 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2190 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002191 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002192 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002193 }
2194 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002195 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002196
2197 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002198 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2199 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002200
2201 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2202 // If we don't do this cast, we get the following bizarre warning/note:
2203 // xx.m:13: warning: function called through a non-compatible type
2204 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002205 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002206 Context->getPointerType(Context->VoidTy),
2207 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002208
Steve Naroffab972d32007-11-04 22:37:50 +00002209 // Now do the "normal" pointer to function cast.
2210 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002211 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002212 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002213 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002214 castType = Context->getPointerType(castType);
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002215 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002216
2217 // Don't forget the parens to enforce the proper binding.
2218 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2219
2220 const FunctionType *FT = msgSendType->getAsFunctionType();
2221 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2222 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002223 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002224 if (MsgSendStretFlavor) {
2225 // We have the method which returns a struct/union. Must also generate
2226 // call to objc_msgSend_stret and hang both varieties on a conditional
2227 // expression which dictate which one to envoke depending on size of
2228 // method's return type.
2229
2230 // Create a reference to the objc_msgSend_stret() declaration.
2231 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2232 SourceLocation());
2233 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002234 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002235 Context->getPointerType(Context->VoidTy),
2236 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002237 // Now do the "normal" pointer to function cast.
2238 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002239 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002240 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002241 castType = Context->getPointerType(castType);
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002242 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002243
2244 // Don't forget the parens to enforce the proper binding.
2245 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2246
2247 FT = msgSendType->getAsFunctionType();
2248 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2249 FT->getResultType(), SourceLocation());
2250
2251 // Build sizeof(returnType)
2252 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2253 returnType, Context->getSizeType(),
2254 SourceLocation(), SourceLocation());
2255 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2256 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2257 // For X86 it is more complicated and some kind of target specific routine
2258 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002259 unsigned IntSize =
2260 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002261 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2262 Context->IntTy,
2263 SourceLocation());
2264 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2265 BinaryOperator::LE,
2266 Context->IntTy,
2267 SourceLocation());
2268 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2269 ConditionalOperator *CondExpr =
2270 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002271 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002272 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002273 return ReplacingStmt;
2274}
2275
Steve Naroffb29b4272008-04-14 22:03:09 +00002276Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002277 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002278
Steve Naroff934f2762007-10-24 22:48:43 +00002279 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002280 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002281
Chris Lattnere64b7772007-10-24 16:57:36 +00002282 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002283 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002284}
2285
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002286/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2287/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002288Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002289 if (!GetProtocolFunctionDecl)
2290 SynthGetProtocolFunctionDecl();
2291 // Create a call to objc_getProtocol("ProtocolName").
2292 llvm::SmallVector<Expr*, 8> ProtoExprs;
2293 QualType argType = Context->getPointerType(Context->CharTy);
2294 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2295 strlen(Exp->getProtocol()->getName()),
2296 false, argType, SourceLocation(),
2297 SourceLocation()));
2298 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2299 &ProtoExprs[0],
2300 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002301 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002302 delete Exp;
2303 return ProtoExp;
2304
2305}
2306
Steve Naroffbaf58c32008-05-31 14:15:04 +00002307bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2308 const char *endBuf) {
2309 while (startBuf < endBuf) {
2310 if (*startBuf == '#') {
2311 // Skip whitespace.
2312 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2313 ;
2314 if (!strncmp(startBuf, "if", strlen("if")) ||
2315 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2316 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2317 !strncmp(startBuf, "define", strlen("define")) ||
2318 !strncmp(startBuf, "undef", strlen("undef")) ||
2319 !strncmp(startBuf, "else", strlen("else")) ||
2320 !strncmp(startBuf, "elif", strlen("elif")) ||
2321 !strncmp(startBuf, "endif", strlen("endif")) ||
2322 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2323 !strncmp(startBuf, "include", strlen("include")) ||
2324 !strncmp(startBuf, "import", strlen("import")) ||
2325 !strncmp(startBuf, "include_next", strlen("include_next")))
2326 return true;
2327 }
2328 startBuf++;
2329 }
2330 return false;
2331}
2332
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002333/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002334/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002335void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002336 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002337 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2338 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002339 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002340 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002341 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002342 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002343 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002344 SourceLocation LocStart = CDecl->getLocStart();
2345 SourceLocation LocEnd = CDecl->getLocEnd();
2346
2347 const char *startBuf = SM->getCharacterData(LocStart);
2348 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002349
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002350 // If no ivars and no root or if its root, directly or indirectly,
2351 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002352 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2353 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002354 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002355 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002356 return;
2357 }
2358
2359 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002360 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002361 Result += "\nstruct ";
2362 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002363 if (LangOpts.Microsoft)
2364 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002365
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002366 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002367 const char *cursor = strchr(startBuf, '{');
2368 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002369 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002370 // If the buffer contains preprocessor directives, we do more fine-grained
2371 // rewrites. This is intended to fix code that looks like (which occurs in
2372 // NSURL.h, for example):
2373 //
2374 // #ifdef XYZ
2375 // @interface Foo : NSObject
2376 // #else
2377 // @interface FooBar : NSObject
2378 // #endif
2379 // {
2380 // int i;
2381 // }
2382 // @end
2383 //
2384 // This clause is segregated to avoid breaking the common case.
2385 if (BufferContainsPPDirectives(startBuf, cursor)) {
2386 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2387 CDecl->getClassLoc();
2388 const char *endHeader = SM->getCharacterData(L);
2389 endHeader += Lexer::MeasureTokenLength(L, *SM);
2390
Chris Lattner3db6cae2008-07-21 18:19:38 +00002391 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002392 // advance to the end of the referenced protocols.
2393 while (endHeader < cursor && *endHeader != '>') endHeader++;
2394 endHeader++;
2395 }
2396 // rewrite the original header
2397 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2398 } else {
2399 // rewrite the original header *without* disturbing the '{'
2400 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2401 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002402 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002403 Result = "\n struct ";
2404 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002405 Result += "_IMPL ";
2406 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002407 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002408
2409 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002410 SourceLocation OnePastCurly =
2411 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2412 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002413 }
2414 cursor++; // past '{'
2415
2416 // Now comment out any visibility specifiers.
2417 while (cursor < endBuf) {
2418 if (*cursor == '@') {
2419 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002420 // Skip whitespace.
2421 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2422 /*scan*/;
2423
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002424 // FIXME: presence of @public, etc. inside comment results in
2425 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002426 if (!strncmp(cursor, "public", strlen("public")) ||
2427 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002428 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002429 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002430 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002431 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002432 // FIXME: If there are cases where '<' is used in ivar declaration part
2433 // of user code, then scan the ivar list and use needToScanForQualifiers
2434 // for type checking.
2435 else if (*cursor == '<') {
2436 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002437 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002438 cursor = strchr(cursor, '>');
2439 cursor++;
2440 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002441 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002442 }
Steve Narofffea763e82007-11-14 19:25:57 +00002443 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002444 }
Steve Narofffea763e82007-11-14 19:25:57 +00002445 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002446 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002447 } else { // we don't have any instance variables - insert super struct.
2448 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2449 Result += " {\n struct ";
2450 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002451 Result += "_IMPL ";
2452 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002453 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002454 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002455 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002456 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002457 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002458 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002459}
2460
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002461// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002462/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002463void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002464 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002465 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002466 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002467 const char *ClassName,
2468 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002469 if (MethodBegin == MethodEnd) return;
2470
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002471 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002472 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002473 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002474 SEL _cmd;
2475 char *method_types;
2476 void *_imp;
2477 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002478 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002479 Result += "\nstruct _objc_method {\n";
2480 Result += "\tSEL _cmd;\n";
2481 Result += "\tchar *method_types;\n";
2482 Result += "\tvoid *_imp;\n";
2483 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002484
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002485 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002486 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002487
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002488 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002489
2490 /* struct {
2491 struct _objc_method_list *next_method;
2492 int method_count;
2493 struct _objc_method method_list[];
2494 }
2495 */
2496 Result += "\nstatic struct {\n";
2497 Result += "\tstruct _objc_method_list *next_method;\n";
2498 Result += "\tint method_count;\n";
2499 Result += "\tstruct _objc_method method_list[";
2500 Result += utostr(MethodEnd-MethodBegin);
2501 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002502 Result += prefix;
2503 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2504 Result += "_METHODS_";
2505 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002506 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002507 Result += IsInstanceMethod ? "inst" : "cls";
2508 Result += "_meth\")))= ";
2509 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002510
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002511 Result += "\t,{{(SEL)\"";
2512 Result += (*MethodBegin)->getSelector().getName().c_str();
2513 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002514 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002515 Result += "\", \"";
2516 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002517 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002518 Result += MethodInternalNames[*MethodBegin];
2519 Result += "}\n";
2520 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2521 Result += "\t ,{(SEL)\"";
2522 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002523 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002524 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002525 Result += "\", \"";
2526 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002527 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002528 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002529 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002530 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002531 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002532}
2533
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002534/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002535void RewriteObjC::
2536RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2537 const char *prefix,
2538 const char *ClassName,
2539 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002540 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002541 if (Protocols.empty()) return;
2542
2543 for (unsigned i = 0; i != Protocols.size(); i++) {
2544 ObjCProtocolDecl *PDecl = Protocols[i];
2545 // Output struct protocol_methods holder of method selector and type.
2546 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2547 /* struct protocol_methods {
2548 SEL _cmd;
2549 char *method_types;
2550 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002551 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002552 Result += "\nstruct protocol_methods {\n";
2553 Result += "\tSEL _cmd;\n";
2554 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002555 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002556
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002557 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002558 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002559 // Do not synthesize the protocol more than once.
2560 if (ObjCSynthesizedProtocols.count(PDecl))
2561 continue;
2562
2563 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2564 unsigned NumMethods = PDecl->getNumInstanceMethods();
2565 /* struct _objc_protocol_method_list {
2566 int protocol_method_count;
2567 struct protocol_methods protocols[];
2568 }
2569 */
2570 Result += "\nstatic struct {\n";
2571 Result += "\tint protocol_method_count;\n";
2572 Result += "\tstruct protocol_methods protocols[";
2573 Result += utostr(NumMethods);
2574 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2575 Result += PDecl->getName();
2576 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2577 "{\n\t" + utostr(NumMethods) + "\n";
2578
2579 // Output instance methods declared in this protocol.
2580 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2581 E = PDecl->instmeth_end(); I != E; ++I) {
2582 if (I == PDecl->instmeth_begin())
2583 Result += "\t ,{{(SEL)\"";
2584 else
2585 Result += "\t ,{(SEL)\"";
2586 Result += (*I)->getSelector().getName().c_str();
2587 std::string MethodTypeString;
2588 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2589 Result += "\", \"";
2590 Result += MethodTypeString;
2591 Result += "\"}\n";
2592 }
2593 Result += "\t }\n};\n";
2594 }
2595
2596 // Output class methods declared in this protocol.
2597 int NumMethods = PDecl->getNumClassMethods();
2598 if (NumMethods > 0) {
2599 /* struct _objc_protocol_method_list {
2600 int protocol_method_count;
2601 struct protocol_methods protocols[];
2602 }
2603 */
2604 Result += "\nstatic struct {\n";
2605 Result += "\tint protocol_method_count;\n";
2606 Result += "\tstruct protocol_methods protocols[";
2607 Result += utostr(NumMethods);
2608 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2609 Result += PDecl->getName();
2610 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2611 "{\n\t";
2612 Result += utostr(NumMethods);
2613 Result += "\n";
2614
2615 // Output instance methods declared in this protocol.
2616 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2617 E = PDecl->classmeth_end(); I != E; ++I) {
2618 if (I == PDecl->classmeth_begin())
2619 Result += "\t ,{{(SEL)\"";
2620 else
2621 Result += "\t ,{(SEL)\"";
2622 Result += (*I)->getSelector().getName().c_str();
2623 std::string MethodTypeString;
2624 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2625 Result += "\", \"";
2626 Result += MethodTypeString;
2627 Result += "\"}\n";
2628 }
2629 Result += "\t }\n};\n";
2630 }
2631
2632 // Output:
2633 /* struct _objc_protocol {
2634 // Objective-C 1.0 extensions
2635 struct _objc_protocol_extension *isa;
2636 char *protocol_name;
2637 struct _objc_protocol **protocol_list;
2638 struct _objc_protocol_method_list *instance_methods;
2639 struct _objc_protocol_method_list *class_methods;
2640 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002641 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002642 static bool objc_protocol = false;
2643 if (!objc_protocol) {
2644 Result += "\nstruct _objc_protocol {\n";
2645 Result += "\tstruct _objc_protocol_extension *isa;\n";
2646 Result += "\tchar *protocol_name;\n";
2647 Result += "\tstruct _objc_protocol **protocol_list;\n";
2648 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2649 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2650 Result += "};\n";
2651
2652 objc_protocol = true;
2653 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002654
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002655 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2656 Result += PDecl->getName();
2657 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2658 "{\n\t0, \"";
2659 Result += PDecl->getName();
2660 Result += "\", 0, ";
2661 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2662 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2663 Result += PDecl->getName();
2664 Result += ", ";
2665 }
2666 else
2667 Result += "0, ";
2668 if (PDecl->getNumClassMethods() > 0) {
2669 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2670 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002671 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002672 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002673 else
2674 Result += "0\n";
2675 Result += "};\n";
2676
2677 // Mark this protocol as having been generated.
2678 if (!ObjCSynthesizedProtocols.insert(PDecl))
2679 assert(false && "protocol already synthesized");
2680 }
2681 // Output the top lovel protocol meta-data for the class.
2682 /* struct _objc_protocol_list {
2683 struct _objc_protocol_list *next;
2684 int protocol_count;
2685 struct _objc_protocol *class_protocols[];
2686 }
2687 */
2688 Result += "\nstatic struct {\n";
2689 Result += "\tstruct _objc_protocol_list *next;\n";
2690 Result += "\tint protocol_count;\n";
2691 Result += "\tstruct _objc_protocol *class_protocols[";
2692 Result += utostr(Protocols.size());
2693 Result += "];\n} _OBJC_";
2694 Result += prefix;
2695 Result += "_PROTOCOLS_";
2696 Result += ClassName;
2697 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2698 "{\n\t0, ";
2699 Result += utostr(Protocols.size());
2700 Result += "\n";
2701
2702 Result += "\t,{&_OBJC_PROTOCOL_";
2703 Result += Protocols[0]->getName();
2704 Result += " \n";
2705
2706 for (unsigned i = 1; i != Protocols.size(); i++) {
2707 Result += "\t ,&_OBJC_PROTOCOL_";
2708 Result += Protocols[i]->getName();
2709 Result += "\n";
2710 }
2711 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002712}
2713
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002714/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002715/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002716void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002717 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002718 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002719 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002720 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002721 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2722 CDecl = CDecl->getNextClassCategory())
2723 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2724 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002725
Chris Lattnereb44eee2007-12-23 01:40:15 +00002726 std::string FullCategoryName = ClassDecl->getName();
2727 FullCategoryName += '_';
2728 FullCategoryName += IDecl->getName();
2729
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002730 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002731 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002732 true, "CATEGORY_", FullCategoryName.c_str(),
2733 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002734
2735 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002736 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002737 false, "CATEGORY_", FullCategoryName.c_str(),
2738 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002739
2740 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002741 // Null CDecl is case of a category implementation with no category interface
2742 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002743 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002744 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002745
2746 /* struct _objc_category {
2747 char *category_name;
2748 char *class_name;
2749 struct _objc_method_list *instance_methods;
2750 struct _objc_method_list *class_methods;
2751 struct _objc_protocol_list *protocols;
2752 // Objective-C 1.0 extensions
2753 uint32_t size; // sizeof (struct _objc_category)
2754 struct _objc_property_list *instance_properties; // category's own
2755 // @property decl.
2756 };
2757 */
2758
2759 static bool objc_category = false;
2760 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002761 Result += "\nstruct _objc_category {\n";
2762 Result += "\tchar *category_name;\n";
2763 Result += "\tchar *class_name;\n";
2764 Result += "\tstruct _objc_method_list *instance_methods;\n";
2765 Result += "\tstruct _objc_method_list *class_methods;\n";
2766 Result += "\tstruct _objc_protocol_list *protocols;\n";
2767 Result += "\tunsigned int size;\n";
2768 Result += "\tstruct _objc_property_list *instance_properties;\n";
2769 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002770 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002771 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002772 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2773 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002774 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002775 Result += IDecl->getName();
2776 Result += "\"\n\t, \"";
2777 Result += ClassDecl->getName();
2778 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002779
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002780 if (IDecl->getNumInstanceMethods() > 0) {
2781 Result += "\t, (struct _objc_method_list *)"
2782 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2783 Result += FullCategoryName;
2784 Result += "\n";
2785 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002786 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002787 Result += "\t, 0\n";
2788 if (IDecl->getNumClassMethods() > 0) {
2789 Result += "\t, (struct _objc_method_list *)"
2790 "&_OBJC_CATEGORY_CLASS_METHODS_";
2791 Result += FullCategoryName;
2792 Result += "\n";
2793 }
2794 else
2795 Result += "\t, 0\n";
2796
Chris Lattner780f3292008-07-21 21:32:27 +00002797 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002798 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2799 Result += FullCategoryName;
2800 Result += "\n";
2801 }
2802 else
2803 Result += "\t, 0\n";
2804 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002805}
2806
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002807/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2808/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002809void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002810 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002811 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002812 if (ivar->isBitField()) {
2813 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2814 // place all bitfields at offset 0.
2815 Result += "0";
2816 } else {
2817 Result += "__OFFSETOFIVAR__(struct ";
2818 Result += IDecl->getName();
2819 if (LangOpts.Microsoft)
2820 Result += "_IMPL";
2821 Result += ", ";
2822 Result += ivar->getName();
2823 Result += ")";
2824 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002825}
2826
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002827//===----------------------------------------------------------------------===//
2828// Meta Data Emission
2829//===----------------------------------------------------------------------===//
2830
Steve Naroffb29b4272008-04-14 22:03:09 +00002831void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002832 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002833 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002834
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002835 // Explictly declared @interface's are already synthesized.
2836 if (CDecl->ImplicitInterfaceDecl()) {
2837 // FIXME: Implementation of a class with no @interface (legacy) doese not
2838 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002839 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002840 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002841
Chris Lattnerbe6df082007-12-12 07:56:42 +00002842 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002843 unsigned NumIvars = !IDecl->ivar_empty()
2844 ? IDecl->ivar_size()
2845 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002846 if (NumIvars > 0) {
2847 static bool objc_ivar = false;
2848 if (!objc_ivar) {
2849 /* struct _objc_ivar {
2850 char *ivar_name;
2851 char *ivar_type;
2852 int ivar_offset;
2853 };
2854 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002855 Result += "\nstruct _objc_ivar {\n";
2856 Result += "\tchar *ivar_name;\n";
2857 Result += "\tchar *ivar_type;\n";
2858 Result += "\tint ivar_offset;\n";
2859 Result += "};\n";
2860
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002861 objc_ivar = true;
2862 }
2863
Steve Naroff946a6932008-03-11 00:12:29 +00002864 /* struct {
2865 int ivar_count;
2866 struct _objc_ivar ivar_list[nIvars];
2867 };
2868 */
2869 Result += "\nstatic struct {\n";
2870 Result += "\tint ivar_count;\n";
2871 Result += "\tstruct _objc_ivar ivar_list[";
2872 Result += utostr(NumIvars);
2873 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002874 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002875 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002876 "{\n\t";
2877 Result += utostr(NumIvars);
2878 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002879
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002880 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002881 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002882 IVI = IDecl->ivar_begin();
2883 IVE = IDecl->ivar_end();
2884 } else {
2885 IVI = CDecl->ivar_begin();
2886 IVE = CDecl->ivar_end();
2887 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002888 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002889 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002890 Result += "\", \"";
2891 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002892 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002893 Result += StrEncoding;
2894 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002895 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002896 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002897 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002898 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002899 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002900 Result += "\", \"";
2901 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002902 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002903 Result += StrEncoding;
2904 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002905 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002906 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002907 }
2908
2909 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002910 }
2911
2912 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002913 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002914 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002915
2916 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002917 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002918 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002919
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002920 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00002921 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002922 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002923
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002924
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002925 // Declaration of class/meta-class metadata
2926 /* struct _objc_class {
2927 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002928 const char *super_class_name;
2929 char *name;
2930 long version;
2931 long info;
2932 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002933 struct _objc_ivar_list *ivars;
2934 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002935 struct objc_cache *cache;
2936 struct objc_protocol_list *protocols;
2937 const char *ivar_layout;
2938 struct _objc_class_ext *ext;
2939 };
2940 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002941 static bool objc_class = false;
2942 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002943 Result += "\nstruct _objc_class {\n";
2944 Result += "\tstruct _objc_class *isa;\n";
2945 Result += "\tconst char *super_class_name;\n";
2946 Result += "\tchar *name;\n";
2947 Result += "\tlong version;\n";
2948 Result += "\tlong info;\n";
2949 Result += "\tlong instance_size;\n";
2950 Result += "\tstruct _objc_ivar_list *ivars;\n";
2951 Result += "\tstruct _objc_method_list *methods;\n";
2952 Result += "\tstruct objc_cache *cache;\n";
2953 Result += "\tstruct _objc_protocol_list *protocols;\n";
2954 Result += "\tconst char *ivar_layout;\n";
2955 Result += "\tstruct _objc_class_ext *ext;\n";
2956 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002957 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002958 }
2959
2960 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002961 ObjCInterfaceDecl *RootClass = 0;
2962 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002963 while (SuperClass) {
2964 RootClass = SuperClass;
2965 SuperClass = SuperClass->getSuperClass();
2966 }
2967 SuperClass = CDecl->getSuperClass();
2968
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002969 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2970 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002971 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002972 "{\n\t(struct _objc_class *)\"";
2973 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2974 Result += "\"";
2975
2976 if (SuperClass) {
2977 Result += ", \"";
2978 Result += SuperClass->getName();
2979 Result += "\", \"";
2980 Result += CDecl->getName();
2981 Result += "\"";
2982 }
2983 else {
2984 Result += ", 0, \"";
2985 Result += CDecl->getName();
2986 Result += "\"";
2987 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002988 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002989 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002990 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002991 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002992 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002993 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002994 Result += "\n";
2995 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002996 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002997 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00002998 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002999 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003000 Result += CDecl->getName();
3001 Result += ",0,0\n";
3002 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003003 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003004 Result += "\t,0,0,0,0\n";
3005 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003006
3007 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003008 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3009 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003010 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003011 "{\n\t&_OBJC_METACLASS_";
3012 Result += CDecl->getName();
3013 if (SuperClass) {
3014 Result += ", \"";
3015 Result += SuperClass->getName();
3016 Result += "\", \"";
3017 Result += CDecl->getName();
3018 Result += "\"";
3019 }
3020 else {
3021 Result += ", 0, \"";
3022 Result += CDecl->getName();
3023 Result += "\"";
3024 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003025 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003026 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003027 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003028 Result += ",0";
3029 else {
3030 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003031 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003032 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003033 if (LangOpts.Microsoft)
3034 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003035 Result += ")";
3036 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003037 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003038 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003039 Result += CDecl->getName();
3040 Result += "\n\t";
3041 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003042 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003043 Result += ",0";
3044 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003045 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003046 Result += CDecl->getName();
3047 Result += ", 0\n\t";
3048 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003049 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003050 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003051 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003052 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003053 Result += CDecl->getName();
3054 Result += ", 0,0\n";
3055 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003056 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003057 Result += ",0,0,0\n";
3058 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003059}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003060
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003061/// RewriteImplementations - This routine rewrites all method implementations
3062/// and emits meta-data.
3063
Steve Naroffb29b4272008-04-14 22:03:09 +00003064void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003065 int ClsDefCount = ClassImplementation.size();
3066 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003067
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003068 if (ClsDefCount == 0 && CatDefCount == 0)
3069 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003070 // Rewrite implemented methods
3071 for (int i = 0; i < ClsDefCount; i++)
3072 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003073
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003074 for (int i = 0; i < CatDefCount; i++)
3075 RewriteImplementationDecl(CategoryImplementation[i]);
3076
Steve Naroff5df5b762008-05-07 21:23:49 +00003077 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003078 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003079 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003080 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003081 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003082
3083 // For each implemented category, write out all its meta data.
3084 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003085 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003086
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003087 // Write objc_symtab metadata
3088 /*
3089 struct _objc_symtab
3090 {
3091 long sel_ref_cnt;
3092 SEL *refs;
3093 short cls_def_cnt;
3094 short cat_def_cnt;
3095 void *defs[cls_def_cnt + cat_def_cnt];
3096 };
3097 */
3098
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003099 Result += "\nstruct _objc_symtab {\n";
3100 Result += "\tlong sel_ref_cnt;\n";
3101 Result += "\tSEL *refs;\n";
3102 Result += "\tshort cls_def_cnt;\n";
3103 Result += "\tshort cat_def_cnt;\n";
3104 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3105 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003106
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003107 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003108 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003109 Result += "\t0, 0, " + utostr(ClsDefCount)
3110 + ", " + utostr(CatDefCount) + "\n";
3111 for (int i = 0; i < ClsDefCount; i++) {
3112 Result += "\t,&_OBJC_CLASS_";
3113 Result += ClassImplementation[i]->getName();
3114 Result += "\n";
3115 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003116
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003117 for (int i = 0; i < CatDefCount; i++) {
3118 Result += "\t,&_OBJC_CATEGORY_";
3119 Result += CategoryImplementation[i]->getClassInterface()->getName();
3120 Result += "_";
3121 Result += CategoryImplementation[i]->getName();
3122 Result += "\n";
3123 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003124
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003125 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003126
3127 // Write objc_module metadata
3128
3129 /*
3130 struct _objc_module {
3131 long version;
3132 long size;
3133 const char *name;
3134 struct _objc_symtab *symtab;
3135 }
3136 */
3137
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003138 Result += "\nstruct _objc_module {\n";
3139 Result += "\tlong version;\n";
3140 Result += "\tlong size;\n";
3141 Result += "\tconst char *name;\n";
3142 Result += "\tstruct _objc_symtab *symtab;\n";
3143 Result += "};\n\n";
3144 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003145 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003146 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3147 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003148 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003149
3150 if (LangOpts.Microsoft) {
3151 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003152 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003153 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3154 Result += "&_OBJC_MODULES;\n";
3155 Result += "#pragma data_seg(pop)\n\n";
3156 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003157}
Chris Lattner311ff022007-10-16 22:36:42 +00003158
Steve Naroff54055232008-10-27 17:20:55 +00003159std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3160 const char *funcName,
3161 std::string Tag) {
3162 const FunctionType *AFT = CE->getFunctionType();
3163 QualType RT = AFT->getResultType();
3164 std::string StructRef = "struct " + Tag;
3165 std::string S = "static " + RT.getAsString() + " __" +
3166 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003167
Steve Naroff54055232008-10-27 17:20:55 +00003168 BlockDecl *BD = CE->getBlockDecl();
3169
3170 if (isa<FunctionTypeNoProto>(AFT)) {
3171 S += "()";
3172 } else if (BD->param_empty()) {
3173 S += "(" + StructRef + " *__cself)";
3174 } else {
3175 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3176 assert(FT && "SynthesizeBlockFunc: No function proto");
3177 S += '(';
3178 // first add the implicit argument.
3179 S += StructRef + " *__cself, ";
3180 std::string ParamStr;
3181 for (BlockDecl::param_iterator AI = BD->param_begin(),
3182 E = BD->param_end(); AI != E; ++AI) {
3183 if (AI != BD->param_begin()) S += ", ";
3184 ParamStr = (*AI)->getName();
3185 (*AI)->getType().getAsStringInternal(ParamStr);
3186 S += ParamStr;
3187 }
3188 if (FT->isVariadic()) {
3189 if (!BD->param_empty()) S += ", ";
3190 S += "...";
3191 }
3192 S += ')';
3193 }
3194 S += " {\n";
3195
3196 // Create local declarations to avoid rewriting all closure decl ref exprs.
3197 // First, emit a declaration for all "by ref" decls.
3198 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3199 E = BlockByRefDecls.end(); I != E; ++I) {
3200 S += " ";
3201 std::string Name = (*I)->getName();
3202 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
3203 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
3204 }
3205 // Next, emit a declaration for all "by copy" declarations.
3206 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3207 E = BlockByCopyDecls.end(); I != E; ++I) {
3208 S += " ";
3209 std::string Name = (*I)->getName();
3210 // Handle nested closure invocation. For example:
3211 //
3212 // void (^myImportedClosure)(void);
3213 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3214 //
3215 // void (^anotherClosure)(void);
3216 // anotherClosure = ^(void) {
3217 // myImportedClosure(); // import and invoke the closure
3218 // };
3219 //
3220 if (isBlockPointerType((*I)->getType()))
3221 S += "struct __block_impl *";
3222 else
3223 (*I)->getType().getAsStringInternal(Name);
3224 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
3225 }
3226 std::string RewrittenStr = RewrittenBlockExprs[CE];
3227 const char *cstr = RewrittenStr.c_str();
3228 while (*cstr++ != '{') ;
3229 S += cstr;
3230 S += "\n";
3231 return S;
3232}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003233
Steve Naroff54055232008-10-27 17:20:55 +00003234std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3235 const char *funcName,
3236 std::string Tag) {
3237 std::string StructRef = "struct " + Tag;
3238 std::string S = "static void __";
3239
3240 S += funcName;
3241 S += "_block_copy_" + utostr(i);
3242 S += "(" + StructRef;
3243 S += "*dst, " + StructRef;
3244 S += "*src) {";
3245 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3246 E = ImportedBlockDecls.end(); I != E; ++I) {
3247 S += "_Block_copy_assign(&dst->";
3248 S += (*I)->getName();
3249 S += ", src->";
3250 S += (*I)->getName();
3251 S += ");}";
3252 }
3253 S += "\nstatic void __";
3254 S += funcName;
3255 S += "_block_dispose_" + utostr(i);
3256 S += "(" + StructRef;
3257 S += "*src) {";
3258 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3259 E = ImportedBlockDecls.end(); I != E; ++I) {
3260 S += "_Block_destroy(src->";
3261 S += (*I)->getName();
3262 S += ");";
3263 }
3264 S += "}\n";
3265 return S;
3266}
3267
3268std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3269 bool hasCopyDisposeHelpers) {
3270 std::string S = "struct " + Tag;
3271 std::string Constructor = " " + Tag;
3272
3273 S += " {\n struct __block_impl impl;\n";
3274
3275 if (hasCopyDisposeHelpers)
3276 S += " void *copy;\n void *dispose;\n";
3277
3278 Constructor += "(void *fp";
3279
3280 if (hasCopyDisposeHelpers)
3281 Constructor += ", void *copyHelp, void *disposeHelp";
3282
3283 if (BlockDeclRefs.size()) {
3284 // Output all "by copy" declarations.
3285 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3286 E = BlockByCopyDecls.end(); I != E; ++I) {
3287 S += " ";
3288 std::string FieldName = (*I)->getName();
3289 std::string ArgName = "_" + FieldName;
3290 // Handle nested closure invocation. For example:
3291 //
3292 // void (^myImportedBlock)(void);
3293 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3294 //
3295 // void (^anotherBlock)(void);
3296 // anotherBlock = ^(void) {
3297 // myImportedBlock(); // import and invoke the closure
3298 // };
3299 //
3300 if (isBlockPointerType((*I)->getType())) {
3301 S += "struct __block_impl *";
3302 Constructor += ", void *" + ArgName;
3303 } else {
3304 (*I)->getType().getAsStringInternal(FieldName);
3305 (*I)->getType().getAsStringInternal(ArgName);
3306 Constructor += ", " + ArgName;
3307 }
3308 S += FieldName + ";\n";
3309 }
3310 // Output all "by ref" declarations.
3311 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3312 E = BlockByRefDecls.end(); I != E; ++I) {
3313 S += " ";
3314 std::string FieldName = (*I)->getName();
3315 std::string ArgName = "_" + FieldName;
3316 // Handle nested closure invocation. For example:
3317 //
3318 // void (^myImportedBlock)(void);
3319 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3320 //
3321 // void (^anotherBlock)(void);
3322 // anotherBlock = ^(void) {
3323 // myImportedBlock(); // import and invoke the closure
3324 // };
3325 //
3326 if (isBlockPointerType((*I)->getType())) {
3327 S += "struct __block_impl *";
3328 Constructor += ", void *" + ArgName;
3329 } else {
3330 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3331 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3332 Constructor += ", " + ArgName;
3333 }
3334 S += FieldName + "; // by ref\n";
3335 }
3336 // Finish writing the constructor.
3337 // FIXME: handle NSConcreteGlobalBlock.
3338 Constructor += ", int flags=0) {\n";
3339 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3340 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3341
3342 if (hasCopyDisposeHelpers)
3343 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3344
3345 // Initialize all "by copy" arguments.
3346 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3347 E = BlockByCopyDecls.end(); I != E; ++I) {
3348 std::string Name = (*I)->getName();
3349 Constructor += " ";
3350 if (isBlockPointerType((*I)->getType()))
3351 Constructor += Name + " = (struct __block_impl *)_";
3352 else
3353 Constructor += Name + " = _";
3354 Constructor += Name + ";\n";
3355 }
3356 // Initialize all "by ref" arguments.
3357 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3358 E = BlockByRefDecls.end(); I != E; ++I) {
3359 std::string Name = (*I)->getName();
3360 Constructor += " ";
3361 if (isBlockPointerType((*I)->getType()))
3362 Constructor += Name + " = (struct __block_impl *)_";
3363 else
3364 Constructor += Name + " = _";
3365 Constructor += Name + ";\n";
3366 }
3367 } else {
3368 // Finish writing the constructor.
3369 // FIXME: handle NSConcreteGlobalBlock.
3370 Constructor += ", int flags=0) {\n";
3371 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3372 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3373 if (hasCopyDisposeHelpers)
3374 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3375 }
3376 Constructor += " ";
3377 Constructor += "}\n";
3378 S += Constructor;
3379 S += "};\n";
3380 return S;
3381}
3382
3383void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3384 const char *FunName) {
3385 // Insert closures that were part of the function.
3386 for (unsigned i = 0; i < Blocks.size(); i++) {
3387
3388 CollectBlockDeclRefInfo(Blocks[i]);
3389
3390 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3391
3392 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3393 ImportedBlockDecls.size() > 0);
3394
3395 InsertText(FunLocStart, CI.c_str(), CI.size());
3396
3397 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3398
3399 InsertText(FunLocStart, CF.c_str(), CF.size());
3400
3401 if (ImportedBlockDecls.size()) {
3402 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3403 InsertText(FunLocStart, HF.c_str(), HF.size());
3404 }
3405
3406 BlockDeclRefs.clear();
3407 BlockByRefDecls.clear();
3408 BlockByCopyDecls.clear();
3409 BlockCallExprs.clear();
3410 ImportedBlockDecls.clear();
3411 }
3412 Blocks.clear();
3413 RewrittenBlockExprs.clear();
3414}
3415
3416void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3417 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3418 const char *FuncName = FD->getName();
3419
3420 SynthesizeBlockLiterals(FunLocStart, FuncName);
3421}
3422
3423void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3424 SourceLocation FunLocStart = MD->getLocStart();
3425 std::string FuncName = std::string(MD->getSelector().getName());
3426 // Convert colons to underscores.
3427 std::string::size_type loc = 0;
3428 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3429 FuncName.replace(loc, 1, "_");
3430
3431 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3432}
3433
3434void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3435 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3436 CI != E; ++CI)
3437 if (*CI) {
3438 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3439 GetBlockDeclRefExprs(CBE->getBody());
3440 else
3441 GetBlockDeclRefExprs(*CI);
3442 }
3443 // Handle specific things.
3444 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3445 // FIXME: Handle enums.
3446 if (!isa<FunctionDecl>(CDRE->getDecl()))
3447 BlockDeclRefs.push_back(CDRE);
3448 return;
3449}
3450
3451void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3452 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3453 CI != E; ++CI)
3454 if (*CI) {
3455 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3456 GetBlockCallExprs(CBE->getBody());
3457 else
3458 GetBlockCallExprs(*CI);
3459 }
3460
3461 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3462 if (CE->getCallee()->getType()->isBlockPointerType()) {
3463 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3464 }
3465 }
3466 return;
3467}
3468
3469std::string RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
3470 // Navigate to relevant type information.
3471 const char *closureName = 0;
3472 const BlockPointerType *CPT = 0;
3473
3474 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
3475 closureName = DRE->getDecl()->getName();
3476 CPT = DRE->getType()->getAsBlockPointerType();
3477 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
3478 closureName = CDRE->getDecl()->getName();
3479 CPT = CDRE->getType()->getAsBlockPointerType();
3480 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
3481 closureName = MExpr->getMemberDecl()->getName();
3482 CPT = MExpr->getType()->getAsBlockPointerType();
3483 } else {
3484 assert(1 && "RewriteBlockClass: Bad type");
3485 }
3486 assert(CPT && "RewriteBlockClass: Bad type");
3487 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3488 assert(FT && "RewriteBlockClass: Bad type");
3489 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3490 // FTP will be null for closures that don't take arguments.
3491
3492 // Build a closure call - start with a paren expr to enforce precedence.
3493 std::string BlockCall = "(";
3494
3495 // Synthesize the cast.
3496 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
3497 BlockCall += "(struct __block_impl *";
3498 if (FTP) {
3499 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3500 E = FTP->arg_type_end(); I && (I != E); ++I)
3501 BlockCall += ", " + (*I).getAsString();
3502 }
3503 BlockCall += "))"; // close the argument list and paren expression.
3504
3505 // Invoke the closure. We need to cast it since the declaration type is
3506 // bogus (it's a function pointer type)
3507 BlockCall += "((struct __block_impl *)";
3508 std::string closureExprBufStr;
3509 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
3510 Exp->getCallee()->printPretty(closureExprBuf);
3511 BlockCall += closureExprBuf.str();
3512 BlockCall += ")->FuncPtr)";
3513
3514 // Add the arguments.
3515 BlockCall += "((struct __block_impl *)";
3516 BlockCall += closureExprBuf.str();
3517 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3518 E = Exp->arg_end(); I != E; ++I) {
3519 std::string syncExprBufS;
3520 llvm::raw_string_ostream Buf(syncExprBufS);
3521 (*I)->printPretty(Buf);
3522 BlockCall += ", " + Buf.str();
3523 }
3524 return BlockCall;
3525}
3526
3527void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
3528 std::string BlockCall = SynthesizeBlockCall(Exp);
3529
3530 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
3531 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
3532
3533 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
3534 BlockCall.c_str(), BlockCall.size());
3535}
3536
3537void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3538 // FIXME: Add more elaborate code generation required by the ABI.
3539 InsertText(BDRE->getLocStart(), "*", 1);
3540}
3541
3542void RewriteObjC::RewriteCastExpr(CastExpr *CE) {
3543 SourceLocation LocStart = CE->getLocStart();
3544 SourceLocation LocEnd = CE->getLocEnd();
Steve Narofffa15fd92008-10-28 20:29:00 +00003545
3546 // Need to avoid trying to rewrite synthesized casts.
3547 if (LocStart.isInvalid())
3548 return;
3549
Steve Naroff54055232008-10-27 17:20:55 +00003550 const char *startBuf = SM->getCharacterData(LocStart);
3551 const char *endBuf = SM->getCharacterData(LocEnd);
3552
3553 // advance the location to startArgList.
3554 const char *argPtr = startBuf;
3555
3556 while (*argPtr++ && (argPtr < endBuf)) {
3557 switch (*argPtr) {
3558 case '^':
3559 // Replace the '^' with '*'.
3560 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3561 ReplaceText(LocStart, 1, "*", 1);
3562 break;
3563 }
3564 }
3565 return;
3566}
3567
3568void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3569 SourceLocation DeclLoc = FD->getLocation();
3570 unsigned parenCount = 0;
3571
3572 // We have 1 or more arguments that have closure pointers.
3573 const char *startBuf = SM->getCharacterData(DeclLoc);
3574 const char *startArgList = strchr(startBuf, '(');
3575
3576 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3577
3578 parenCount++;
3579 // advance the location to startArgList.
3580 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3581 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3582
3583 const char *argPtr = startArgList;
3584
3585 while (*argPtr++ && parenCount) {
3586 switch (*argPtr) {
3587 case '^':
3588 // Replace the '^' with '*'.
3589 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3590 ReplaceText(DeclLoc, 1, "*", 1);
3591 break;
3592 case '(':
3593 parenCount++;
3594 break;
3595 case ')':
3596 parenCount--;
3597 break;
3598 }
3599 }
3600 return;
3601}
3602
3603bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3604 const FunctionTypeProto *FTP;
3605 const PointerType *PT = QT->getAsPointerType();
3606 if (PT) {
3607 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3608 } else {
3609 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3610 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3611 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3612 }
3613 if (FTP) {
3614 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3615 E = FTP->arg_type_end(); I != E; ++I)
3616 if (isBlockPointerType(*I))
3617 return true;
3618 }
3619 return false;
3620}
3621
3622void RewriteObjC::GetExtentOfArgList(const char *Name,
3623 const char *&LParen, const char *&RParen) {
3624 const char *argPtr = strchr(Name, '(');
3625 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3626
3627 LParen = argPtr; // output the start.
3628 argPtr++; // skip past the left paren.
3629 unsigned parenCount = 1;
3630
3631 while (*argPtr && parenCount) {
3632 switch (*argPtr) {
3633 case '(': parenCount++; break;
3634 case ')': parenCount--; break;
3635 default: break;
3636 }
3637 if (parenCount) argPtr++;
3638 }
3639 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3640 RParen = argPtr; // output the end
3641}
3642
3643void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3644 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3645 RewriteBlockPointerFunctionArgs(FD);
3646 return;
3647 }
3648 // Handle Variables and Typedefs.
3649 SourceLocation DeclLoc = ND->getLocation();
3650 QualType DeclT;
3651 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3652 DeclT = VD->getType();
3653 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3654 DeclT = TDD->getUnderlyingType();
3655 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3656 DeclT = FD->getType();
3657 else
3658 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3659
3660 const char *startBuf = SM->getCharacterData(DeclLoc);
3661 const char *endBuf = startBuf;
3662 // scan backward (from the decl location) for the end of the previous decl.
3663 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3664 startBuf--;
3665
3666 // *startBuf != '^' if we are dealing with a pointer to function that
3667 // may take block argument types (which will be handled below).
3668 if (*startBuf == '^') {
3669 // Replace the '^' with '*', computing a negative offset.
3670 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3671 ReplaceText(DeclLoc, 1, "*", 1);
3672 }
3673 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3674 // Replace the '^' with '*' for arguments.
3675 DeclLoc = ND->getLocation();
3676 startBuf = SM->getCharacterData(DeclLoc);
3677 const char *argListBegin, *argListEnd;
3678 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3679 while (argListBegin < argListEnd) {
3680 if (*argListBegin == '^') {
3681 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3682 ReplaceText(CaretLoc, 1, "*", 1);
3683 }
3684 argListBegin++;
3685 }
3686 }
3687 return;
3688}
3689
3690void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3691 // Add initializers for any closure decl refs.
3692 GetBlockDeclRefExprs(Exp->getBody());
3693 if (BlockDeclRefs.size()) {
3694 // Unique all "by copy" declarations.
3695 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3696 if (!BlockDeclRefs[i]->isByRef())
3697 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3698 // Unique all "by ref" declarations.
3699 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3700 if (BlockDeclRefs[i]->isByRef()) {
3701 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3702 }
3703 // Find any imported blocks...they will need special attention.
3704 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3705 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
3706 GetBlockCallExprs(Blocks[i]);
3707 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3708 }
3709 }
3710}
3711
Steve Narofffa15fd92008-10-28 20:29:00 +00003712FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3713 IdentifierInfo *ID = &Context->Idents.get(name);
3714 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3715 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3716 ID, FType, FunctionDecl::Extern, false, 0);
3717}
3718
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003719Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003720 Blocks.push_back(Exp);
3721
3722 CollectBlockDeclRefInfo(Exp);
3723 std::string FuncName;
3724
3725 if (CurFunctionDef)
3726 FuncName = std::string(CurFunctionDef->getName());
3727 else if (CurMethodDef) {
3728 FuncName = std::string(CurMethodDef->getSelector().getName());
3729 // Convert colons to underscores.
3730 std::string::size_type loc = 0;
3731 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3732 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003733 } else if (GlobalVarDecl)
3734 FuncName = std::string(GlobalVarDecl->getName());
Steve Narofffa15fd92008-10-28 20:29:00 +00003735
3736 std::string BlockNumber = utostr(Blocks.size()-1);
3737
3738 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3739 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3740
3741 // Get a pointer to the function type so we can cast appropriately.
3742 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3743
3744 FunctionDecl *FD;
3745 Expr *NewRep;
3746
3747 // Simulate a contructor call...
3748 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3749 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3750
3751 llvm::SmallVector<Expr*, 4> InitExprs;
3752
3753 FD = SynthBlockInitFunctionDecl(Func.c_str());
3754 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3755 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
3756 Context->VoidPtrTy, SourceLocation());
3757 InitExprs.push_back(castExpr);
3758#if 0
3759 // Initialize the block function.
3760 Init += "((void*)" + Func;
3761
3762 if (ImportedBlockDecls.size()) {
3763 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
3764 Init += ",(void*)" + Buf;
3765 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
3766 Init += ",(void*)" + Buf;
3767 }
3768 // Add initializers for any closure decl refs.
3769 if (BlockDeclRefs.size()) {
3770 // Output all "by copy" declarations.
3771 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3772 E = BlockByCopyDecls.end(); I != E; ++I) {
3773 Init += ",";
3774 if (isObjCType((*I)->getType())) {
3775 Init += "[[";
3776 Init += (*I)->getName();
3777 Init += " retain] autorelease]";
3778 } else if (isBlockPointerType((*I)->getType())) {
3779 Init += "(void *)";
3780 Init += (*I)->getName();
3781 } else {
3782 Init += (*I)->getName();
3783 }
3784 }
3785 // Output all "by ref" declarations.
3786 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3787 E = BlockByRefDecls.end(); I != E; ++I) {
3788 Init += ",&";
3789 Init += (*I)->getName();
3790 }
3791 }
3792 Init += ")";
3793#endif
3794 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3795 FType, SourceLocation());
3796 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3797 Context->getPointerType(NewRep->getType()),
3798 SourceLocation());
3799 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation());
3800 BlockDeclRefs.clear();
3801 BlockByRefDecls.clear();
3802 BlockByCopyDecls.clear();
3803 ImportedBlockDecls.clear();
3804 return NewRep;
3805}
3806
3807//===----------------------------------------------------------------------===//
3808// Function Body / Expression rewriting
3809//===----------------------------------------------------------------------===//
3810
3811Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3812 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3813 isa<DoStmt>(S) || isa<ForStmt>(S))
3814 Stmts.push_back(S);
3815 else if (isa<ObjCForCollectionStmt>(S)) {
3816 Stmts.push_back(S);
3817 ObjCBcLabelNo.push_back(++BcLabelCount);
3818 }
3819
3820 SourceRange OrigStmtRange = S->getSourceRange();
3821
3822 // Perform a bottom up rewrite of all children.
3823 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3824 CI != E; ++CI)
3825 if (*CI) {
3826 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3827 if (newStmt)
3828 *CI = newStmt;
3829 }
3830
3831 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
3832 // Rewrite the block body in place.
3833 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
3834
3835 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003836 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
3837 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00003838
3839 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
3840 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003841 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00003842 return blockTranscribed;
3843 }
3844 // Handle specific things.
3845 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
3846 return RewriteAtEncode(AtEncode);
3847
3848 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
3849 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
3850
3851 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
3852 return RewriteAtSelector(AtSelector);
3853
3854 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
3855 return RewriteObjCStringLiteral(AtString);
3856
3857 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
3858 // Before we rewrite it, put the original message expression in a comment.
3859 SourceLocation startLoc = MessExpr->getLocStart();
3860 SourceLocation endLoc = MessExpr->getLocEnd();
3861
3862 const char *startBuf = SM->getCharacterData(startLoc);
3863 const char *endBuf = SM->getCharacterData(endLoc);
3864
3865 std::string messString;
3866 messString += "// ";
3867 messString.append(startBuf, endBuf-startBuf+1);
3868 messString += "\n";
3869
3870 // FIXME: Missing definition of
3871 // InsertText(clang::SourceLocation, char const*, unsigned int).
3872 // InsertText(startLoc, messString.c_str(), messString.size());
3873 // Tried this, but it didn't work either...
3874 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
3875 return RewriteMessageExpr(MessExpr);
3876 }
3877
3878 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
3879 return RewriteObjCTryStmt(StmtTry);
3880
3881 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
3882 return RewriteObjCSynchronizedStmt(StmtTry);
3883
3884 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
3885 return RewriteObjCThrowStmt(StmtThrow);
3886
3887 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
3888 return RewriteObjCProtocolExpr(ProtocolExp);
3889
3890 if (ObjCForCollectionStmt *StmtForCollection =
3891 dyn_cast<ObjCForCollectionStmt>(S))
3892 return RewriteObjCForCollectionStmt(StmtForCollection,
3893 OrigStmtRange.getEnd());
3894 if (BreakStmt *StmtBreakStmt =
3895 dyn_cast<BreakStmt>(S))
3896 return RewriteBreakStmt(StmtBreakStmt);
3897 if (ContinueStmt *StmtContinueStmt =
3898 dyn_cast<ContinueStmt>(S))
3899 return RewriteContinueStmt(StmtContinueStmt);
3900
3901 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
3902 // and cast exprs.
3903 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
3904 // FIXME: What we're doing here is modifying the type-specifier that
3905 // precedes the first Decl. In the future the DeclGroup should have
3906 // a separate type-specifier that we can rewrite.
3907 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
3908
3909 // Blocks rewrite rules.
3910 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
3911 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003912 ScopedDecl *SD = *DI;
3913 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
3914 if (isBlockPointerType(ND->getType()))
3915 RewriteBlockPointerDecl(ND);
3916 else if (ND->getType()->isFunctionPointerType())
3917 CheckFunctionPointerDecl(ND->getType(), ND);
3918 }
3919 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
3920 if (isBlockPointerType(TD->getUnderlyingType()))
3921 RewriteBlockPointerDecl(TD);
3922 else if (TD->getUnderlyingType()->isFunctionPointerType())
3923 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
3924 }
3925 }
3926 }
3927
3928 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
3929 RewriteObjCQualifiedInterfaceTypes(CE);
3930
3931 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3932 isa<DoStmt>(S) || isa<ForStmt>(S)) {
3933 assert(!Stmts.empty() && "Statement stack is empty");
3934 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
3935 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
3936 && "Statement stack mismatch");
3937 Stmts.pop_back();
3938 }
3939 // Handle blocks rewriting.
3940 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3941 if (BDRE->isByRef())
3942 RewriteBlockDeclRefExpr(BDRE);
3943 }
3944 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3945 if (CE->getCallee()->getType()->isBlockPointerType())
3946 RewriteBlockCall(CE);
3947 }
3948 if (CastExpr *CE = dyn_cast<CastExpr>(S)) {
3949 RewriteCastExpr(CE);
3950 }
3951#if 0
3952 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
3953 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
3954 // Get the new text.
3955 std::string SStr;
3956 llvm::raw_string_ostream Buf(SStr);
3957 Replacement->printPretty(Buf);
3958 const std::string &Str = Buf.str();
3959
3960 printf("CAST = %s\n", &Str[0]);
3961 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
3962 delete S;
3963 return Replacement;
3964 }
3965#endif
3966 // Return this stmt unmodified.
3967 return S;
3968}
3969
3970/// HandleDeclInMainFile - This is called for each top-level decl defined in the
3971/// main file of the input.
3972void RewriteObjC::HandleDeclInMainFile(Decl *D) {
3973 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3974 // Since function prototypes don't have ParmDecl's, we check the function
3975 // prototype. This enables us to rewrite function declarations and
3976 // definitions using the same code.
3977 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
3978
3979 if (Stmt *Body = FD->getBody()) {
3980 CurFunctionDef = FD;
3981 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
3982 // This synthesizes and inserts the block "impl" struct, invoke function,
3983 // and any copy/dispose helper functions.
3984 InsertBlockLiteralsWithinFunction(FD);
3985 CurFunctionDef = 0;
3986 }
3987 return;
3988 }
3989 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3990 if (Stmt *Body = MD->getBody()) {
3991 //Body->dump();
3992 CurMethodDef = MD;
3993 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
3994 InsertBlockLiteralsWithinMethod(MD);
3995 CurMethodDef = 0;
3996 }
3997 }
3998 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
3999 ClassImplementation.push_back(CI);
4000 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4001 CategoryImplementation.push_back(CI);
4002 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4003 RewriteForwardClassDecl(CD);
4004 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4005 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004006 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004007 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004008 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004009 CheckFunctionPointerDecl(VD->getType(), VD);
4010 if (VD->getInit()) {
4011 if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
4012 RewriteCastExpr(CE);
4013 }
4014 }
4015 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004016 if (VD->getInit()) {
4017 GlobalVarDecl = VD;
4018 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4019 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4020 GlobalVarDecl = 0;
4021
4022 // This is needed for blocks.
4023 if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
4024 RewriteCastExpr(CE);
4025 }
4026 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004027 return;
4028 }
4029 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4030 if (isBlockPointerType(TD->getUnderlyingType()))
4031 RewriteBlockPointerDecl(TD);
4032 else if (TD->getUnderlyingType()->isFunctionPointerType())
4033 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4034 return;
4035 }
4036 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4037 if (RD->isDefinition()) {
4038 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4039 e = RD->field_end(); i != e; ++i) {
4040 FieldDecl *FD = *i;
4041 if (isBlockPointerType(FD->getType()))
4042 RewriteBlockPointerDecl(FD);
4043 }
4044 }
4045 return;
4046 }
4047 // Nothing yet.
4048}
4049
4050void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4051 // Get the top-level buffer that this corresponds to.
4052
4053 // Rewrite tabs if we care.
4054 //RewriteTabs();
4055
4056 if (Diags.hasErrorOccurred())
4057 return;
4058
4059 // Create the output file.
4060
4061 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4062 llvm::raw_ostream *OutFile;
4063 if (OutFileName == "-") {
4064 OutFile = &llvm::outs();
4065 } else if (!OutFileName.empty()) {
4066 std::string Err;
4067 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), Err);
4068 OwnedStream.reset(OutFile);
4069 } else if (InFileName == "-") {
4070 OutFile = &llvm::outs();
4071 } else {
4072 llvm::sys::Path Path(InFileName);
4073 Path.eraseSuffix();
4074 Path.appendSuffix("cpp");
4075 std::string Err;
4076 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), Err);
4077 OwnedStream.reset(OutFile);
4078 }
4079
4080 RewriteInclude();
4081
4082 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4083 Preamble.c_str(), Preamble.size(), false);
4084
4085 // Rewrite Objective-c meta data*
4086 std::string ResultStr;
4087 RewriteImplementations(ResultStr);
4088
4089 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4090 // we are done.
4091 if (const RewriteBuffer *RewriteBuf =
4092 Rewrite.getRewriteBufferFor(MainFileID)) {
4093 //printf("Changed:\n");
4094 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4095 } else {
4096 fprintf(stderr, "No changes\n");
4097 }
4098 // Emit metadata.
4099 *OutFile << ResultStr;
4100 OutFile->flush();
4101}
4102