blob: c4f67627ceccc7d8b6a7574ac22a199c4ec50540 [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"
Steve Naroff8599e7a2008-12-08 16:43:47 +000019#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000020#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000021#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000022#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000023#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000024#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000025#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000026#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000027#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000028#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000029#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000031#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000032using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000033using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034
Steve Naroff0113c9d2008-01-28 21:34:52 +000035static llvm::cl::opt<bool>
36SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
37 llvm::cl::desc("Silence ObjC rewriting warnings"));
38
Chris Lattner77cd2a02007-10-11 00:43:27 +000039namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000040 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000041 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000042 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000043 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000044 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000045 unsigned TryFinallyContainsReturnDiag;
46
Chris Lattner01c57482007-10-17 22:35:30 +000047 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000048 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000049 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000050 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000051 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000052 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000053
Ted Kremeneka526c5c2008-01-07 19:49:32 +000054 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
55 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
56 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000057 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000058 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
59 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000060 llvm::SmallVector<Stmt *, 32> Stmts;
61 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000062
Steve Naroffd82a9ab2008-03-15 00:55:56 +000063 unsigned NumObjCStringLiterals;
64
Steve Naroffebf2b562007-10-23 23:50:29 +000065 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000066 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000067 FunctionDecl *MsgSendStretFunctionDecl;
68 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000069 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000070 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000071 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000072 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000073 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000074 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000075 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000076
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000078 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000079 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000080
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000081 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000082 int BcLabelCount;
83
Steve Naroff874e2322007-11-15 10:28:18 +000084 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000085 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000086 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000087 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000088
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000089 // Needed for header files being rewritten
90 bool IsHeader;
91
Steve Naroffa7b402d2008-03-28 22:26:09 +000092 std::string InFileName;
93 std::string OutFileName;
94
Steve Naroffba92b2e2008-03-27 22:29:16 +000095 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000096
97 // Block expressions.
98 llvm::SmallVector<BlockExpr *, 32> Blocks;
99 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
100 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +0000101
Steve Naroff54055232008-10-27 17:20:55 +0000102 // Block related declarations.
103 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
104 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
105 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
106
107 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
108
Steve Naroffc77a6362008-12-04 16:24:46 +0000109 // This maps a property to it's assignment statement.
110 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000111 // This maps a property to it's synthesied message expression.
112 // This allows us to rewrite chained getters (e.g. o.a.b.c).
113 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
114
Steve Naroff4c3580e2008-12-04 23:50:32 +0000115 // This maps an original source AST to it's rewritten form. This allows
116 // us to avoid rewriting the same node twice (which is very uncommon).
117 // This is needed to support some of the exotic property rewriting.
118 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000119
Steve Naroff54055232008-10-27 17:20:55 +0000120 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000121 VarDecl *GlobalVarDecl;
122
Steve Naroffb619d952008-12-09 12:56:34 +0000123 bool DisableReplaceStmt;
124
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000125 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000126 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000127 virtual void Initialize(ASTContext &context);
128
129 virtual void InitializeTU(TranslationUnit &TU) {
130 TU.SetOwnsDecls(false);
131 Initialize(TU.getContext());
132 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000133
Chris Lattner8a12c272007-10-11 18:38:32 +0000134
Chris Lattnerf04da132007-10-24 17:06:59 +0000135 // Top Level Driver code.
136 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000137 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000138 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000139 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000140
141 ~RewriteObjC() {}
142
143 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000144
145 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000146 Stmt *ReplacingStmt = ReplacedNodes[Old];
147
148 if (ReplacingStmt)
149 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000150
Steve Naroffb619d952008-12-09 12:56:34 +0000151 if (DisableReplaceStmt)
152 return; // Used when rewriting the assignment of a property setter.
153
Steve Naroff4c3580e2008-12-04 23:50:32 +0000154 // If replacement succeeded or warning disabled return with no warning.
155 if (!Rewrite.ReplaceStmt(Old, New)) {
156 ReplacedNodes[Old] = New;
157 return;
158 }
159 if (SilenceRewriteMacroWarning)
160 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000161 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
162 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000163 }
Steve Naroffb619d952008-12-09 12:56:34 +0000164
165 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
166 // Measaure the old text.
167 int Size = Rewrite.getRangeSize(SrcRange);
168 if (Size == -1) {
169 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
170 << Old->getSourceRange();
171 return;
172 }
173 // Get the new text.
174 std::string SStr;
175 llvm::raw_string_ostream S(SStr);
176 New->printPretty(S);
177 const std::string &Str = S.str();
178
179 // If replacement succeeded or warning disabled return with no warning.
180 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
188 }
189
Steve Naroffba92b2e2008-03-27 22:29:16 +0000190 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
191 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000192 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000193 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000194 SilenceRewriteMacroWarning)
195 return;
196
197 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
198 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000199
Chris Lattneraadaf782008-01-31 19:51:04 +0000200 void RemoveText(SourceLocation Loc, unsigned StrLen) {
201 // If removal succeeded or warning disabled return with no warning.
202 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
203 return;
204
205 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
206 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000207
Chris Lattneraadaf782008-01-31 19:51:04 +0000208 void ReplaceText(SourceLocation Start, unsigned OrigLength,
209 const char *NewStr, unsigned NewLength) {
210 // If removal succeeded or warning disabled return with no warning.
211 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
212 SilenceRewriteMacroWarning)
213 return;
214
215 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
216 }
217
Chris Lattnerf04da132007-10-24 17:06:59 +0000218 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000219 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000220 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000221 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000222 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000223 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
224 ObjCImplementationDecl *IMD,
225 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000227 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000228 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
229 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
230 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
231 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
232 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000233 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000234 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000235 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000236 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000237 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000238 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000239 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000240 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000241 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000242
Chris Lattnerf04da132007-10-24 17:06:59 +0000243 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000244 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000245 void CollectPropertySetters(Stmt *S);
246
Steve Naroff8599e7a2008-12-08 16:43:47 +0000247 Stmt *CurrentBody;
248 ParentMap *PropParentMap; // created lazily.
249
Chris Lattnere64b7772007-10-24 16:57:36 +0000250 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000251 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000252 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffb619d952008-12-09 12:56:34 +0000253 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
254 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000255 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000256 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000257 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000258 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000259 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000261 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000262 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
263 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
264 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000265 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
266 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000267 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
268 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000269 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000270 Stmt *RewriteBreakStmt(BreakStmt *S);
271 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000272 void SynthCountByEnumWithState(std::string &buf);
273
Steve Naroff09b266e2007-10-30 23:14:51 +0000274 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000275 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000276 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000277 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000278 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000279 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000280 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000281 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000282 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000283 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000284
Chris Lattnerf04da132007-10-24 17:06:59 +0000285 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000287 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000288
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000290 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000291
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000292 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
293 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000294 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000295 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000296 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000297 const char *ClassName,
298 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000299
Chris Lattner780f3292008-07-21 21:32:27 +0000300 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
301 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000302 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000303 const char *ClassName,
304 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000306 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
308 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000309 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000310 void RewriteImplementations();
311 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000312
313 // Block rewriting.
Douglas Gregor72564e72009-02-26 23:50:07 +0000314 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000315 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
316
317 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
318 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
319
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000320 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000321 void RewriteBlockCall(CallExpr *Exp);
322 void RewriteBlockPointerDecl(NamedDecl *VD);
323 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
324 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
325
326 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
327 const char *funcName, std::string Tag);
328 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
329 const char *funcName, std::string Tag);
330 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
331 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000332 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000333 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
334 const char *FunName);
335
336 void CollectBlockDeclRefInfo(BlockExpr *Exp);
337 void GetBlockCallExprs(Stmt *S);
338 void GetBlockDeclRefExprs(Stmt *S);
339
340 // We avoid calling Type::isBlockPointerType(), since it operates on the
341 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000342 bool isTopLevelBlockPointerType(QualType T) {
343 return isa<BlockPointerType>(T);
344 }
Steve Naroff54055232008-10-27 17:20:55 +0000345
346 // FIXME: This predicate seems like it would be useful to add to ASTContext.
347 bool isObjCType(QualType T) {
348 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
349 return false;
350
351 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
352
353 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
354 OCT == Context->getCanonicalType(Context->getObjCClassType()))
355 return true;
356
357 if (const PointerType *PT = OCT->getAsPointerType()) {
358 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
359 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
360 return true;
361 }
362 return false;
363 }
364 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000365 void GetExtentOfArgList(const char *Name, const char *&LParen,
366 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000367 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000368
369 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000370 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000371 };
372}
373
Douglas Gregor72564e72009-02-26 23:50:07 +0000374void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
Steve Naroff54055232008-10-27 17:20:55 +0000375 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000376 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
377 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000378 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000379 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000380 // All the args are checked/rewritten. Don't call twice!
381 RewriteBlockPointerDecl(D);
382 break;
383 }
384 }
385}
386
387void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
388 const PointerType *PT = funcType->getAsPointerType();
389 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000390 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000391}
392
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000393static bool IsHeaderFile(const std::string &Filename) {
394 std::string::size_type DotPos = Filename.rfind('.');
395
396 if (DotPos == std::string::npos) {
397 // no file extension
398 return false;
399 }
400
401 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
402 // C header: .h
403 // C++ header: .hh or .H;
404 return Ext == "h" || Ext == "hh" || Ext == "H";
405}
406
Steve Naroffb29b4272008-04-14 22:03:09 +0000407RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000408 Diagnostic &D, const LangOptions &LOpts)
409 : Diags(D), LangOpts(LOpts) {
410 IsHeader = IsHeaderFile(inFile);
411 InFileName = inFile;
412 OutFileName = outFile;
413 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
414 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000415 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000416 "rewriter doesn't support user-specified control flow semantics "
417 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000418}
419
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000420ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000421 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000422 Diagnostic &Diags,
423 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000424 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000425}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000426
Steve Naroffb29b4272008-04-14 22:03:09 +0000427void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000428 Context = &context;
429 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000430 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000431 MsgSendFunctionDecl = 0;
432 MsgSendSuperFunctionDecl = 0;
433 MsgSendStretFunctionDecl = 0;
434 MsgSendSuperStretFunctionDecl = 0;
435 MsgSendFpretFunctionDecl = 0;
436 GetClassFunctionDecl = 0;
437 GetMetaClassFunctionDecl = 0;
438 SelGetUidFunctionDecl = 0;
439 CFStringFunctionDecl = 0;
440 GetProtocolFunctionDecl = 0;
441 ConstantStringClassReference = 0;
442 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000443 CurMethodDef = 0;
444 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000445 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000446 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000447 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000448 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000449 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000450 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000451 PropParentMap = 0;
452 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000453 DisableReplaceStmt = false;
454
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000455 // Get the ID and start/end of the main file.
456 MainFileID = SM->getMainFileID();
457 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
458 MainFileStart = MainBuf->getBufferStart();
459 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000460
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000461 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000462
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000463 // declaring objc_selector outside the parameter list removes a silly
464 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000465 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000466 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000467 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000468 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000469 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000470 if (LangOpts.Microsoft) {
471 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000472 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
473 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000474 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000475 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000476 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000477 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
478 Preamble += "typedef struct objc_object Protocol;\n";
479 Preamble += "#define _REWRITER_typedef_Protocol\n";
480 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000481 if (LangOpts.Microsoft) {
482 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
483 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
484 } else
485 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
486 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000487 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000488 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000489 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000490 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000491 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000492 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000493 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000494 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000495 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000496 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000497 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000498 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000499 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000500 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
501 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
502 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
503 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
504 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000505 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000506 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000507 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
508 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
509 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000510 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
511 Preamble += "struct __objcFastEnumerationState {\n\t";
512 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000513 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000514 Preamble += "unsigned long *mutationsPtr;\n\t";
515 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000516 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000517 Preamble += "#define __FASTENUMERATIONSTATE\n";
518 Preamble += "#endif\n";
519 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
520 Preamble += "struct __NSConstantStringImpl {\n";
521 Preamble += " int *isa;\n";
522 Preamble += " int flags;\n";
523 Preamble += " char *str;\n";
524 Preamble += " long length;\n";
525 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000526 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
527 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
528 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000529 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000530 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000531 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
532 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000533 // Blocks preamble.
534 Preamble += "#ifndef BLOCK_IMPL\n";
535 Preamble += "#define BLOCK_IMPL\n";
536 Preamble += "struct __block_impl {\n";
537 Preamble += " void *isa;\n";
538 Preamble += " int Flags;\n";
539 Preamble += " int Size;\n";
540 Preamble += " void *FuncPtr;\n";
541 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000542 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
543 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
544 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
545 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
546 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff54055232008-10-27 17:20:55 +0000547 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000548 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000549 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
550 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000551 Preamble += "#define __attribute__(X)\n";
552 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000553}
554
555
Chris Lattnerf04da132007-10-24 17:06:59 +0000556//===----------------------------------------------------------------------===//
557// Top Level Driver Code
558//===----------------------------------------------------------------------===//
559
Steve Naroffb29b4272008-04-14 22:03:09 +0000560void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000561 // Two cases: either the decl could be in the main file, or it could be in a
562 // #included file. If the former, rewrite it now. If the later, check to see
563 // if we rewrote the #include/#import.
564 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000565 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000566
567 // If this is for a builtin, ignore it.
568 if (Loc.isInvalid()) return;
569
Steve Naroffebf2b562007-10-23 23:50:29 +0000570 // Look for built-in declarations that we need to refer during the rewrite.
571 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000572 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000573 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000574 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000575 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000576 ConstantStringClassReference = FVD;
577 return;
578 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000579 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000580 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000581 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000582 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000583 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000584 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000585 } else if (ObjCForwardProtocolDecl *FP =
586 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000587 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000588 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
589 // Recurse into linkage specifications
590 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
591 DIEnd = LSD->decls_end();
592 DI != DIEnd; ++DI)
593 HandleTopLevelDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000594 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000595 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000596 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000597 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000598}
599
Chris Lattnerf04da132007-10-24 17:06:59 +0000600//===----------------------------------------------------------------------===//
601// Syntactic (non-AST) Rewriting Code
602//===----------------------------------------------------------------------===//
603
Steve Naroffb29b4272008-04-14 22:03:09 +0000604void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000605 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000606 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
607 const char *MainBufStart = MainBuf.first;
608 const char *MainBufEnd = MainBuf.second;
609 size_t ImportLen = strlen("import");
610 size_t IncludeLen = strlen("include");
611
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000612 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000613 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
614 if (*BufPtr == '#') {
615 if (++BufPtr == MainBufEnd)
616 return;
617 while (*BufPtr == ' ' || *BufPtr == '\t')
618 if (++BufPtr == MainBufEnd)
619 return;
620 if (!strncmp(BufPtr, "import", ImportLen)) {
621 // replace import with include
622 SourceLocation ImportLoc =
623 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000624 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000625 BufPtr += ImportLen;
626 }
627 }
628 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000629}
630
Steve Naroffb29b4272008-04-14 22:03:09 +0000631void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000632 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
633 const char *MainBufStart = MainBuf.first;
634 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000635
Chris Lattnerf04da132007-10-24 17:06:59 +0000636 // Loop over the whole file, looking for tabs.
637 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
638 if (*BufPtr != '\t')
639 continue;
640
641 // Okay, we found a tab. This tab will turn into at least one character,
642 // but it depends on which 'virtual column' it is in. Compute that now.
643 unsigned VCol = 0;
644 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
645 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
646 ++VCol;
647
648 // Okay, now that we know the virtual column, we know how many spaces to
649 // insert. We assume 8-character tab-stops.
650 unsigned Spaces = 8-(VCol & 7);
651
652 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000653 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
654 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerf04da132007-10-24 17:06:59 +0000655
656 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000657 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000658 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000659}
660
Steve Naroffeb0646c2008-12-02 15:48:25 +0000661static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
662 ObjCIvarDecl *OID) {
663 std::string S;
664 S = "((struct ";
665 S += ClassDecl->getIdentifier()->getName();
666 S += "_IMPL *)self)->";
667 S += OID->getNameAsCString();
668 return S;
669}
670
Steve Naroffa0876e82008-12-02 17:36:43 +0000671void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
672 ObjCImplementationDecl *IMD,
673 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000674 SourceLocation startLoc = PID->getLocStart();
675 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000676 const char *startBuf = SM->getCharacterData(startLoc);
677 assert((*startBuf == '@') && "bogus @synthesize location");
678 const char *semiBuf = strchr(startBuf, ';');
679 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000680 SourceLocation onePastSemiLoc =
681 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000682
683 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
684 return; // FIXME: is this correct?
685
686 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000687 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000688 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000689 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000690
691 if (!OID)
692 return;
693
694 std::string Getr;
695 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
696 Getr += "{ ";
697 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000698 // FIXME: deal with code generation implications for various property
699 // attributes (copy, retain, nonatomic).
700 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000701 Getr += "return " + getIvarAccessString(ClassDecl, OID);
702 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000703 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000704
705 // Add the rewritten getter to trigger meta data generation. An alternate, and
706 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
707 // with properties explicitly. The following addInstanceMethod() required far
708 // less code change (and actually models what the rewriter is doing).
709 if (IMD)
710 IMD->addInstanceMethod(PD->getGetterMethodDecl());
711 else
712 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000713
714 if (PD->isReadOnly())
715 return;
716
717 // Generate the 'setter' function.
718 std::string Setr;
719 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000720 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000721 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000722 // FIXME: deal with code generation implications for various property
723 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000724 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000725 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000726 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000727 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000728 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000729
730 // Add the rewritten setter to trigger meta data generation.
731 if (IMD)
732 IMD->addInstanceMethod(PD->getSetterMethodDecl());
733 else
734 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000735}
Chris Lattner8a12c272007-10-11 18:38:32 +0000736
Steve Naroffb29b4272008-04-14 22:03:09 +0000737void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000738 // Get the start location and compute the semi location.
739 SourceLocation startLoc = ClassDecl->getLocation();
740 const char *startBuf = SM->getCharacterData(startLoc);
741 const char *semiPtr = strchr(startBuf, ';');
742
743 // Translate to typedef's that forward reference structs with the same name
744 // as the class. As a convenience, we include the original declaration
745 // as a comment.
746 std::string typedefString;
747 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000748 typedefString.append(startBuf, semiPtr-startBuf+1);
749 typedefString += "\n";
Chris Lattner67956052009-02-20 18:04:31 +0000750 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
751 I != E; ++I) {
752 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff32174822007-11-09 12:50:28 +0000753 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000754 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000755 typedefString += "\n";
756 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000757 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000758 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000759 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000760 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000761 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000762 }
763
764 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000765 ReplaceText(startLoc, semiPtr-startBuf+1,
766 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000767}
768
Steve Naroffb29b4272008-04-14 22:03:09 +0000769void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000770 SourceLocation LocStart = Method->getLocStart();
771 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000772
Chris Lattner30fc9332009-02-04 01:06:56 +0000773 if (SM->getInstantiationLineNumber(LocEnd) >
774 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000775 InsertText(LocStart, "#if 0\n", 6);
776 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000777 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000778 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000779 }
780}
781
Steve Naroff6327e0d2009-01-11 01:06:09 +0000782void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000783{
Steve Naroff6327e0d2009-01-11 01:06:09 +0000784 SourceLocation Loc = prop->getLocation();
785
786 ReplaceText(Loc, 0, "// ", 3);
787
788 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000789}
790
Steve Naroffb29b4272008-04-14 22:03:09 +0000791void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000792 SourceLocation LocStart = CatDecl->getLocStart();
793
794 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000795 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000796
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000797 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000798 E = CatDecl->instmeth_end(); I != E; ++I)
799 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000800 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000801 E = CatDecl->classmeth_end(); I != E; ++I)
802 RewriteMethodDeclaration(*I);
803
Steve Naroff423cb562007-10-30 13:30:57 +0000804 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000805 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000806}
807
Steve Naroffb29b4272008-04-14 22:03:09 +0000808void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000809 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000810
Steve Naroff752d6ef2007-10-30 16:42:30 +0000811 SourceLocation LocStart = PDecl->getLocStart();
812
813 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000814 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000815
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000816 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000817 E = PDecl->instmeth_end(); I != E; ++I)
818 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000819 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000820 E = PDecl->classmeth_end(); I != E; ++I)
821 RewriteMethodDeclaration(*I);
822
Steve Naroff752d6ef2007-10-30 16:42:30 +0000823 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000824 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000825 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000826
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000827 // Must comment out @optional/@required
828 const char *startBuf = SM->getCharacterData(LocStart);
829 const char *endBuf = SM->getCharacterData(LocEnd);
830 for (const char *p = startBuf; p < endBuf; p++) {
831 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
832 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000833 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000834 ReplaceText(OptionalLoc, strlen("@optional"),
835 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000836
837 }
838 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
839 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000840 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000841 ReplaceText(OptionalLoc, strlen("@required"),
842 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000843
844 }
845 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000846}
847
Steve Naroffb29b4272008-04-14 22:03:09 +0000848void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000849 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000850 if (LocStart.isInvalid())
851 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000852 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000853 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000854}
855
Steve Naroffb29b4272008-04-14 22:03:09 +0000856void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000857 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000858 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000859 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000860 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000861 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000862 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000863 else if (OMD->getResultType()->isFunctionPointerType() ||
864 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000865 // needs special handling, since pointer-to-functions have special
866 // syntax (where a decaration models use).
867 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000868 QualType PointeeTy;
869 if (const PointerType* PT = retType->getAsPointerType())
870 PointeeTy = PT->getPointeeType();
871 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
872 PointeeTy = BPT->getPointeeType();
873 if ((FPRetType = PointeeTy->getAsFunctionType())) {
874 ResultStr += FPRetType->getResultType().getAsString();
875 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000876 }
877 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000878 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000879 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000880
881 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000882 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000883
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000884 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000885 NameStr += "_I_";
886 else
887 NameStr += "_C_";
888
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000889 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000890 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000891
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000892 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000893 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000894 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000895 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000896 }
Steve Naroff563b8282008-04-04 22:23:44 +0000897 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000898 {
899 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000900 int len = selString.size();
901 for (int i = 0; i < len; i++)
902 if (selString[i] == ':')
903 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000904 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000905 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000906 // Remember this name for metadata emission
907 MethodInternalNames[OMD] = NameStr;
908 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000909
910 // Rewrite arguments
911 ResultStr += "(";
912
913 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000914 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000915 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000916 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000917 if (!LangOpts.Microsoft) {
918 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
919 ResultStr += "struct ";
920 }
921 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000922 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000923 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000924 }
925 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000926 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000927
928 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000929 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000930 ResultStr += " _cmd";
931
932 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +0000933 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
934 E = OMD->param_end(); PI != E; ++PI) {
935 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000936 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000937 if (PDecl->getType()->isObjCQualifiedIdType()) {
938 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000939 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000940 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000941 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000942 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000943 // Make sure we convert "t (^)(...)" to "t (*)(...)".
944 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
945 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
946 } else
947 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000948 ResultStr += Name;
949 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000950 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000951 if (OMD->isVariadic())
952 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000953 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000954
Steve Naroff76e429d2008-07-16 14:40:40 +0000955 if (FPRetType) {
956 ResultStr += ")"; // close the precedence "scope" for "*".
957
958 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +0000959 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000960 ResultStr += "(";
961 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
962 if (i) ResultStr += ", ";
963 std::string ParamStr = FT->getArgType(i).getAsString();
964 ResultStr += ParamStr;
965 }
966 if (FT->isVariadic()) {
967 if (FT->getNumArgs()) ResultStr += ", ";
968 ResultStr += "...";
969 }
970 ResultStr += ")";
971 } else {
972 ResultStr += "()";
973 }
974 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000975}
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000976void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000977 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
978 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000979
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000980 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000981 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000982 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000983 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000984
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000985 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000986 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
987 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000988 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000989 ObjCMethodDecl *OMD = *I;
990 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000991 SourceLocation LocStart = OMD->getLocStart();
992 SourceLocation LocEnd = OMD->getBody()->getLocStart();
993
994 const char *startBuf = SM->getCharacterData(LocStart);
995 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000996 ReplaceText(LocStart, endBuf-startBuf,
997 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000998 }
999
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001000 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001001 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1002 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001003 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001004 ObjCMethodDecl *OMD = *I;
1005 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001006 SourceLocation LocStart = OMD->getLocStart();
1007 SourceLocation LocEnd = OMD->getBody()->getLocStart();
1008
1009 const char *startBuf = SM->getCharacterData(LocStart);
1010 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001011 ReplaceText(LocStart, endBuf-startBuf,
1012 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001013 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001014 for (ObjCCategoryImplDecl::propimpl_iterator
1015 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1016 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001017 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001018 }
1019
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001020 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001021 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001022 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001023 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001024}
1025
Steve Naroffb29b4272008-04-14 22:03:09 +00001026void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001027 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001028 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001029 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001030 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001031 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001032 ResultStr += "\n";
1033 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001034 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001035 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001036 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001037 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001038 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001039 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001040 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001041 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001042 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001043
Steve Naroff6327e0d2009-01-11 01:06:09 +00001044 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1045 E = ClassDecl->prop_end(); I != E; ++I)
1046 RewriteProperty(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001047 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001048 E = ClassDecl->instmeth_end(); I != E; ++I)
1049 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001050 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001051 E = ClassDecl->classmeth_end(); I != E; ++I)
1052 RewriteMethodDeclaration(*I);
1053
Steve Naroff2feac5e2007-10-30 03:43:13 +00001054 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001055 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001056}
1057
Steve Naroffb619d952008-12-09 12:56:34 +00001058Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1059 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001060 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1061 // This allows us to reuse all the fun and games in SynthMessageExpr().
1062 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1063 ObjCMessageExpr *MsgExpr;
1064 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1065 llvm::SmallVector<Expr *, 1> ExprVec;
1066 ExprVec.push_back(newStmt);
1067
Steve Naroff8599e7a2008-12-08 16:43:47 +00001068 Stmt *Receiver = PropRefExpr->getBase();
1069 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1070 if (PRE && PropGetters[PRE]) {
1071 // This allows us to handle chain/nested property getters.
1072 Receiver = PropGetters[PRE];
1073 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001074 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001075 PDecl->getSetterName(), PDecl->getType(),
1076 PDecl->getSetterMethodDecl(),
1077 SourceLocation(), SourceLocation(),
1078 &ExprVec[0], 1);
1079 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1080
1081 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001082 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001083 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001084 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1085 // to things that stay around.
1086 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001087 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001088}
1089
Steve Naroffc77a6362008-12-04 16:24:46 +00001090Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001091 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1092 // This allows us to reuse all the fun and games in SynthMessageExpr().
1093 ObjCMessageExpr *MsgExpr;
1094 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1095
Steve Naroff8599e7a2008-12-08 16:43:47 +00001096 Stmt *Receiver = PropRefExpr->getBase();
1097
1098 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1099 if (PRE && PropGetters[PRE]) {
1100 // This allows us to handle chain/nested property getters.
1101 Receiver = PropGetters[PRE];
1102 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001103 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001104 PDecl->getGetterName(), PDecl->getType(),
1105 PDecl->getGetterMethodDecl(),
1106 SourceLocation(), SourceLocation(),
1107 0, 0);
1108
Steve Naroff4c3580e2008-12-04 23:50:32 +00001109 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001110
1111 if (!PropParentMap)
1112 PropParentMap = new ParentMap(CurrentBody);
1113
1114 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1115 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1116 // We stash away the ReplacingStmt since actually doing the
1117 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1118 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001119 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1120 // to things that stay around.
1121 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001122 return PropRefExpr; // return the original...
1123 } else {
1124 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001125 // delete PropRefExpr; elsewhere...
1126 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1127 // to things that stay around.
1128 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001129 return ReplacingStmt;
1130 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001131}
1132
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001133Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1134 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001135 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001136 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001137 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001138 ObjCInterfaceType *iFaceDecl =
1139 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001140 // lookup which class implements the instance variable.
1141 ObjCInterfaceDecl *clsDeclared = 0;
1142 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1143 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1144
1145 // Synthesize an explicit cast to gain access to the ivar.
1146 std::string RecName = clsDeclared->getIdentifier()->getName();
1147 RecName += "_IMPL";
1148 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001149 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001150 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001151 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1152 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001153 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1154 castT,SourceLocation(),
1155 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001156 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001157 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1158 IV->getBase()->getLocEnd(),
1159 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001160 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001161 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001162 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1163 IV->getLocation(),
1164 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001165 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001166 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001167 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001168 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001169
1170 ReplaceStmt(IV->getBase(), PE);
1171 // Cannot delete IV->getBase(), since PE points to it.
1172 // Replace the old base with the cast. This is important when doing
1173 // embedded rewrites. For example, [newInv->_container addObject:0].
1174 IV->setBase(PE);
1175 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001176 }
Steve Naroff84472a82008-04-18 21:55:08 +00001177 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001178 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1179
1180 // Explicit ivar refs need to have a cast inserted.
1181 // FIXME: consider sharing some of this code with the code above.
1182 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001183 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001184 // lookup which class implements the instance variable.
1185 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001186 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001187 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1188
1189 // Synthesize an explicit cast to gain access to the ivar.
1190 std::string RecName = clsDeclared->getIdentifier()->getName();
1191 RecName += "_IMPL";
1192 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001193 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001194 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001195 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1196 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001197 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1198 castT, SourceLocation(),
1199 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001200 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001201 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001202 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001203 ReplaceStmt(IV->getBase(), PE);
1204 // Cannot delete IV->getBase(), since PE points to it.
1205 // Replace the old base with the cast. This is important when doing
1206 // embedded rewrites. For example, [newInv->_container addObject:0].
1207 IV->setBase(PE);
1208 return IV;
1209 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001210 }
Steve Naroff84472a82008-04-18 21:55:08 +00001211 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001212}
1213
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001214/// SynthCountByEnumWithState - To print:
1215/// ((unsigned int (*)
1216/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1217/// (void *)objc_msgSend)((id)l_collection,
1218/// sel_registerName(
1219/// "countByEnumeratingWithState:objects:count:"),
1220/// &enumState,
1221/// (id *)items, (unsigned int)16)
1222///
Steve Naroffb29b4272008-04-14 22:03:09 +00001223void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001224 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1225 "id *, unsigned int))(void *)objc_msgSend)";
1226 buf += "\n\t\t";
1227 buf += "((id)l_collection,\n\t\t";
1228 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1229 buf += "\n\t\t";
1230 buf += "&enumState, "
1231 "(id *)items, (unsigned int)16)";
1232}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001233
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001234/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1235/// statement to exit to its outer synthesized loop.
1236///
Steve Naroffb29b4272008-04-14 22:03:09 +00001237Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001238 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1239 return S;
1240 // replace break with goto __break_label
1241 std::string buf;
1242
1243 SourceLocation startLoc = S->getLocStart();
1244 buf = "goto __break_label_";
1245 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001246 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001247
1248 return 0;
1249}
1250
1251/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1252/// statement to continue with its inner synthesized loop.
1253///
Steve Naroffb29b4272008-04-14 22:03:09 +00001254Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001255 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1256 return S;
1257 // replace continue with goto __continue_label
1258 std::string buf;
1259
1260 SourceLocation startLoc = S->getLocStart();
1261 buf = "goto __continue_label_";
1262 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001263 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001264
1265 return 0;
1266}
1267
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001268/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001269/// It rewrites:
1270/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001271
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001272/// Into:
1273/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001274/// type elem;
1275/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001276/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001277/// id l_collection = (id)collection;
1278/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1279/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001280/// if (limit) {
1281/// unsigned long startMutations = *enumState.mutationsPtr;
1282/// do {
1283/// unsigned long counter = 0;
1284/// do {
1285/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001286/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001287/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001288/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001289/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001290/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001291/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1292/// objects:items count:16]);
1293/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001294/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001295/// }
1296/// else
1297/// elem = nil;
1298/// }
1299///
Steve Naroffb29b4272008-04-14 22:03:09 +00001300Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001301 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001302 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1303 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1304 "ObjCForCollectionStmt Statement stack mismatch");
1305 assert(!ObjCBcLabelNo.empty() &&
1306 "ObjCForCollectionStmt - Label No stack empty");
1307
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001308 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001309 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001310 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001311 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001312 std::string buf;
1313 buf = "\n{\n\t";
1314 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1315 // type elem;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001316 NamedDecl* D = cast<NamedDecl>(DS->getSolitaryDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001317 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001318 elementTypeAsString = ElementType.getAsString();
1319 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001320 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001321 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001322 buf += elementName;
1323 buf += ";\n\t";
1324 }
Chris Lattner06767512008-04-08 05:52:18 +00001325 else {
1326 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001327 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001328 elementTypeAsString
1329 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001330 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001331
1332 // struct __objcFastEnumerationState enumState = { 0 };
1333 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1334 // id items[16];
1335 buf += "id items[16];\n\t";
1336 // id l_collection = (id)
1337 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001338 // Find start location of 'collection' the hard way!
1339 const char *startCollectionBuf = startBuf;
1340 startCollectionBuf += 3; // skip 'for'
1341 startCollectionBuf = strchr(startCollectionBuf, '(');
1342 startCollectionBuf++; // skip '('
1343 // find 'in' and skip it.
1344 while (*startCollectionBuf != ' ' ||
1345 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1346 (*(startCollectionBuf+3) != ' ' &&
1347 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1348 startCollectionBuf++;
1349 startCollectionBuf += 3;
1350
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001351 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001352 ReplaceText(startLoc, startCollectionBuf - startBuf,
1353 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001354 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001355 SourceLocation rightParenLoc = S->getRParenLoc();
1356 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1357 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001358 buf = ";\n\t";
1359
1360 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1361 // objects:items count:16];
1362 // which is synthesized into:
1363 // unsigned int limit =
1364 // ((unsigned int (*)
1365 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1366 // (void *)objc_msgSend)((id)l_collection,
1367 // sel_registerName(
1368 // "countByEnumeratingWithState:objects:count:"),
1369 // (struct __objcFastEnumerationState *)&state,
1370 // (id *)items, (unsigned int)16);
1371 buf += "unsigned long limit =\n\t\t";
1372 SynthCountByEnumWithState(buf);
1373 buf += ";\n\t";
1374 /// if (limit) {
1375 /// unsigned long startMutations = *enumState.mutationsPtr;
1376 /// do {
1377 /// unsigned long counter = 0;
1378 /// do {
1379 /// if (startMutations != *enumState.mutationsPtr)
1380 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001381 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001382 buf += "if (limit) {\n\t";
1383 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1384 buf += "do {\n\t\t";
1385 buf += "unsigned long counter = 0;\n\t\t";
1386 buf += "do {\n\t\t\t";
1387 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1388 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1389 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001390 buf += " = (";
1391 buf += elementTypeAsString;
1392 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001393 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001394 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001395
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001396 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001397 /// } while (counter < limit);
1398 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1399 /// objects:items count:16]);
1400 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001401 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001402 /// }
1403 /// else
1404 /// elem = nil;
1405 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001406 ///
1407 buf = ";\n\t";
1408 buf += "__continue_label_";
1409 buf += utostr(ObjCBcLabelNo.back());
1410 buf += ": ;";
1411 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001412 buf += "} while (counter < limit);\n\t";
1413 buf += "} while (limit = ";
1414 SynthCountByEnumWithState(buf);
1415 buf += ");\n\t";
1416 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001417 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001418 buf += "__break_label_";
1419 buf += utostr(ObjCBcLabelNo.back());
1420 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001421 buf += "}\n\t";
1422 buf += "else\n\t\t";
1423 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001424 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001425 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001426
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001427 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001428 if (isa<CompoundStmt>(S->getBody())) {
1429 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1430 InsertText(endBodyLoc, buf.c_str(), buf.size());
1431 } else {
1432 /* Need to treat single statements specially. For example:
1433 *
1434 * for (A *a in b) if (stuff()) break;
1435 * for (A *a in b) xxxyy;
1436 *
1437 * The following code simply scans ahead to the semi to find the actual end.
1438 */
1439 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1440 const char *semiBuf = strchr(stmtBuf, ';');
1441 assert(semiBuf && "Can't find ';'");
1442 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1443 InsertText(endBodyLoc, buf.c_str(), buf.size());
1444 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001445 Stmts.pop_back();
1446 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001447 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001448}
1449
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001450/// RewriteObjCSynchronizedStmt -
1451/// This routine rewrites @synchronized(expr) stmt;
1452/// into:
1453/// objc_sync_enter(expr);
1454/// @try stmt @finally { objc_sync_exit(expr); }
1455///
Steve Naroffb29b4272008-04-14 22:03:09 +00001456Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001457 // Get the start location and compute the semi location.
1458 SourceLocation startLoc = S->getLocStart();
1459 const char *startBuf = SM->getCharacterData(startLoc);
1460
1461 assert((*startBuf == '@') && "bogus @synchronized location");
1462
1463 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001464 buf = "objc_sync_enter((id)";
1465 const char *lparenBuf = startBuf;
1466 while (*lparenBuf != '(') lparenBuf++;
1467 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001468 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1469 // the sync expression is typically a message expression that's already
1470 // been rewritten! (which implies the SourceLocation's are invalid).
1471 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001472 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001473 while (*endBuf != ')') endBuf--;
1474 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001475 buf = ");\n";
1476 // declare a new scope with two variables, _stack and _rethrow.
1477 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1478 buf += "int buf[18/*32-bit i386*/];\n";
1479 buf += "char *pointers[4];} _stack;\n";
1480 buf += "id volatile _rethrow = 0;\n";
1481 buf += "objc_exception_try_enter(&_stack);\n";
1482 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001483 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001484 startLoc = S->getSynchBody()->getLocEnd();
1485 startBuf = SM->getCharacterData(startLoc);
1486
Steve Naroffc7089f12008-08-19 13:04:19 +00001487 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001488 SourceLocation lastCurlyLoc = startLoc;
1489 buf = "}\nelse {\n";
1490 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1491 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001492 buf += " objc_sync_exit(";
Ted Kremenek8189cde2009-02-07 01:47:29 +00001493 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1494 S->getSynchExpr(),
1495 Context->getObjCIdType(),
1496 SourceLocation(),
1497 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001498 std::string syncExprBufS;
1499 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001500 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001501 buf += syncExprBuf.str();
1502 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001503 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1504 buf += "}\n";
1505 buf += "}";
1506
Chris Lattneraadaf782008-01-31 19:51:04 +00001507 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001508 return 0;
1509}
1510
Steve Naroff8c565152008-12-05 17:03:39 +00001511void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1512 // Perform a bottom up traversal of all children.
1513 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1514 CI != E; ++CI)
1515 if (*CI)
1516 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1517
1518 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1519 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1520 Diags.Report(Context->getFullLoc(S->getLocStart()),
1521 TryFinallyContainsReturnDiag);
1522 }
1523 return;
1524}
1525
Steve Naroffb29b4272008-04-14 22:03:09 +00001526Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001527 // Get the start location and compute the semi location.
1528 SourceLocation startLoc = S->getLocStart();
1529 const char *startBuf = SM->getCharacterData(startLoc);
1530
1531 assert((*startBuf == '@') && "bogus @try location");
1532
1533 std::string buf;
1534 // declare a new scope with two variables, _stack and _rethrow.
1535 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1536 buf += "int buf[18/*32-bit i386*/];\n";
1537 buf += "char *pointers[4];} _stack;\n";
1538 buf += "id volatile _rethrow = 0;\n";
1539 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001540 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001541
Chris Lattneraadaf782008-01-31 19:51:04 +00001542 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001543
1544 startLoc = S->getTryBody()->getLocEnd();
1545 startBuf = SM->getCharacterData(startLoc);
1546
1547 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001548
Steve Naroff75730982007-11-07 04:08:17 +00001549 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001550 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1551 if (catchList) {
1552 startLoc = startLoc.getFileLocWithOffset(1);
1553 buf = " /* @catch begin */ else {\n";
1554 buf += " id _caught = objc_exception_extract(&_stack);\n";
1555 buf += " objc_exception_try_enter (&_stack);\n";
1556 buf += " if (_setjmp(_stack.buf))\n";
1557 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1558 buf += " else { /* @catch continue */";
1559
1560 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001561 } else { /* no catch list */
1562 buf = "}\nelse {\n";
1563 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1564 buf += "}";
1565 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001566 }
Steve Naroff75730982007-11-07 04:08:17 +00001567 bool sawIdTypedCatch = false;
1568 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001569 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001570 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001571
1572 if (catchList == S->getCatchStmts())
1573 buf = "if ("; // we are generating code for the first catch clause
1574 else
1575 buf = "else if (";
1576 startLoc = catchList->getLocStart();
1577 startBuf = SM->getCharacterData(startLoc);
1578
1579 assert((*startBuf == '@') && "bogus @catch location");
1580
1581 const char *lParenLoc = strchr(startBuf, '(');
1582
Steve Naroffbe4b3332008-02-01 22:08:12 +00001583 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001584 // Now rewrite the body...
1585 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001586 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1587 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001588 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1589 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001590 assert((*bodyBuf == '{') && "bogus @catch body location");
1591
1592 buf += "1) { id _tmp = _caught;";
1593 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1594 buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001595 } else if (catchDecl) {
1596 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001597 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001598 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001599 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001600 sawIdTypedCatch = true;
1601 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001602 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001603
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001604 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001605 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001606 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001607 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001608 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001609 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001610 }
1611 }
1612 // Now rewrite the body...
1613 lastCatchBody = catchList->getCatchBody();
1614 SourceLocation rParenLoc = catchList->getRParenLoc();
1615 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1616 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1617 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1618 assert((*rParenBuf == ')') && "bogus @catch paren location");
1619 assert((*bodyBuf == '{') && "bogus @catch body location");
1620
1621 buf = " = _caught;";
1622 // Here we replace ") {" with "= _caught;" (which initializes and
1623 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001624 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001625 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001626 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001627 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001628 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001629 catchList = catchList->getNextCatchStmt();
1630 }
1631 // Complete the catch list...
1632 if (lastCatchBody) {
1633 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001634 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1635 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001636
Steve Naroff378f47a2008-09-11 15:29:03 +00001637 // Insert the last (implicit) else clause *before* the right curly brace.
1638 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1639 buf = "} /* last catch end */\n";
1640 buf += "else {\n";
1641 buf += " _rethrow = _caught;\n";
1642 buf += " objc_exception_try_exit(&_stack);\n";
1643 buf += "} } /* @catch end */\n";
1644 if (!S->getFinallyStmt())
1645 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001646 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001647
1648 // Set lastCurlyLoc
1649 lastCurlyLoc = lastCatchBody->getLocEnd();
1650 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001651 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001652 startLoc = finalStmt->getLocStart();
1653 startBuf = SM->getCharacterData(startLoc);
1654 assert((*startBuf == '@') && "bogus @finally start");
1655
1656 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001657 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001658
1659 Stmt *body = finalStmt->getFinallyBody();
1660 SourceLocation startLoc = body->getLocStart();
1661 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001662 assert(*SM->getCharacterData(startLoc) == '{' &&
1663 "bogus @finally body location");
1664 assert(*SM->getCharacterData(endLoc) == '}' &&
1665 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001666
1667 startLoc = startLoc.getFileLocWithOffset(1);
1668 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001669 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001670 endLoc = endLoc.getFileLocWithOffset(-1);
1671 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001672 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001673
1674 // Set lastCurlyLoc
1675 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001676
1677 // Now check for any return/continue/go statements within the @try.
1678 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001679 } else { /* no finally clause - make sure we synthesize an implicit one */
1680 buf = "{ /* implicit finally clause */\n";
1681 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1682 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1683 buf += "}";
1684 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001685 }
1686 // Now emit the final closing curly brace...
1687 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1688 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001689 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001690 return 0;
1691}
1692
Steve Naroffb29b4272008-04-14 22:03:09 +00001693Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001694 return 0;
1695}
1696
Steve Naroffb29b4272008-04-14 22:03:09 +00001697Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001698 return 0;
1699}
1700
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001701// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001702// the throw expression is typically a message expression that's already
1703// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001704Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001705 // Get the start location and compute the semi location.
1706 SourceLocation startLoc = S->getLocStart();
1707 const char *startBuf = SM->getCharacterData(startLoc);
1708
1709 assert((*startBuf == '@') && "bogus @throw location");
1710
1711 std::string buf;
1712 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001713 if (S->getThrowExpr())
1714 buf = "objc_exception_throw(";
1715 else // add an implicit argument
1716 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001717
1718 // handle "@ throw" correctly.
1719 const char *wBuf = strchr(startBuf, 'w');
1720 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1721 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1722
Steve Naroff2bd03922007-11-07 15:32:26 +00001723 const char *semiBuf = strchr(startBuf, ';');
1724 assert((*semiBuf == ';') && "@throw: can't find ';'");
1725 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1726 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001727 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001728 return 0;
1729}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001730
Steve Naroffb29b4272008-04-14 22:03:09 +00001731Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001732 // Create a new string expression.
1733 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001734 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001735 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001736 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1737 StrEncoding.length(), false,StrType,
1738 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001739 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001740
Chris Lattner07506182007-11-30 22:53:43 +00001741 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001742 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001743 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001744}
1745
Steve Naroffb29b4272008-04-14 22:03:09 +00001746Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001747 if (!SelGetUidFunctionDecl)
1748 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001749 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1750 // Create a call to sel_registerName("selName").
1751 llvm::SmallVector<Expr*, 8> SelExprs;
1752 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00001753 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001754 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001755 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001756 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001757 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1758 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001759 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001760 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001761 return SelExp;
1762}
1763
Steve Naroffb29b4272008-04-14 22:03:09 +00001764CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001765 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001766 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001767 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001768
1769 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001770 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001771
1772 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001773 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001774 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001775 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001776
1777 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001778
Ted Kremenek668bf912009-02-09 20:51:47 +00001779 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1780 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001781}
1782
Steve Naroffd5255f52007-11-01 13:24:47 +00001783static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1784 const char *&startRef, const char *&endRef) {
1785 while (startBuf < endBuf) {
1786 if (*startBuf == '<')
1787 startRef = startBuf; // mark the start.
1788 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001789 if (startRef && *startRef == '<') {
1790 endRef = startBuf; // mark the end.
1791 return true;
1792 }
1793 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001794 }
1795 startBuf++;
1796 }
1797 return false;
1798}
1799
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001800static void scanToNextArgument(const char *&argRef) {
1801 int angle = 0;
1802 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1803 if (*argRef == '<')
1804 angle++;
1805 else if (*argRef == '>')
1806 angle--;
1807 argRef++;
1808 }
1809 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1810}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001811
Steve Naroffb29b4272008-04-14 22:03:09 +00001812bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001813
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001814 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001815 return true;
1816
Steve Naroffd5255f52007-11-01 13:24:47 +00001817 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001818 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001819 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001820 return true; // we have "Class <Protocol> *".
1821 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001822 return false;
1823}
1824
Steve Naroff4f95b752008-07-29 18:15:38 +00001825void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1826 QualType Type = E->getType();
1827 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001828 SourceLocation Loc, EndLoc;
1829
1830 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1831 Loc = ECE->getLParenLoc();
1832 EndLoc = ECE->getRParenLoc();
1833 } else {
1834 Loc = E->getLocStart();
1835 EndLoc = E->getLocEnd();
1836 }
1837 // This will defend against trying to rewrite synthesized expressions.
1838 if (Loc.isInvalid() || EndLoc.isInvalid())
1839 return;
1840
Steve Naroff4f95b752008-07-29 18:15:38 +00001841 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001842 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001843 const char *startRef = 0, *endRef = 0;
1844 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1845 // Get the locations of the startRef, endRef.
1846 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1847 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1848 // Comment out the protocol references.
1849 InsertText(LessLoc, "/*", 2);
1850 InsertText(GreaterLoc, "*/", 2);
1851 }
1852 }
1853}
1854
Steve Naroffb29b4272008-04-14 22:03:09 +00001855void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001856 SourceLocation Loc;
1857 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00001858 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001859 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1860 Loc = VD->getLocation();
1861 Type = VD->getType();
1862 }
1863 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1864 Loc = FD->getLocation();
1865 // Check for ObjC 'id' and class types that have been adorned with protocol
1866 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1867 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1868 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00001869 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001870 if (!proto)
1871 return;
1872 Type = proto->getResultType();
1873 }
1874 else
1875 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001876
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001877 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001878 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001879
1880 const char *endBuf = SM->getCharacterData(Loc);
1881 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001882 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001883 startBuf--; // scan backward (from the decl location) for return type.
1884 const char *startRef = 0, *endRef = 0;
1885 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1886 // Get the locations of the startRef, endRef.
1887 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1888 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1889 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001890 InsertText(LessLoc, "/*", 2);
1891 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001892 }
1893 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001894 if (!proto)
1895 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001896 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001897 const char *startBuf = SM->getCharacterData(Loc);
1898 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001899 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1900 if (needToScanForQualifiers(proto->getArgType(i))) {
1901 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001902
Steve Naroffd5255f52007-11-01 13:24:47 +00001903 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001904 // scan forward (from the decl location) for argument types.
1905 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001906 const char *startRef = 0, *endRef = 0;
1907 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1908 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001909 SourceLocation LessLoc =
1910 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1911 SourceLocation GreaterLoc =
1912 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001913 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001914 InsertText(LessLoc, "/*", 2);
1915 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001916 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001917 startBuf = ++endBuf;
1918 }
1919 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001920 // If the function name is derived from a macro expansion, then the
1921 // argument buffer will not follow the name. Need to speak with Chris.
1922 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001923 startBuf++; // scan forward (from the decl location) for argument types.
1924 startBuf++;
1925 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001926 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001927}
1928
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001929// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001930void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001931 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1932 llvm::SmallVector<QualType, 16> ArgTys;
1933 ArgTys.push_back(Context->getPointerType(
1934 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001935 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001936 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001937 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001938 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001939 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001940 SelGetUidIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001941 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001942}
1943
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001944// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001945void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001946 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1947 llvm::SmallVector<QualType, 16> ArgTys;
1948 ArgTys.push_back(Context->getPointerType(
1949 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001950 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001951 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001952 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001953 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001954 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001955 SelGetProtoIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001956 FunctionDecl::Extern, false);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001957}
1958
Steve Naroffb29b4272008-04-14 22:03:09 +00001959void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001960 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00001961 if (FD->getIdentifier() &&
1962 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001963 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001964 return;
1965 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001966 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001967}
1968
Steve Naroffc0a123c2008-03-11 17:37:02 +00001969// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001970void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001971 if (SuperContructorFunctionDecl)
1972 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00001973 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00001974 llvm::SmallVector<QualType, 16> ArgTys;
1975 QualType argT = Context->getObjCIdType();
1976 assert(!argT.isNull() && "Can't find 'id' type");
1977 ArgTys.push_back(argT);
1978 ArgTys.push_back(argT);
1979 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1980 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001981 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001982 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001983 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001984 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001985 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00001986}
1987
Steve Naroff09b266e2007-10-30 23:14:51 +00001988// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001989void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001990 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1991 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001992 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001993 assert(!argT.isNull() && "Can't find 'id' type");
1994 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001995 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001996 assert(!argT.isNull() && "Can't find 'SEL' type");
1997 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001998 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001999 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002000 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002001 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002002 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002003 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002004 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002005}
2006
Steve Naroff874e2322007-11-15 10:28:18 +00002007// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002008void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002009 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2010 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002011 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002012 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002013 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002014 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2015 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2016 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002017 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002018 assert(!argT.isNull() && "Can't find 'SEL' type");
2019 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002020 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002021 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002022 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002023 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002024 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002025 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002026 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002027}
2028
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002029// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002030void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002031 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2032 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002033 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002034 assert(!argT.isNull() && "Can't find 'id' type");
2035 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002036 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002037 assert(!argT.isNull() && "Can't find 'SEL' type");
2038 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002039 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002040 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002041 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002042 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002043 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002044 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002045 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002046}
2047
2048// SynthMsgSendSuperStretFunctionDecl -
2049// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002050void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002051 IdentifierInfo *msgSendIdent =
2052 &Context->Idents.get("objc_msgSendSuper_stret");
2053 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002054 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002055 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002056 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002057 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2058 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2059 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002060 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002061 assert(!argT.isNull() && "Can't find 'SEL' type");
2062 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002063 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002064 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002065 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002066 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002067 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002068 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002069 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002070}
2071
Steve Naroff1284db82008-05-08 22:02:18 +00002072// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002073void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002074 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2075 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002076 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002077 assert(!argT.isNull() && "Can't find 'id' type");
2078 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002079 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002080 assert(!argT.isNull() && "Can't find 'SEL' type");
2081 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002082 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002083 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002084 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002085 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002086 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002087 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002088 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002089}
2090
Steve Naroff09b266e2007-10-30 23:14:51 +00002091// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002092void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002093 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2094 llvm::SmallVector<QualType, 16> ArgTys;
2095 ArgTys.push_back(Context->getPointerType(
2096 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002097 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002098 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002099 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002100 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002101 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002102 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002103 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002104}
2105
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002106// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002107void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002108 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2109 llvm::SmallVector<QualType, 16> ArgTys;
2110 ArgTys.push_back(Context->getPointerType(
2111 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002112 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002113 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002114 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002115 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002116 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002117 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002118 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002119}
2120
Steve Naroffb29b4272008-04-14 22:03:09 +00002121Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002122 QualType strType = getConstantStringStructType();
2123
2124 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002125
2126 std::string tmpName = InFileName;
2127 unsigned i;
2128 for (i=0; i < tmpName.length(); i++) {
2129 char c = tmpName.at(i);
2130 // replace any non alphanumeric characters with '_'.
2131 if (!isalpha(c) && (c < '0' || c > '9'))
2132 tmpName[i] = '_';
2133 }
2134 S += tmpName;
2135 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002136 S += utostr(NumObjCStringLiterals++);
2137
Steve Naroffba92b2e2008-03-27 22:29:16 +00002138 Preamble += "static __NSConstantStringImpl " + S;
2139 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2140 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002141 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002142 std::string prettyBufS;
2143 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002144 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002145 Preamble += prettyBuf.str();
2146 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002147 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002148 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002149
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002150 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002151 &Context->Idents.get(S.c_str()), strType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002152 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002153 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2154 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002155 Context->getPointerType(DRE->getType()),
2156 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002157 // cast to NSConstantString *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002158 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002159 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002160 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002161 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002162 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002163}
2164
Steve Naroffb29b4272008-04-14 22:03:09 +00002165ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002166 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002167 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002168
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002169 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2170 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002171 assert(PT);
2172 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2173 return IT->getDecl();
2174 }
2175 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002176}
2177
2178// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002179QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002180 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002181 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002182 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002183 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002184 QualType FieldTypes[2];
2185
2186 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002187 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002188 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002189 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002190
Steve Naroff874e2322007-11-15 10:28:18 +00002191 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002192 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregor482b77d2009-01-12 23:27:07 +00002193 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002194 SourceLocation(), 0,
2195 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002196 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002197 }
Steve Naroff874e2322007-11-15 10:28:18 +00002198
Douglas Gregor44b43212008-12-11 16:49:14 +00002199 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002200 }
2201 return Context->getTagDeclType(SuperStructDecl);
2202}
2203
Steve Naroffb29b4272008-04-14 22:03:09 +00002204QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002205 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002206 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002207 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002208 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002209 QualType FieldTypes[4];
2210
2211 // struct objc_object *receiver;
2212 FieldTypes[0] = Context->getObjCIdType();
2213 // int flags;
2214 FieldTypes[1] = Context->IntTy;
2215 // char *str;
2216 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2217 // long length;
2218 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002219
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002220 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002221 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregor482b77d2009-01-12 23:27:07 +00002222 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
Douglas Gregor44b43212008-12-11 16:49:14 +00002223 ConstantStringDecl,
2224 SourceLocation(), 0,
2225 FieldTypes[i],
2226 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002227 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002228 }
2229
2230 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002231 }
2232 return Context->getTagDeclType(ConstantStringDecl);
2233}
2234
Steve Naroffb29b4272008-04-14 22:03:09 +00002235Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002236 if (!SelGetUidFunctionDecl)
2237 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002238 if (!MsgSendFunctionDecl)
2239 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002240 if (!MsgSendSuperFunctionDecl)
2241 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002242 if (!MsgSendStretFunctionDecl)
2243 SynthMsgSendStretFunctionDecl();
2244 if (!MsgSendSuperStretFunctionDecl)
2245 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002246 if (!MsgSendFpretFunctionDecl)
2247 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002248 if (!GetClassFunctionDecl)
2249 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002250 if (!GetMetaClassFunctionDecl)
2251 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002252
Steve Naroff874e2322007-11-15 10:28:18 +00002253 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002254 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2255 // May need to use objc_msgSend_stret() as well.
2256 FunctionDecl *MsgSendStretFlavor = 0;
Chris Lattner89951a82009-02-20 18:43:26 +00002257 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2258 QualType resultType = OMD->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002259 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002260 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002261 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002262 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002263 }
Steve Naroff874e2322007-11-15 10:28:18 +00002264
Steve Naroff934f2762007-10-24 22:48:43 +00002265 // Synthesize a call to objc_msgSend().
2266 llvm::SmallVector<Expr*, 8> MsgExprs;
2267 IdentifierInfo *clsName = Exp->getClassName();
2268
2269 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2270 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002271 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2272 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002273 if (!strcmp(clsName->getName(), "super")) {
2274 MsgSendFlavor = MsgSendSuperFunctionDecl;
2275 if (MsgSendStretFlavor)
2276 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2277 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2278
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002279 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002280 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002281
2282 llvm::SmallVector<Expr*, 4> InitExprs;
2283
2284 // set the receiver to self, the first argument to all methods.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002285 InitExprs.push_back(new (Context) DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002286 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002287 Context->getObjCIdType(),
2288 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002289 llvm::SmallVector<Expr*, 8> ClsExprs;
2290 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002291 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002292 SuperDecl->getIdentifier()->getName(),
2293 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002294 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002295 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2296 &ClsExprs[0],
2297 ClsExprs.size());
2298 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002299 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002300 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002301 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002302 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002303 // struct objc_super
2304 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002305 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002306
Steve Naroff23f41272008-03-11 18:14:26 +00002307 if (LangOpts.Microsoft) {
2308 SynthSuperContructorFunctionDecl();
2309 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002310 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002311 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002312 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2313 InitExprs.size(),
2314 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002315 // The code for super is a little tricky to prevent collision with
2316 // the structure definition in the header. The rewriter has it's own
2317 // internal definition (__rw_objc_super) that is uses. This is why
2318 // we need the cast below. For example:
2319 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2320 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002321 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002322 Context->getPointerType(SuperRep->getType()),
2323 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002324 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002325 SuperRep, Context->getPointerType(superType),
2326 SourceLocation(), SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002327 } else {
2328 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002329 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroff23f41272008-03-11 18:14:26 +00002330 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002331 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002332 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner418f6c72008-10-26 23:43:26 +00002333 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002334 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002335 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002336 Context->getPointerType(SuperRep->getType()),
2337 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002338 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002339 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002340 } else {
2341 llvm::SmallVector<Expr*, 8> ClsExprs;
2342 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002343 ClsExprs.push_back(StringLiteral::Create(*Context,
2344 clsName->getName(),
2345 clsName->getLength(),
2346 false, argType,
2347 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002348 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2349 &ClsExprs[0],
2350 ClsExprs.size());
2351 MsgExprs.push_back(Cls);
2352 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002353 } else { // instance message.
2354 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002355
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002356 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002357 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002358 if (MsgSendStretFlavor)
2359 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002360 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2361
2362 llvm::SmallVector<Expr*, 4> InitExprs;
2363
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002364 InitExprs.push_back(
Ted Kremenek8189cde2009-02-07 01:47:29 +00002365 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2366 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002367 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002368 SourceLocation()),
2369 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002370 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002371
2372 llvm::SmallVector<Expr*, 8> ClsExprs;
2373 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002374 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002375 SuperDecl->getIdentifier()->getName(),
2376 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002377 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002378 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002379 &ClsExprs[0],
2380 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002381 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002382 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002383 // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002384 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002385 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002386 // struct objc_super
2387 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002388 Expr *SuperRep;
2389
2390 if (LangOpts.Microsoft) {
2391 SynthSuperContructorFunctionDecl();
2392 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002393 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002394 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002395 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2396 InitExprs.size(),
2397 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002398 // The code for super is a little tricky to prevent collision with
2399 // the structure definition in the header. The rewriter has it's own
2400 // internal definition (__rw_objc_super) that is uses. This is why
2401 // we need the cast below. For example:
2402 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2403 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002404 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002405 Context->getPointerType(SuperRep->getType()),
2406 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002407 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002408 SuperRep, Context->getPointerType(superType),
2409 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002410 } else {
2411 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002412 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00002413 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002414 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002415 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002416 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002417 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002418 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002419 // Remove all type-casts because it may contain objc-style types; e.g.
2420 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002421 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002422 recExpr = CE->getSubExpr();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002423 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002424 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002425 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002426 MsgExprs.push_back(recExpr);
2427 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002428 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002429 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002430 llvm::SmallVector<Expr*, 8> SelExprs;
2431 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002432 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002433 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002434 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002435 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002436 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2437 &SelExprs[0], SelExprs.size());
2438 MsgExprs.push_back(SelExp);
2439
2440 // Now push any user supplied arguments.
2441 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002442 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002443 // Make all implicit casts explicit...ICE comes in handy:-)
2444 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2445 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002446 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002447 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002448 : ICE->getType();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002449 userExpr = new (Context) CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002450 }
2451 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002452 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002453 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002454 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002455 userExpr = CE->getSubExpr();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002456 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002457 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002458 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002459 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002460 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002461 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002462 // We've transferred the ownership to MsgExprs. Null out the argument in
2463 // the original expression, since we will delete it below.
2464 Exp->setArg(i, 0);
2465 }
Steve Naroffab972d32007-11-04 22:37:50 +00002466 // Generate the funky cast.
2467 CastExpr *cast;
2468 llvm::SmallVector<QualType, 8> ArgTypes;
2469 QualType returnType;
2470
2471 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002472 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2473 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2474 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002475 ArgTypes.push_back(Context->getObjCIdType());
2476 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002477 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002478 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002479 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2480 E = OMD->param_end(); PI != E; ++PI) {
2481 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002482 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002483 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002484 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002485 if (isTopLevelBlockPointerType(t)) {
Steve Naroffa206b062008-10-29 14:49:46 +00002486 const BlockPointerType *BPT = t->getAsBlockPointerType();
2487 t = Context->getPointerType(BPT->getPointeeType());
2488 }
Steve Naroff352336b2007-11-05 14:36:37 +00002489 ArgTypes.push_back(t);
2490 }
Chris Lattner89951a82009-02-20 18:43:26 +00002491 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2492 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002493 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002494 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002495 }
2496 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002497 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002498
2499 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002500 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002501 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002502
2503 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2504 // If we don't do this cast, we get the following bizarre warning/note:
2505 // xx.m:13: warning: function called through a non-compatible type
2506 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek8189cde2009-02-07 01:47:29 +00002507 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002508 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002509 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002510
Steve Naroffab972d32007-11-04 22:37:50 +00002511 // Now do the "normal" pointer to function cast.
2512 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002513 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002514 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002515 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002516 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002517 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002518
2519 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002520 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002521
2522 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002523 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2524 MsgExprs.size(),
2525 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002526 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002527 if (MsgSendStretFlavor) {
2528 // We have the method which returns a struct/union. Must also generate
2529 // call to objc_msgSend_stret and hang both varieties on a conditional
2530 // expression which dictate which one to envoke depending on size of
2531 // method's return type.
2532
2533 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002534 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002535 SourceLocation());
2536 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek8189cde2009-02-07 01:47:29 +00002537 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002538 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002539 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002540 // Now do the "normal" pointer to function cast.
2541 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002542 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002543 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002544 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002545 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002546
2547 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002548 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002549
2550 FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002551 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2552 MsgExprs.size(),
2553 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002554
2555 // Build sizeof(returnType)
Ted Kremenek8189cde2009-02-07 01:47:29 +00002556 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true, true,
Sebastian Redl05189992008-11-11 17:56:53 +00002557 returnType.getAsOpaquePtr(),
2558 Context->getSizeType(),
2559 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002560 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2561 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2562 // For X86 it is more complicated and some kind of target specific routine
2563 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002564 unsigned IntSize =
2565 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek8189cde2009-02-07 01:47:29 +00002566 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002567 Context->IntTy,
2568 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002569 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002570 BinaryOperator::LE,
2571 Context->IntTy,
2572 SourceLocation());
2573 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2574 ConditionalOperator *CondExpr =
Ted Kremenek8189cde2009-02-07 01:47:29 +00002575 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2576 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002577 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002578 return ReplacingStmt;
2579}
2580
Steve Naroffb29b4272008-04-14 22:03:09 +00002581Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002582 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002583
Steve Naroffc77a6362008-12-04 16:24:46 +00002584 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002585 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002586 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002587
Steve Naroff4c3580e2008-12-04 23:50:32 +00002588 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002589 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002590}
2591
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002592/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2593/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002594Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002595 if (!GetProtocolFunctionDecl)
2596 SynthGetProtocolFunctionDecl();
2597 // Create a call to objc_getProtocol("ProtocolName").
2598 llvm::SmallVector<Expr*, 8> ProtoExprs;
2599 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002600 ProtoExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002601 Exp->getProtocol()->getNameAsCString(),
2602 strlen(Exp->getProtocol()->getNameAsCString()),
Chris Lattner726e1682009-02-18 05:49:11 +00002603 false, argType, SourceLocation()));
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002604 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2605 &ProtoExprs[0],
2606 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002607 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002608 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002609 return ProtoExp;
2610
2611}
2612
Steve Naroffbaf58c32008-05-31 14:15:04 +00002613bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2614 const char *endBuf) {
2615 while (startBuf < endBuf) {
2616 if (*startBuf == '#') {
2617 // Skip whitespace.
2618 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2619 ;
2620 if (!strncmp(startBuf, "if", strlen("if")) ||
2621 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2622 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2623 !strncmp(startBuf, "define", strlen("define")) ||
2624 !strncmp(startBuf, "undef", strlen("undef")) ||
2625 !strncmp(startBuf, "else", strlen("else")) ||
2626 !strncmp(startBuf, "elif", strlen("elif")) ||
2627 !strncmp(startBuf, "endif", strlen("endif")) ||
2628 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2629 !strncmp(startBuf, "include", strlen("include")) ||
2630 !strncmp(startBuf, "import", strlen("import")) ||
2631 !strncmp(startBuf, "include_next", strlen("include_next")))
2632 return true;
2633 }
2634 startBuf++;
2635 }
2636 return false;
2637}
2638
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002639/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002640/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002641void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002642 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002643 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002644 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002645 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002646 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002647 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002648 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002649 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002650 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002651 SourceLocation LocStart = CDecl->getLocStart();
2652 SourceLocation LocEnd = CDecl->getLocEnd();
2653
2654 const char *startBuf = SM->getCharacterData(LocStart);
2655 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002656
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002657 // If no ivars and no root or if its root, directly or indirectly,
2658 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002659 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2660 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002661 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002662 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002663 return;
2664 }
2665
2666 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002667 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002668 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002669 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002670 if (LangOpts.Microsoft)
2671 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002672
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002673 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002674 const char *cursor = strchr(startBuf, '{');
2675 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002676 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002677 // If the buffer contains preprocessor directives, we do more fine-grained
2678 // rewrites. This is intended to fix code that looks like (which occurs in
2679 // NSURL.h, for example):
2680 //
2681 // #ifdef XYZ
2682 // @interface Foo : NSObject
2683 // #else
2684 // @interface FooBar : NSObject
2685 // #endif
2686 // {
2687 // int i;
2688 // }
2689 // @end
2690 //
2691 // This clause is segregated to avoid breaking the common case.
2692 if (BufferContainsPPDirectives(startBuf, cursor)) {
2693 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2694 CDecl->getClassLoc();
2695 const char *endHeader = SM->getCharacterData(L);
2696 endHeader += Lexer::MeasureTokenLength(L, *SM);
2697
Chris Lattnercafeb352009-02-20 18:18:36 +00002698 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002699 // advance to the end of the referenced protocols.
2700 while (endHeader < cursor && *endHeader != '>') endHeader++;
2701 endHeader++;
2702 }
2703 // rewrite the original header
2704 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2705 } else {
2706 // rewrite the original header *without* disturbing the '{'
2707 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2708 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002709 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002710 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002711 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002712 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002713 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002714 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002715
2716 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002717 SourceLocation OnePastCurly =
2718 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2719 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002720 }
2721 cursor++; // past '{'
2722
2723 // Now comment out any visibility specifiers.
2724 while (cursor < endBuf) {
2725 if (*cursor == '@') {
2726 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002727 // Skip whitespace.
2728 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2729 /*scan*/;
2730
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002731 // FIXME: presence of @public, etc. inside comment results in
2732 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002733 if (!strncmp(cursor, "public", strlen("public")) ||
2734 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002735 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002736 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002737 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002738 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002739 // FIXME: If there are cases where '<' is used in ivar declaration part
2740 // of user code, then scan the ivar list and use needToScanForQualifiers
2741 // for type checking.
2742 else if (*cursor == '<') {
2743 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002744 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002745 cursor = strchr(cursor, '>');
2746 cursor++;
2747 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002748 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002749 } else if (*cursor == '^') { // rewrite block specifier.
2750 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2751 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002752 }
Steve Narofffea763e82007-11-14 19:25:57 +00002753 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002754 }
Steve Narofffea763e82007-11-14 19:25:57 +00002755 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002756 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002757 } else { // we don't have any instance variables - insert super struct.
2758 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2759 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002760 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002761 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002762 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002763 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002764 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002765 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002766 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002767 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002768 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002769}
2770
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002771// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002772/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002773void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002774 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002775 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002776 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002777 const char *ClassName,
2778 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002779 if (MethodBegin == MethodEnd) return;
2780
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002781 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002782 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002783 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002784 SEL _cmd;
2785 char *method_types;
2786 void *_imp;
2787 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002788 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002789 Result += "\nstruct _objc_method {\n";
2790 Result += "\tSEL _cmd;\n";
2791 Result += "\tchar *method_types;\n";
2792 Result += "\tvoid *_imp;\n";
2793 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002794
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002795 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002796 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002797
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002798 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002799
2800 /* struct {
2801 struct _objc_method_list *next_method;
2802 int method_count;
2803 struct _objc_method method_list[];
2804 }
2805 */
2806 Result += "\nstatic struct {\n";
2807 Result += "\tstruct _objc_method_list *next_method;\n";
2808 Result += "\tint method_count;\n";
2809 Result += "\tstruct _objc_method method_list[";
2810 Result += utostr(MethodEnd-MethodBegin);
2811 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002812 Result += prefix;
2813 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2814 Result += "_METHODS_";
2815 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002816 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002817 Result += IsInstanceMethod ? "inst" : "cls";
2818 Result += "_meth\")))= ";
2819 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002820
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002821 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002822 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002823 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002824 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002825 Result += "\", \"";
2826 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002827 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002828 Result += MethodInternalNames[*MethodBegin];
2829 Result += "}\n";
2830 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2831 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002832 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002833 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002834 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002835 Result += "\", \"";
2836 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002837 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002838 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002839 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002840 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002841 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002842}
2843
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002844/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002845void RewriteObjC::
2846RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2847 const char *prefix,
2848 const char *ClassName,
2849 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002850 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002851 if (Protocols.empty()) return;
2852
2853 for (unsigned i = 0; i != Protocols.size(); i++) {
2854 ObjCProtocolDecl *PDecl = Protocols[i];
2855 // Output struct protocol_methods holder of method selector and type.
2856 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2857 /* struct protocol_methods {
2858 SEL _cmd;
2859 char *method_types;
2860 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002861 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002862 Result += "\nstruct protocol_methods {\n";
2863 Result += "\tSEL _cmd;\n";
2864 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002865 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002866
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002867 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002868 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002869 // Do not synthesize the protocol more than once.
2870 if (ObjCSynthesizedProtocols.count(PDecl))
2871 continue;
2872
2873 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Chris Lattnercafeb352009-02-20 18:18:36 +00002874 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
2875 PDecl->instmeth_end());
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002876 /* struct _objc_protocol_method_list {
2877 int protocol_method_count;
2878 struct protocol_methods protocols[];
2879 }
2880 */
2881 Result += "\nstatic struct {\n";
2882 Result += "\tint protocol_method_count;\n";
2883 Result += "\tstruct protocol_methods protocols[";
2884 Result += utostr(NumMethods);
2885 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002886 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002887 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2888 "{\n\t" + utostr(NumMethods) + "\n";
2889
2890 // Output instance methods declared in this protocol.
2891 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2892 E = PDecl->instmeth_end(); I != E; ++I) {
2893 if (I == PDecl->instmeth_begin())
2894 Result += "\t ,{{(SEL)\"";
2895 else
2896 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002897 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002898 std::string MethodTypeString;
2899 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2900 Result += "\", \"";
2901 Result += MethodTypeString;
2902 Result += "\"}\n";
2903 }
2904 Result += "\t }\n};\n";
2905 }
2906
2907 // Output class methods declared in this protocol.
Chris Lattnercafeb352009-02-20 18:18:36 +00002908 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
2909 PDecl->classmeth_end());
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002910 if (NumMethods > 0) {
2911 /* struct _objc_protocol_method_list {
2912 int protocol_method_count;
2913 struct protocol_methods protocols[];
2914 }
2915 */
2916 Result += "\nstatic struct {\n";
2917 Result += "\tint protocol_method_count;\n";
2918 Result += "\tstruct protocol_methods protocols[";
2919 Result += utostr(NumMethods);
2920 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002921 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002922 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2923 "{\n\t";
2924 Result += utostr(NumMethods);
2925 Result += "\n";
2926
2927 // Output instance methods declared in this protocol.
2928 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2929 E = PDecl->classmeth_end(); I != E; ++I) {
2930 if (I == PDecl->classmeth_begin())
2931 Result += "\t ,{{(SEL)\"";
2932 else
2933 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002934 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002935 std::string MethodTypeString;
2936 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2937 Result += "\", \"";
2938 Result += MethodTypeString;
2939 Result += "\"}\n";
2940 }
2941 Result += "\t }\n};\n";
2942 }
2943
2944 // Output:
2945 /* struct _objc_protocol {
2946 // Objective-C 1.0 extensions
2947 struct _objc_protocol_extension *isa;
2948 char *protocol_name;
2949 struct _objc_protocol **protocol_list;
2950 struct _objc_protocol_method_list *instance_methods;
2951 struct _objc_protocol_method_list *class_methods;
2952 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002953 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002954 static bool objc_protocol = false;
2955 if (!objc_protocol) {
2956 Result += "\nstruct _objc_protocol {\n";
2957 Result += "\tstruct _objc_protocol_extension *isa;\n";
2958 Result += "\tchar *protocol_name;\n";
2959 Result += "\tstruct _objc_protocol **protocol_list;\n";
2960 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2961 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2962 Result += "};\n";
2963
2964 objc_protocol = true;
2965 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002966
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002967 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002968 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002969 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2970 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002971 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002972 Result += "\", 0, ";
2973 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2974 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002975 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002976 Result += ", ";
2977 }
2978 else
2979 Result += "0, ";
Chris Lattnercafeb352009-02-20 18:18:36 +00002980 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002981 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002982 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002983 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002984 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002985 else
2986 Result += "0\n";
2987 Result += "};\n";
2988
2989 // Mark this protocol as having been generated.
2990 if (!ObjCSynthesizedProtocols.insert(PDecl))
2991 assert(false && "protocol already synthesized");
2992 }
2993 // Output the top lovel protocol meta-data for the class.
2994 /* struct _objc_protocol_list {
2995 struct _objc_protocol_list *next;
2996 int protocol_count;
2997 struct _objc_protocol *class_protocols[];
2998 }
2999 */
3000 Result += "\nstatic struct {\n";
3001 Result += "\tstruct _objc_protocol_list *next;\n";
3002 Result += "\tint protocol_count;\n";
3003 Result += "\tstruct _objc_protocol *class_protocols[";
3004 Result += utostr(Protocols.size());
3005 Result += "];\n} _OBJC_";
3006 Result += prefix;
3007 Result += "_PROTOCOLS_";
3008 Result += ClassName;
3009 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3010 "{\n\t0, ";
3011 Result += utostr(Protocols.size());
3012 Result += "\n";
3013
3014 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003015 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003016 Result += " \n";
3017
3018 for (unsigned i = 1; i != Protocols.size(); i++) {
3019 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003020 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003021 Result += "\n";
3022 }
3023 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003024}
3025
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003026/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003027/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003028void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003029 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003030 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003031 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003032 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003033 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3034 CDecl = CDecl->getNextClassCategory())
3035 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3036 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003037
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003038 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003039 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003040 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003041
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003042 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003043 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003044 true, "CATEGORY_", FullCategoryName.c_str(),
3045 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003046
3047 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003048 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003049 false, "CATEGORY_", FullCategoryName.c_str(),
3050 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003051
3052 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003053 // Null CDecl is case of a category implementation with no category interface
3054 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003055 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003056 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003057
3058 /* struct _objc_category {
3059 char *category_name;
3060 char *class_name;
3061 struct _objc_method_list *instance_methods;
3062 struct _objc_method_list *class_methods;
3063 struct _objc_protocol_list *protocols;
3064 // Objective-C 1.0 extensions
3065 uint32_t size; // sizeof (struct _objc_category)
3066 struct _objc_property_list *instance_properties; // category's own
3067 // @property decl.
3068 };
3069 */
3070
3071 static bool objc_category = false;
3072 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003073 Result += "\nstruct _objc_category {\n";
3074 Result += "\tchar *category_name;\n";
3075 Result += "\tchar *class_name;\n";
3076 Result += "\tstruct _objc_method_list *instance_methods;\n";
3077 Result += "\tstruct _objc_method_list *class_methods;\n";
3078 Result += "\tstruct _objc_protocol_list *protocols;\n";
3079 Result += "\tunsigned int size;\n";
3080 Result += "\tstruct _objc_property_list *instance_properties;\n";
3081 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003082 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003083 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003084 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3085 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003086 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003087 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003088 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003089 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003090 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003091
Chris Lattnercafeb352009-02-20 18:18:36 +00003092 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003093 Result += "\t, (struct _objc_method_list *)"
3094 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3095 Result += FullCategoryName;
3096 Result += "\n";
3097 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003098 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003099 Result += "\t, 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003100 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003101 Result += "\t, (struct _objc_method_list *)"
3102 "&_OBJC_CATEGORY_CLASS_METHODS_";
3103 Result += FullCategoryName;
3104 Result += "\n";
3105 }
3106 else
3107 Result += "\t, 0\n";
3108
Chris Lattnercafeb352009-02-20 18:18:36 +00003109 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003110 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3111 Result += FullCategoryName;
3112 Result += "\n";
3113 }
3114 else
3115 Result += "\t, 0\n";
3116 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003117}
3118
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003119/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3120/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003121void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003122 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003123 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003124 if (ivar->isBitField()) {
3125 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3126 // place all bitfields at offset 0.
3127 Result += "0";
3128 } else {
3129 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003130 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003131 if (LangOpts.Microsoft)
3132 Result += "_IMPL";
3133 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003134 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003135 Result += ")";
3136 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003137}
3138
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003139//===----------------------------------------------------------------------===//
3140// Meta Data Emission
3141//===----------------------------------------------------------------------===//
3142
Steve Naroffb29b4272008-04-14 22:03:09 +00003143void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003144 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003145 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003146
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003147 // Explictly declared @interface's are already synthesized.
3148 if (CDecl->ImplicitInterfaceDecl()) {
3149 // FIXME: Implementation of a class with no @interface (legacy) doese not
3150 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003151 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003152 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003153
Chris Lattnerbe6df082007-12-12 07:56:42 +00003154 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003155 unsigned NumIvars = !IDecl->ivar_empty()
3156 ? IDecl->ivar_size()
3157 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003158 if (NumIvars > 0) {
3159 static bool objc_ivar = false;
3160 if (!objc_ivar) {
3161 /* struct _objc_ivar {
3162 char *ivar_name;
3163 char *ivar_type;
3164 int ivar_offset;
3165 };
3166 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003167 Result += "\nstruct _objc_ivar {\n";
3168 Result += "\tchar *ivar_name;\n";
3169 Result += "\tchar *ivar_type;\n";
3170 Result += "\tint ivar_offset;\n";
3171 Result += "};\n";
3172
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003173 objc_ivar = true;
3174 }
3175
Steve Naroff946a6932008-03-11 00:12:29 +00003176 /* struct {
3177 int ivar_count;
3178 struct _objc_ivar ivar_list[nIvars];
3179 };
3180 */
3181 Result += "\nstatic struct {\n";
3182 Result += "\tint ivar_count;\n";
3183 Result += "\tstruct _objc_ivar ivar_list[";
3184 Result += utostr(NumIvars);
3185 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003186 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003187 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003188 "{\n\t";
3189 Result += utostr(NumIvars);
3190 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003191
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003192 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003193 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003194 IVI = IDecl->ivar_begin();
3195 IVE = IDecl->ivar_end();
3196 } else {
3197 IVI = CDecl->ivar_begin();
3198 IVE = CDecl->ivar_end();
3199 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003200 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003201 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003202 Result += "\", \"";
3203 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003204 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003205 Result += StrEncoding;
3206 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003207 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003208 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003209 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003210 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003211 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003212 Result += "\", \"";
3213 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003214 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003215 Result += StrEncoding;
3216 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003217 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003218 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003219 }
3220
3221 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003222 }
3223
3224 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003225 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003226 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003227
3228 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003229 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003230 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003231
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003232 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003233 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003234 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003235
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003236
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003237 // Declaration of class/meta-class metadata
3238 /* struct _objc_class {
3239 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003240 const char *super_class_name;
3241 char *name;
3242 long version;
3243 long info;
3244 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003245 struct _objc_ivar_list *ivars;
3246 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003247 struct objc_cache *cache;
3248 struct objc_protocol_list *protocols;
3249 const char *ivar_layout;
3250 struct _objc_class_ext *ext;
3251 };
3252 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003253 static bool objc_class = false;
3254 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003255 Result += "\nstruct _objc_class {\n";
3256 Result += "\tstruct _objc_class *isa;\n";
3257 Result += "\tconst char *super_class_name;\n";
3258 Result += "\tchar *name;\n";
3259 Result += "\tlong version;\n";
3260 Result += "\tlong info;\n";
3261 Result += "\tlong instance_size;\n";
3262 Result += "\tstruct _objc_ivar_list *ivars;\n";
3263 Result += "\tstruct _objc_method_list *methods;\n";
3264 Result += "\tstruct objc_cache *cache;\n";
3265 Result += "\tstruct _objc_protocol_list *protocols;\n";
3266 Result += "\tconst char *ivar_layout;\n";
3267 Result += "\tstruct _objc_class_ext *ext;\n";
3268 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003269 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003270 }
3271
3272 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003273 ObjCInterfaceDecl *RootClass = 0;
3274 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003275 while (SuperClass) {
3276 RootClass = SuperClass;
3277 SuperClass = SuperClass->getSuperClass();
3278 }
3279 SuperClass = CDecl->getSuperClass();
3280
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003281 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003282 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003283 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003284 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003285 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003286 Result += "\"";
3287
3288 if (SuperClass) {
3289 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003290 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003291 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003292 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003293 Result += "\"";
3294 }
3295 else {
3296 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003297 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003298 Result += "\"";
3299 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003300 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003301 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003302 Result += ", 0,2, sizeof(struct _objc_class), 0";
Chris Lattner89951a82009-02-20 18:43:26 +00003303 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003304 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003305 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003306 Result += "\n";
3307 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003308 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003309 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003310 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003311 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003312 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003313 Result += ",0,0\n";
3314 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003315 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003316 Result += "\t,0,0,0,0\n";
3317 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003318
3319 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003320 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003321 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003322 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003323 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003324 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003325 if (SuperClass) {
3326 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003327 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003328 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003329 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003330 Result += "\"";
3331 }
3332 else {
3333 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003334 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003335 Result += "\"";
3336 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003337 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003338 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003339 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003340 Result += ",0";
3341 else {
3342 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003343 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003344 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003345 if (LangOpts.Microsoft)
3346 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003347 Result += ")";
3348 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003349 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003350 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003351 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003352 Result += "\n\t";
3353 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003354 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003355 Result += ",0";
Chris Lattner89951a82009-02-20 18:43:26 +00003356 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003357 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003358 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003359 Result += ", 0\n\t";
3360 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003361 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003362 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003363 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003364 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003365 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003366 Result += ", 0,0\n";
3367 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003368 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003369 Result += ",0,0,0\n";
3370 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003371}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003372
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003373/// RewriteImplementations - This routine rewrites all method implementations
3374/// and emits meta-data.
3375
Steve Narofface66252008-11-13 20:07:04 +00003376void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003377 int ClsDefCount = ClassImplementation.size();
3378 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003379
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003380 // Rewrite implemented methods
3381 for (int i = 0; i < ClsDefCount; i++)
3382 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003383
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003384 for (int i = 0; i < CatDefCount; i++)
3385 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003386}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003387
Steve Narofface66252008-11-13 20:07:04 +00003388void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3389 int ClsDefCount = ClassImplementation.size();
3390 int CatDefCount = CategoryImplementation.size();
3391
Steve Naroff5df5b762008-05-07 21:23:49 +00003392 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003393 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003394 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003395 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003396 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003397
3398 // For each implemented category, write out all its meta data.
3399 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003400 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003401
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003402 // Write objc_symtab metadata
3403 /*
3404 struct _objc_symtab
3405 {
3406 long sel_ref_cnt;
3407 SEL *refs;
3408 short cls_def_cnt;
3409 short cat_def_cnt;
3410 void *defs[cls_def_cnt + cat_def_cnt];
3411 };
3412 */
3413
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003414 Result += "\nstruct _objc_symtab {\n";
3415 Result += "\tlong sel_ref_cnt;\n";
3416 Result += "\tSEL *refs;\n";
3417 Result += "\tshort cls_def_cnt;\n";
3418 Result += "\tshort cat_def_cnt;\n";
3419 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3420 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003421
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003422 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003423 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003424 Result += "\t0, 0, " + utostr(ClsDefCount)
3425 + ", " + utostr(CatDefCount) + "\n";
3426 for (int i = 0; i < ClsDefCount; i++) {
3427 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003428 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003429 Result += "\n";
3430 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003431
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003432 for (int i = 0; i < CatDefCount; i++) {
3433 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003434 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003435 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003436 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003437 Result += "\n";
3438 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003439
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003440 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003441
3442 // Write objc_module metadata
3443
3444 /*
3445 struct _objc_module {
3446 long version;
3447 long size;
3448 const char *name;
3449 struct _objc_symtab *symtab;
3450 }
3451 */
3452
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003453 Result += "\nstruct _objc_module {\n";
3454 Result += "\tlong version;\n";
3455 Result += "\tlong size;\n";
3456 Result += "\tconst char *name;\n";
3457 Result += "\tstruct _objc_symtab *symtab;\n";
3458 Result += "};\n\n";
3459 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003460 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003461 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3462 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003463 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003464
3465 if (LangOpts.Microsoft) {
3466 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003467 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003468 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3469 Result += "&_OBJC_MODULES;\n";
3470 Result += "#pragma data_seg(pop)\n\n";
3471 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003472}
Chris Lattner311ff022007-10-16 22:36:42 +00003473
Steve Naroff54055232008-10-27 17:20:55 +00003474std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3475 const char *funcName,
3476 std::string Tag) {
3477 const FunctionType *AFT = CE->getFunctionType();
3478 QualType RT = AFT->getResultType();
3479 std::string StructRef = "struct " + Tag;
3480 std::string S = "static " + RT.getAsString() + " __" +
3481 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003482
Steve Naroff54055232008-10-27 17:20:55 +00003483 BlockDecl *BD = CE->getBlockDecl();
3484
Douglas Gregor72564e72009-02-26 23:50:07 +00003485 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroffdf8570d2009-02-02 17:19:26 +00003486 // No user-supplied arguments. Still need to pass in a pointer to the
3487 // block (to reference imported block decl refs).
3488 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003489 } else if (BD->param_empty()) {
3490 S += "(" + StructRef + " *__cself)";
3491 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003492 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003493 assert(FT && "SynthesizeBlockFunc: No function proto");
3494 S += '(';
3495 // first add the implicit argument.
3496 S += StructRef + " *__cself, ";
3497 std::string ParamStr;
3498 for (BlockDecl::param_iterator AI = BD->param_begin(),
3499 E = BD->param_end(); AI != E; ++AI) {
3500 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003501 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003502 (*AI)->getType().getAsStringInternal(ParamStr);
3503 S += ParamStr;
3504 }
3505 if (FT->isVariadic()) {
3506 if (!BD->param_empty()) S += ", ";
3507 S += "...";
3508 }
3509 S += ')';
3510 }
3511 S += " {\n";
3512
3513 // Create local declarations to avoid rewriting all closure decl ref exprs.
3514 // First, emit a declaration for all "by ref" decls.
3515 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3516 E = BlockByRefDecls.end(); I != E; ++I) {
3517 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003518 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003519 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003520 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003521 }
3522 // Next, emit a declaration for all "by copy" declarations.
3523 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3524 E = BlockByCopyDecls.end(); I != E; ++I) {
3525 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003526 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003527 // Handle nested closure invocation. For example:
3528 //
3529 // void (^myImportedClosure)(void);
3530 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3531 //
3532 // void (^anotherClosure)(void);
3533 // anotherClosure = ^(void) {
3534 // myImportedClosure(); // import and invoke the closure
3535 // };
3536 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003537 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003538 S += "struct __block_impl *";
3539 else
3540 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003541 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003542 }
3543 std::string RewrittenStr = RewrittenBlockExprs[CE];
3544 const char *cstr = RewrittenStr.c_str();
3545 while (*cstr++ != '{') ;
3546 S += cstr;
3547 S += "\n";
3548 return S;
3549}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003550
Steve Naroff54055232008-10-27 17:20:55 +00003551std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3552 const char *funcName,
3553 std::string Tag) {
3554 std::string StructRef = "struct " + Tag;
3555 std::string S = "static void __";
3556
3557 S += funcName;
3558 S += "_block_copy_" + utostr(i);
3559 S += "(" + StructRef;
3560 S += "*dst, " + StructRef;
3561 S += "*src) {";
3562 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3563 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003564 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003565 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003566 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003567 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003568 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff54055232008-10-27 17:20:55 +00003569 }
3570 S += "\nstatic void __";
3571 S += funcName;
3572 S += "_block_dispose_" + utostr(i);
3573 S += "(" + StructRef;
3574 S += "*src) {";
3575 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3576 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003577 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003578 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003579 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003580 }
3581 S += "}\n";
3582 return S;
3583}
3584
3585std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3586 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003587 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003588 std::string Constructor = " " + Tag;
3589
3590 S += " {\n struct __block_impl impl;\n";
3591
3592 if (hasCopyDisposeHelpers)
3593 S += " void *copy;\n void *dispose;\n";
3594
3595 Constructor += "(void *fp";
3596
3597 if (hasCopyDisposeHelpers)
3598 Constructor += ", void *copyHelp, void *disposeHelp";
3599
3600 if (BlockDeclRefs.size()) {
3601 // Output all "by copy" declarations.
3602 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3603 E = BlockByCopyDecls.end(); I != E; ++I) {
3604 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003605 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003606 std::string ArgName = "_" + FieldName;
3607 // Handle nested closure invocation. For example:
3608 //
3609 // void (^myImportedBlock)(void);
3610 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3611 //
3612 // void (^anotherBlock)(void);
3613 // anotherBlock = ^(void) {
3614 // myImportedBlock(); // import and invoke the closure
3615 // };
3616 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003617 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003618 S += "struct __block_impl *";
3619 Constructor += ", void *" + ArgName;
3620 } else {
3621 (*I)->getType().getAsStringInternal(FieldName);
3622 (*I)->getType().getAsStringInternal(ArgName);
3623 Constructor += ", " + ArgName;
3624 }
3625 S += FieldName + ";\n";
3626 }
3627 // Output all "by ref" declarations.
3628 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3629 E = BlockByRefDecls.end(); I != E; ++I) {
3630 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003631 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003632 std::string ArgName = "_" + FieldName;
3633 // Handle nested closure invocation. For example:
3634 //
3635 // void (^myImportedBlock)(void);
3636 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3637 //
3638 // void (^anotherBlock)(void);
3639 // anotherBlock = ^(void) {
3640 // myImportedBlock(); // import and invoke the closure
3641 // };
3642 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003643 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003644 S += "struct __block_impl *";
3645 Constructor += ", void *" + ArgName;
3646 } else {
3647 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3648 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3649 Constructor += ", " + ArgName;
3650 }
3651 S += FieldName + "; // by ref\n";
3652 }
3653 // Finish writing the constructor.
3654 // FIXME: handle NSConcreteGlobalBlock.
3655 Constructor += ", int flags=0) {\n";
3656 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3657 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3658
3659 if (hasCopyDisposeHelpers)
3660 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3661
3662 // Initialize all "by copy" arguments.
3663 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3664 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003665 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003666 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003667 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003668 Constructor += Name + " = (struct __block_impl *)_";
3669 else
3670 Constructor += Name + " = _";
3671 Constructor += Name + ";\n";
3672 }
3673 // Initialize all "by ref" arguments.
3674 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3675 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003676 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003677 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003678 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003679 Constructor += Name + " = (struct __block_impl *)_";
3680 else
3681 Constructor += Name + " = _";
3682 Constructor += Name + ";\n";
3683 }
3684 } else {
3685 // Finish writing the constructor.
3686 // FIXME: handle NSConcreteGlobalBlock.
3687 Constructor += ", int flags=0) {\n";
3688 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3689 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3690 if (hasCopyDisposeHelpers)
3691 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3692 }
3693 Constructor += " ";
3694 Constructor += "}\n";
3695 S += Constructor;
3696 S += "};\n";
3697 return S;
3698}
3699
3700void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3701 const char *FunName) {
3702 // Insert closures that were part of the function.
3703 for (unsigned i = 0; i < Blocks.size(); i++) {
3704
3705 CollectBlockDeclRefInfo(Blocks[i]);
3706
3707 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3708
3709 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3710 ImportedBlockDecls.size() > 0);
3711
3712 InsertText(FunLocStart, CI.c_str(), CI.size());
3713
3714 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3715
3716 InsertText(FunLocStart, CF.c_str(), CF.size());
3717
3718 if (ImportedBlockDecls.size()) {
3719 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3720 InsertText(FunLocStart, HF.c_str(), HF.size());
3721 }
3722
3723 BlockDeclRefs.clear();
3724 BlockByRefDecls.clear();
3725 BlockByCopyDecls.clear();
3726 BlockCallExprs.clear();
3727 ImportedBlockDecls.clear();
3728 }
3729 Blocks.clear();
3730 RewrittenBlockExprs.clear();
3731}
3732
3733void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3734 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003735 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003736
3737 SynthesizeBlockLiterals(FunLocStart, FuncName);
3738}
3739
3740void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003741 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3742 //SourceLocation FunLocStart = MD->getLocStart();
3743 // FIXME: This hack works around a bug in Rewrite.InsertText().
3744 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003745 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003746 // Convert colons to underscores.
3747 std::string::size_type loc = 0;
3748 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3749 FuncName.replace(loc, 1, "_");
3750
3751 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3752}
3753
3754void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3755 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3756 CI != E; ++CI)
3757 if (*CI) {
3758 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3759 GetBlockDeclRefExprs(CBE->getBody());
3760 else
3761 GetBlockDeclRefExprs(*CI);
3762 }
3763 // Handle specific things.
3764 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3765 // FIXME: Handle enums.
3766 if (!isa<FunctionDecl>(CDRE->getDecl()))
3767 BlockDeclRefs.push_back(CDRE);
3768 return;
3769}
3770
3771void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3772 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3773 CI != E; ++CI)
3774 if (*CI) {
3775 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3776 GetBlockCallExprs(CBE->getBody());
3777 else
3778 GetBlockCallExprs(*CI);
3779 }
3780
3781 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3782 if (CE->getCallee()->getType()->isBlockPointerType()) {
3783 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3784 }
3785 }
3786 return;
3787}
3788
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003789Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003790 // Navigate to relevant type information.
3791 const char *closureName = 0;
3792 const BlockPointerType *CPT = 0;
3793
3794 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003795 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003796 CPT = DRE->getType()->getAsBlockPointerType();
3797 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003798 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003799 CPT = CDRE->getType()->getAsBlockPointerType();
3800 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003801 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003802 CPT = MExpr->getType()->getAsBlockPointerType();
3803 } else {
3804 assert(1 && "RewriteBlockClass: Bad type");
3805 }
3806 assert(CPT && "RewriteBlockClass: Bad type");
3807 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3808 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003809 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003810 // FTP will be null for closures that don't take arguments.
3811
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003812 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3813 SourceLocation(),
3814 &Context->Idents.get("__block_impl"));
3815 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003816
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003817 // Generate a funky cast.
3818 llvm::SmallVector<QualType, 8> ArgTypes;
3819
3820 // Push the block argument type.
3821 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003822 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003823 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003824 E = FTP->arg_type_end(); I && (I != E); ++I) {
3825 QualType t = *I;
3826 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003827 if (isTopLevelBlockPointerType(t)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003828 const BlockPointerType *BPT = t->getAsBlockPointerType();
3829 t = Context->getPointerType(BPT->getPointeeType());
3830 }
3831 ArgTypes.push_back(t);
3832 }
Steve Naroff54055232008-10-27 17:20:55 +00003833 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003834 // Now do the pointer to function cast.
3835 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3836 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3837
3838 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003839
Ted Kremenek8189cde2009-02-07 01:47:29 +00003840 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3841 PtrBlock, SourceLocation(),
3842 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003843 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003844 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3845 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003846 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003847
Douglas Gregor44b43212008-12-11 16:49:14 +00003848 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3849 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003850 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003851 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3852 FD->getType());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003853
Ted Kremenek8189cde2009-02-07 01:47:29 +00003854 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3855 PtrToFuncCastType,
3856 SourceLocation(),
3857 SourceLocation());
3858 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003859
3860 llvm::SmallVector<Expr*, 8> BlkExprs;
3861 // Add the implicit argument.
3862 BlkExprs.push_back(BlkCast);
3863 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003864 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3865 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003866 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003867 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003868 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3869 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00003870 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003871 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003872}
3873
3874void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003875 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3876 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003877}
3878
3879void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3880 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003881 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroffdf8570d2009-02-02 17:19:26 +00003882 Context->getPointerType(BDRE->getType()),
3883 SourceLocation());
3884 // Need parens to enforce precedence.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003885 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroffdf8570d2009-02-02 17:19:26 +00003886 ReplaceStmt(BDRE, PE);
Steve Naroff54055232008-10-27 17:20:55 +00003887}
3888
Steve Naroffb2f9e512008-11-03 23:29:32 +00003889void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3890 SourceLocation LocStart = CE->getLParenLoc();
3891 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003892
3893 // Need to avoid trying to rewrite synthesized casts.
3894 if (LocStart.isInvalid())
3895 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003896 // Need to avoid trying to rewrite casts contained in macros.
3897 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3898 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003899
Steve Naroff54055232008-10-27 17:20:55 +00003900 const char *startBuf = SM->getCharacterData(LocStart);
3901 const char *endBuf = SM->getCharacterData(LocEnd);
3902
3903 // advance the location to startArgList.
3904 const char *argPtr = startBuf;
3905
3906 while (*argPtr++ && (argPtr < endBuf)) {
3907 switch (*argPtr) {
3908 case '^':
3909 // Replace the '^' with '*'.
3910 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3911 ReplaceText(LocStart, 1, "*", 1);
3912 break;
3913 }
3914 }
3915 return;
3916}
3917
3918void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3919 SourceLocation DeclLoc = FD->getLocation();
3920 unsigned parenCount = 0;
3921
3922 // We have 1 or more arguments that have closure pointers.
3923 const char *startBuf = SM->getCharacterData(DeclLoc);
3924 const char *startArgList = strchr(startBuf, '(');
3925
3926 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3927
3928 parenCount++;
3929 // advance the location to startArgList.
3930 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3931 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3932
3933 const char *argPtr = startArgList;
3934
3935 while (*argPtr++ && parenCount) {
3936 switch (*argPtr) {
3937 case '^':
3938 // Replace the '^' with '*'.
3939 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3940 ReplaceText(DeclLoc, 1, "*", 1);
3941 break;
3942 case '(':
3943 parenCount++;
3944 break;
3945 case ')':
3946 parenCount--;
3947 break;
3948 }
3949 }
3950 return;
3951}
3952
3953bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003954 const FunctionProtoType *FTP;
Steve Naroff54055232008-10-27 17:20:55 +00003955 const PointerType *PT = QT->getAsPointerType();
3956 if (PT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003957 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff54055232008-10-27 17:20:55 +00003958 } else {
3959 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3960 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003961 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff54055232008-10-27 17:20:55 +00003962 }
3963 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003964 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003965 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003966 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00003967 return true;
3968 }
3969 return false;
3970}
3971
Ted Kremenek8189cde2009-02-07 01:47:29 +00003972void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
3973 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00003974 const char *argPtr = strchr(Name, '(');
3975 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3976
3977 LParen = argPtr; // output the start.
3978 argPtr++; // skip past the left paren.
3979 unsigned parenCount = 1;
3980
3981 while (*argPtr && parenCount) {
3982 switch (*argPtr) {
3983 case '(': parenCount++; break;
3984 case ')': parenCount--; break;
3985 default: break;
3986 }
3987 if (parenCount) argPtr++;
3988 }
3989 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3990 RParen = argPtr; // output the end
3991}
3992
3993void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3994 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3995 RewriteBlockPointerFunctionArgs(FD);
3996 return;
3997 }
3998 // Handle Variables and Typedefs.
3999 SourceLocation DeclLoc = ND->getLocation();
4000 QualType DeclT;
4001 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4002 DeclT = VD->getType();
4003 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4004 DeclT = TDD->getUnderlyingType();
4005 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4006 DeclT = FD->getType();
4007 else
4008 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4009
4010 const char *startBuf = SM->getCharacterData(DeclLoc);
4011 const char *endBuf = startBuf;
4012 // scan backward (from the decl location) for the end of the previous decl.
4013 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4014 startBuf--;
4015
4016 // *startBuf != '^' if we are dealing with a pointer to function that
4017 // may take block argument types (which will be handled below).
4018 if (*startBuf == '^') {
4019 // Replace the '^' with '*', computing a negative offset.
4020 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4021 ReplaceText(DeclLoc, 1, "*", 1);
4022 }
4023 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4024 // Replace the '^' with '*' for arguments.
4025 DeclLoc = ND->getLocation();
4026 startBuf = SM->getCharacterData(DeclLoc);
4027 const char *argListBegin, *argListEnd;
4028 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4029 while (argListBegin < argListEnd) {
4030 if (*argListBegin == '^') {
4031 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4032 ReplaceText(CaretLoc, 1, "*", 1);
4033 }
4034 argListBegin++;
4035 }
4036 }
4037 return;
4038}
4039
4040void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4041 // Add initializers for any closure decl refs.
4042 GetBlockDeclRefExprs(Exp->getBody());
4043 if (BlockDeclRefs.size()) {
4044 // Unique all "by copy" declarations.
4045 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4046 if (!BlockDeclRefs[i]->isByRef())
4047 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4048 // Unique all "by ref" declarations.
4049 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4050 if (BlockDeclRefs[i]->isByRef()) {
4051 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4052 }
4053 // Find any imported blocks...they will need special attention.
4054 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff47a24222008-12-11 20:51:38 +00004055 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004056 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004057 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4058 }
4059 }
4060}
4061
Steve Narofffa15fd92008-10-28 20:29:00 +00004062FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4063 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004064 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Narofffa15fd92008-10-28 20:29:00 +00004065 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor2224f842009-02-25 16:33:18 +00004066 ID, FType, FunctionDecl::Extern, false,
4067 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004068}
4069
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004070Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004071 Blocks.push_back(Exp);
4072
4073 CollectBlockDeclRefInfo(Exp);
4074 std::string FuncName;
4075
4076 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004077 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004078 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004079 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004080 // Convert colons to underscores.
4081 std::string::size_type loc = 0;
4082 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4083 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004084 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004085 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004086
4087 std::string BlockNumber = utostr(Blocks.size()-1);
4088
4089 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4090 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4091
4092 // Get a pointer to the function type so we can cast appropriately.
4093 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4094
4095 FunctionDecl *FD;
4096 Expr *NewRep;
4097
4098 // Simulate a contructor call...
4099 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004100 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004101
4102 llvm::SmallVector<Expr*, 4> InitExprs;
4103
Steve Narofffdc03722008-10-29 21:23:59 +00004104 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004105 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004106 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4107 SourceLocation());
4108 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4109 Context->VoidPtrTy, SourceLocation(),
4110 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004111 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004112
4113 if (ImportedBlockDecls.size()) {
4114 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004115 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004116 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4117 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4118 Context->VoidPtrTy, SourceLocation(),
4119 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004120 InitExprs.push_back(castExpr);
4121
Steve Narofffa15fd92008-10-28 20:29:00 +00004122 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004123 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004124 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4125 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4126 Context->VoidPtrTy, SourceLocation(),
4127 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004128 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004129 }
4130 // Add initializers for any closure decl refs.
4131 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004132 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004133 // Output all "by copy" declarations.
4134 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4135 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004136 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004137 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004138 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004139 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004140 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004141 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004142 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4143 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4144 Context->VoidPtrTy, SourceLocation(),
4145 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004146 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004147 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004148 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004149 }
Steve Narofffdc03722008-10-29 21:23:59 +00004150 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004151 }
4152 // Output all "by ref" declarations.
4153 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4154 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004155 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004156 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4157 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Narofffdc03722008-10-29 21:23:59 +00004158 Context->getPointerType(Exp->getType()),
4159 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004160 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004161 }
4162 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004163 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4164 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004165 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Narofffa15fd92008-10-28 20:29:00 +00004166 Context->getPointerType(NewRep->getType()),
4167 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004168 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4169 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004170 BlockDeclRefs.clear();
4171 BlockByRefDecls.clear();
4172 BlockByCopyDecls.clear();
4173 ImportedBlockDecls.clear();
4174 return NewRep;
4175}
4176
4177//===----------------------------------------------------------------------===//
4178// Function Body / Expression rewriting
4179//===----------------------------------------------------------------------===//
4180
Steve Naroffc77a6362008-12-04 16:24:46 +00004181// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4182// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4183// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4184// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4185// Since the rewriter isn't capable of rewriting rewritten code, it's important
4186// we get this right.
4187void RewriteObjC::CollectPropertySetters(Stmt *S) {
4188 // Perform a bottom up traversal of all children.
4189 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4190 CI != E; ++CI)
4191 if (*CI)
4192 CollectPropertySetters(*CI);
4193
4194 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4195 if (BinOp->isAssignmentOp()) {
4196 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4197 PropSetters[PRE] = BinOp;
4198 }
4199 }
4200}
4201
Steve Narofffa15fd92008-10-28 20:29:00 +00004202Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4203 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4204 isa<DoStmt>(S) || isa<ForStmt>(S))
4205 Stmts.push_back(S);
4206 else if (isa<ObjCForCollectionStmt>(S)) {
4207 Stmts.push_back(S);
4208 ObjCBcLabelNo.push_back(++BcLabelCount);
4209 }
4210
4211 SourceRange OrigStmtRange = S->getSourceRange();
4212
4213 // Perform a bottom up rewrite of all children.
4214 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4215 CI != E; ++CI)
4216 if (*CI) {
4217 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4218 if (newStmt)
4219 *CI = newStmt;
4220 }
4221
4222 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4223 // Rewrite the block body in place.
4224 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4225
4226 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004227 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4228 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004229
4230 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4231 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004232 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004233 return blockTranscribed;
4234 }
4235 // Handle specific things.
4236 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4237 return RewriteAtEncode(AtEncode);
4238
4239 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4240 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4241
Steve Naroffc77a6362008-12-04 16:24:46 +00004242 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4243 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4244 if (BinOp) {
4245 // Because the rewriter doesn't allow us to rewrite rewritten code,
4246 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004247 DisableReplaceStmt = true;
4248 // Save the source range. Even if we disable the replacement, the
4249 // rewritten node will have been inserted into the tree. If the synthesized
4250 // node is at the 'end', the rewriter will fail. Consider this:
4251 // self.errorHandler = handler ? handler :
4252 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4253 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004254 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004255 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004256 //
4257 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4258 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4259 // to see the original expression). Consider this example:
4260 //
4261 // Foo *obj1, *obj2;
4262 //
4263 // obj1.i = [obj2 rrrr];
4264 //
4265 // 'BinOp' for the previous expression looks like:
4266 //
4267 // (BinaryOperator 0x231ccf0 'int' '='
4268 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4269 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4270 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4271 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4272 //
4273 // 'newStmt' represents the rewritten message expression. For example:
4274 //
4275 // (CallExpr 0x231d300 'id':'struct objc_object *'
4276 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4277 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4278 // (CStyleCastExpr 0x231d220 'void *'
4279 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4280 //
4281 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4282 // can be used as the setter argument. ReplaceStmt() will still 'see'
4283 // the original RHS (since we haven't altered BinOp).
4284 //
4285 // This implies the Rewrite* routines can no longer delete the original
4286 // node. As a result, we now leak the original AST nodes.
4287 //
Steve Naroffb619d952008-12-09 12:56:34 +00004288 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004289 } else {
4290 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004291 }
4292 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004293 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4294 return RewriteAtSelector(AtSelector);
4295
4296 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4297 return RewriteObjCStringLiteral(AtString);
4298
4299 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004300#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004301 // Before we rewrite it, put the original message expression in a comment.
4302 SourceLocation startLoc = MessExpr->getLocStart();
4303 SourceLocation endLoc = MessExpr->getLocEnd();
4304
4305 const char *startBuf = SM->getCharacterData(startLoc);
4306 const char *endBuf = SM->getCharacterData(endLoc);
4307
4308 std::string messString;
4309 messString += "// ";
4310 messString.append(startBuf, endBuf-startBuf+1);
4311 messString += "\n";
4312
4313 // FIXME: Missing definition of
4314 // InsertText(clang::SourceLocation, char const*, unsigned int).
4315 // InsertText(startLoc, messString.c_str(), messString.size());
4316 // Tried this, but it didn't work either...
4317 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004318#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004319 return RewriteMessageExpr(MessExpr);
4320 }
4321
4322 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4323 return RewriteObjCTryStmt(StmtTry);
4324
4325 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4326 return RewriteObjCSynchronizedStmt(StmtTry);
4327
4328 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4329 return RewriteObjCThrowStmt(StmtThrow);
4330
4331 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4332 return RewriteObjCProtocolExpr(ProtocolExp);
4333
4334 if (ObjCForCollectionStmt *StmtForCollection =
4335 dyn_cast<ObjCForCollectionStmt>(S))
4336 return RewriteObjCForCollectionStmt(StmtForCollection,
4337 OrigStmtRange.getEnd());
4338 if (BreakStmt *StmtBreakStmt =
4339 dyn_cast<BreakStmt>(S))
4340 return RewriteBreakStmt(StmtBreakStmt);
4341 if (ContinueStmt *StmtContinueStmt =
4342 dyn_cast<ContinueStmt>(S))
4343 return RewriteContinueStmt(StmtContinueStmt);
4344
4345 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4346 // and cast exprs.
4347 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4348 // FIXME: What we're doing here is modifying the type-specifier that
4349 // precedes the first Decl. In the future the DeclGroup should have
4350 // a separate type-specifier that we can rewrite.
4351 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4352
4353 // Blocks rewrite rules.
4354 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4355 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004356 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004357 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004358 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004359 RewriteBlockPointerDecl(ND);
4360 else if (ND->getType()->isFunctionPointerType())
4361 CheckFunctionPointerDecl(ND->getType(), ND);
4362 }
4363 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004364 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004365 RewriteBlockPointerDecl(TD);
4366 else if (TD->getUnderlyingType()->isFunctionPointerType())
4367 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4368 }
4369 }
4370 }
4371
4372 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4373 RewriteObjCQualifiedInterfaceTypes(CE);
4374
4375 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4376 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4377 assert(!Stmts.empty() && "Statement stack is empty");
4378 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4379 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4380 && "Statement stack mismatch");
4381 Stmts.pop_back();
4382 }
4383 // Handle blocks rewriting.
4384 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4385 if (BDRE->isByRef())
4386 RewriteBlockDeclRefExpr(BDRE);
4387 }
4388 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004389 if (CE->getCallee()->getType()->isBlockPointerType()) {
4390 Stmt *BlockCall = SynthesizeBlockCall(CE);
4391 ReplaceStmt(S, BlockCall);
4392 return BlockCall;
4393 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004394 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004395 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004396 RewriteCastExpr(CE);
4397 }
4398#if 0
4399 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004400 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004401 // Get the new text.
4402 std::string SStr;
4403 llvm::raw_string_ostream Buf(SStr);
4404 Replacement->printPretty(Buf);
4405 const std::string &Str = Buf.str();
4406
4407 printf("CAST = %s\n", &Str[0]);
4408 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4409 delete S;
4410 return Replacement;
4411 }
4412#endif
4413 // Return this stmt unmodified.
4414 return S;
4415}
4416
4417/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4418/// main file of the input.
4419void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4420 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004421 if (FD->isOverloadedOperator())
4422 return;
4423
Steve Narofffa15fd92008-10-28 20:29:00 +00004424 // Since function prototypes don't have ParmDecl's, we check the function
4425 // prototype. This enables us to rewrite function declarations and
4426 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00004427 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004428
4429 if (Stmt *Body = FD->getBody()) {
4430 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004431 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004432 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004433 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004434 CurrentBody = 0;
4435 if (PropParentMap) {
4436 delete PropParentMap;
4437 PropParentMap = 0;
4438 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004439 // This synthesizes and inserts the block "impl" struct, invoke function,
4440 // and any copy/dispose helper functions.
4441 InsertBlockLiteralsWithinFunction(FD);
4442 CurFunctionDef = 0;
4443 }
4444 return;
4445 }
4446 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4447 if (Stmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004448 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004449 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004450 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004451 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004452 CurrentBody = 0;
4453 if (PropParentMap) {
4454 delete PropParentMap;
4455 PropParentMap = 0;
4456 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004457 InsertBlockLiteralsWithinMethod(MD);
4458 CurMethodDef = 0;
4459 }
4460 }
4461 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4462 ClassImplementation.push_back(CI);
4463 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4464 CategoryImplementation.push_back(CI);
4465 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4466 RewriteForwardClassDecl(CD);
4467 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4468 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004469 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004470 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004471 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004472 CheckFunctionPointerDecl(VD->getType(), VD);
4473 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004474 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004475 RewriteCastExpr(CE);
4476 }
4477 }
4478 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004479 if (VD->getInit()) {
4480 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004481 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004482 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004483 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004484 CurrentBody = 0;
4485 if (PropParentMap) {
4486 delete PropParentMap;
4487 PropParentMap = 0;
4488 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004489 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004490 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004491 GlobalVarDecl = 0;
4492
4493 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004494 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004495 RewriteCastExpr(CE);
4496 }
4497 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004498 return;
4499 }
4500 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004501 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004502 RewriteBlockPointerDecl(TD);
4503 else if (TD->getUnderlyingType()->isFunctionPointerType())
4504 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4505 return;
4506 }
4507 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4508 if (RD->isDefinition()) {
Douglas Gregora4c46df2008-12-11 17:59:21 +00004509 for (RecordDecl::field_iterator i = RD->field_begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004510 e = RD->field_end(); i != e; ++i) {
4511 FieldDecl *FD = *i;
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004512 if (isTopLevelBlockPointerType(FD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004513 RewriteBlockPointerDecl(FD);
4514 }
4515 }
4516 return;
4517 }
4518 // Nothing yet.
4519}
4520
4521void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4522 // Get the top-level buffer that this corresponds to.
4523
4524 // Rewrite tabs if we care.
4525 //RewriteTabs();
4526
4527 if (Diags.hasErrorOccurred())
4528 return;
4529
4530 // Create the output file.
4531
4532 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4533 llvm::raw_ostream *OutFile;
4534 if (OutFileName == "-") {
4535 OutFile = &llvm::outs();
4536 } else if (!OutFileName.empty()) {
4537 std::string Err;
Steve Naroff62c26322009-02-03 20:39:18 +00004538 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(),
4539 // set binary mode (critical for Windoze)
4540 true,
4541 Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004542 OwnedStream.reset(OutFile);
4543 } else if (InFileName == "-") {
4544 OutFile = &llvm::outs();
4545 } else {
4546 llvm::sys::Path Path(InFileName);
4547 Path.eraseSuffix();
4548 Path.appendSuffix("cpp");
4549 std::string Err;
Steve Naroff62c26322009-02-03 20:39:18 +00004550 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(),
4551 // set binary mode (critical for Windoze)
4552 true,
4553 Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004554 OwnedStream.reset(OutFile);
4555 }
4556
4557 RewriteInclude();
4558
Chris Lattner2b2453a2009-01-17 06:22:33 +00004559 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00004560 Preamble.c_str(), Preamble.size(), false);
4561
Steve Naroff0aab7962008-11-14 14:10:01 +00004562 if (ClassImplementation.size() || CategoryImplementation.size())
4563 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004564
4565 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4566 // we are done.
4567 if (const RewriteBuffer *RewriteBuf =
4568 Rewrite.getRewriteBufferFor(MainFileID)) {
4569 //printf("Changed:\n");
4570 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4571 } else {
4572 fprintf(stderr, "No changes\n");
4573 }
Steve Narofface66252008-11-13 20:07:04 +00004574
Steve Naroff0aab7962008-11-14 14:10:01 +00004575 if (ClassImplementation.size() || CategoryImplementation.size()) {
4576 // Rewrite Objective-c meta data*
4577 std::string ResultStr;
4578 SynthesizeMetaDataIntoBuffer(ResultStr);
4579 // Emit metadata.
4580 *OutFile << ResultStr;
4581 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004582 OutFile->flush();
4583}
4584