blob: 878a94c1f1aaf48fefd9811d06fb370dacb74e62 [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.
314 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
315 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
Steve Naroff54055232008-10-27 17:20:55 +0000374void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
375 NamedDecl *D) {
376 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
377 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
378 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))
390 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
391}
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 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000739 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000740
741 // Get the start location and compute the semi location.
742 SourceLocation startLoc = ClassDecl->getLocation();
743 const char *startBuf = SM->getCharacterData(startLoc);
744 const char *semiPtr = strchr(startBuf, ';');
745
746 // Translate to typedef's that forward reference structs with the same name
747 // as the class. As a convenience, we include the original declaration
748 // as a comment.
749 std::string typedefString;
750 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000751 typedefString.append(startBuf, semiPtr-startBuf+1);
752 typedefString += "\n";
753 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000754 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000755 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000756 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000757 typedefString += "\n";
758 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000759 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000760 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000761 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000762 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000763 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000764 }
765
766 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000767 ReplaceText(startLoc, semiPtr-startBuf+1,
768 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000769}
770
Steve Naroffb29b4272008-04-14 22:03:09 +0000771void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000772 SourceLocation LocStart = Method->getLocStart();
773 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000774
Chris Lattner30fc9332009-02-04 01:06:56 +0000775 if (SM->getInstantiationLineNumber(LocEnd) >
776 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000777 InsertText(LocStart, "#if 0\n", 6);
778 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000779 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000780 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000781 }
782}
783
Steve Naroff6327e0d2009-01-11 01:06:09 +0000784void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000785{
Steve Naroff6327e0d2009-01-11 01:06:09 +0000786 SourceLocation Loc = prop->getLocation();
787
788 ReplaceText(Loc, 0, "// ", 3);
789
790 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000791}
792
Steve Naroffb29b4272008-04-14 22:03:09 +0000793void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000794 SourceLocation LocStart = CatDecl->getLocStart();
795
796 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000797 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000798
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000799 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000800 E = CatDecl->instmeth_end(); I != E; ++I)
801 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000802 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000803 E = CatDecl->classmeth_end(); I != E; ++I)
804 RewriteMethodDeclaration(*I);
805
Steve Naroff423cb562007-10-30 13:30:57 +0000806 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000807 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000808}
809
Steve Naroffb29b4272008-04-14 22:03:09 +0000810void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000811 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000812
Steve Naroff752d6ef2007-10-30 16:42:30 +0000813 SourceLocation LocStart = PDecl->getLocStart();
814
815 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000816 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000817
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000818 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000819 E = PDecl->instmeth_end(); I != E; ++I)
820 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000821 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000822 E = PDecl->classmeth_end(); I != E; ++I)
823 RewriteMethodDeclaration(*I);
824
Steve Naroff752d6ef2007-10-30 16:42:30 +0000825 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000826 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000827 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000828
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000829 // Must comment out @optional/@required
830 const char *startBuf = SM->getCharacterData(LocStart);
831 const char *endBuf = SM->getCharacterData(LocEnd);
832 for (const char *p = startBuf; p < endBuf; p++) {
833 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
834 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000835 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000836 ReplaceText(OptionalLoc, strlen("@optional"),
837 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000838
839 }
840 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
841 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000842 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000843 ReplaceText(OptionalLoc, strlen("@required"),
844 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000845
846 }
847 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000848}
849
Steve Naroffb29b4272008-04-14 22:03:09 +0000850void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000851 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000852 if (LocStart.isInvalid())
853 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000854 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000855 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000856}
857
Steve Naroffb29b4272008-04-14 22:03:09 +0000858void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000859 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000860 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000861 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000862 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000863 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000864 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000865 else if (OMD->getResultType()->isFunctionPointerType() ||
866 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000867 // needs special handling, since pointer-to-functions have special
868 // syntax (where a decaration models use).
869 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000870 QualType PointeeTy;
871 if (const PointerType* PT = retType->getAsPointerType())
872 PointeeTy = PT->getPointeeType();
873 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
874 PointeeTy = BPT->getPointeeType();
875 if ((FPRetType = PointeeTy->getAsFunctionType())) {
876 ResultStr += FPRetType->getResultType().getAsString();
877 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000878 }
879 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000880 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000881 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000882
883 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000884 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000885
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000886 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000887 NameStr += "_I_";
888 else
889 NameStr += "_C_";
890
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000891 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000892 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000893
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000894 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000895 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000896 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000897 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000898 }
Steve Naroff563b8282008-04-04 22:23:44 +0000899 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000900 {
901 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000902 int len = selString.size();
903 for (int i = 0; i < len; i++)
904 if (selString[i] == ':')
905 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000906 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000907 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000908 // Remember this name for metadata emission
909 MethodInternalNames[OMD] = NameStr;
910 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000911
912 // Rewrite arguments
913 ResultStr += "(";
914
915 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000916 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000917 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000918 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000919 if (!LangOpts.Microsoft) {
920 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
921 ResultStr += "struct ";
922 }
923 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000924 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000925 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000926 }
927 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000928 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000929
930 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000931 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000932 ResultStr += " _cmd";
933
934 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000935 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000936 ParmVarDecl *PDecl = OMD->getParamDecl(i);
937 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000938 if (PDecl->getType()->isObjCQualifiedIdType()) {
939 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000940 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000941 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000942 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000943 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000944 // Make sure we convert "t (^)(...)" to "t (*)(...)".
945 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
946 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
947 } else
948 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000949 ResultStr += Name;
950 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000951 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000952 if (OMD->isVariadic())
953 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000954 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000955
Steve Naroff76e429d2008-07-16 14:40:40 +0000956 if (FPRetType) {
957 ResultStr += ")"; // close the precedence "scope" for "*".
958
959 // Now, emit the argument types (if any).
960 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
961 ResultStr += "(";
962 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
963 if (i) ResultStr += ", ";
964 std::string ParamStr = FT->getArgType(i).getAsString();
965 ResultStr += ParamStr;
966 }
967 if (FT->isVariadic()) {
968 if (FT->getNumArgs()) ResultStr += ", ";
969 ResultStr += "...";
970 }
971 ResultStr += ")";
972 } else {
973 ResultStr += "()";
974 }
975 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000976}
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000977void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000978 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
979 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000980
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000981 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000982 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000983 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000984 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000985
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000986 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000987 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
988 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000989 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000990 ObjCMethodDecl *OMD = *I;
991 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000992 SourceLocation LocStart = OMD->getLocStart();
993 SourceLocation LocEnd = OMD->getBody()->getLocStart();
994
995 const char *startBuf = SM->getCharacterData(LocStart);
996 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000997 ReplaceText(LocStart, endBuf-startBuf,
998 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000999 }
1000
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001001 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001002 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1003 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001004 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 ObjCMethodDecl *OMD = *I;
1006 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001007 SourceLocation LocStart = OMD->getLocStart();
1008 SourceLocation LocEnd = OMD->getBody()->getLocStart();
1009
1010 const char *startBuf = SM->getCharacterData(LocStart);
1011 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001012 ReplaceText(LocStart, endBuf-startBuf,
1013 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001014 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001015 for (ObjCCategoryImplDecl::propimpl_iterator
1016 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1017 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001018 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001019 }
1020
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001021 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001022 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001023 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001024 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001025}
1026
Steve Naroffb29b4272008-04-14 22:03:09 +00001027void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001028 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001029 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001030 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001031 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001032 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001033 ResultStr += "\n";
1034 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001035 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001036 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001037 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001038 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001039 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001040 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001041 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001042 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001043 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001044
Steve Naroff6327e0d2009-01-11 01:06:09 +00001045 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1046 E = ClassDecl->prop_end(); I != E; ++I)
1047 RewriteProperty(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001048 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001049 E = ClassDecl->instmeth_end(); I != E; ++I)
1050 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001051 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001052 E = ClassDecl->classmeth_end(); I != E; ++I)
1053 RewriteMethodDeclaration(*I);
1054
Steve Naroff2feac5e2007-10-30 03:43:13 +00001055 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001056 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001057}
1058
Steve Naroffb619d952008-12-09 12:56:34 +00001059Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1060 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001061 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1062 // This allows us to reuse all the fun and games in SynthMessageExpr().
1063 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1064 ObjCMessageExpr *MsgExpr;
1065 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1066 llvm::SmallVector<Expr *, 1> ExprVec;
1067 ExprVec.push_back(newStmt);
1068
Steve Naroff8599e7a2008-12-08 16:43:47 +00001069 Stmt *Receiver = PropRefExpr->getBase();
1070 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1071 if (PRE && PropGetters[PRE]) {
1072 // This allows us to handle chain/nested property getters.
1073 Receiver = PropGetters[PRE];
1074 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001075 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001076 PDecl->getSetterName(), PDecl->getType(),
1077 PDecl->getSetterMethodDecl(),
1078 SourceLocation(), SourceLocation(),
1079 &ExprVec[0], 1);
1080 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1081
1082 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001083 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001084 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001085 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1086 // to things that stay around.
1087 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001088 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001089}
1090
Steve Naroffc77a6362008-12-04 16:24:46 +00001091Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001092 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1093 // This allows us to reuse all the fun and games in SynthMessageExpr().
1094 ObjCMessageExpr *MsgExpr;
1095 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1096
Steve Naroff8599e7a2008-12-08 16:43:47 +00001097 Stmt *Receiver = PropRefExpr->getBase();
1098
1099 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1100 if (PRE && PropGetters[PRE]) {
1101 // This allows us to handle chain/nested property getters.
1102 Receiver = PropGetters[PRE];
1103 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001104 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001105 PDecl->getGetterName(), PDecl->getType(),
1106 PDecl->getGetterMethodDecl(),
1107 SourceLocation(), SourceLocation(),
1108 0, 0);
1109
Steve Naroff4c3580e2008-12-04 23:50:32 +00001110 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001111
1112 if (!PropParentMap)
1113 PropParentMap = new ParentMap(CurrentBody);
1114
1115 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1116 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1117 // We stash away the ReplacingStmt since actually doing the
1118 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1119 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001120 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1121 // to things that stay around.
1122 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001123 return PropRefExpr; // return the original...
1124 } else {
1125 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001126 // delete PropRefExpr; elsewhere...
1127 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1128 // to things that stay around.
1129 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001130 return ReplacingStmt;
1131 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001132}
1133
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001134Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1135 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001136 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001137 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001138 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001139 ObjCInterfaceType *iFaceDecl =
1140 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001141 // lookup which class implements the instance variable.
1142 ObjCInterfaceDecl *clsDeclared = 0;
1143 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1144 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1145
1146 // Synthesize an explicit cast to gain access to the ivar.
1147 std::string RecName = clsDeclared->getIdentifier()->getName();
1148 RecName += "_IMPL";
1149 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001150 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001151 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001152 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1153 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001154 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1155 castT,SourceLocation(),
1156 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001157 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001158 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1159 IV->getBase()->getLocEnd(),
1160 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001161 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001162 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001163 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1164 IV->getLocation(),
1165 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001166 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001167 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001168 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001169 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001170
1171 ReplaceStmt(IV->getBase(), PE);
1172 // Cannot delete IV->getBase(), since PE points to it.
1173 // Replace the old base with the cast. This is important when doing
1174 // embedded rewrites. For example, [newInv->_container addObject:0].
1175 IV->setBase(PE);
1176 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001177 }
Steve Naroff84472a82008-04-18 21:55:08 +00001178 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001179 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1180
1181 // Explicit ivar refs need to have a cast inserted.
1182 // FIXME: consider sharing some of this code with the code above.
1183 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001184 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001185 // lookup which class implements the instance variable.
1186 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001187 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001188 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1189
1190 // Synthesize an explicit cast to gain access to the ivar.
1191 std::string RecName = clsDeclared->getIdentifier()->getName();
1192 RecName += "_IMPL";
1193 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001194 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001195 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001196 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1197 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001198 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1199 castT, SourceLocation(),
1200 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001201 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001202 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001203 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001204 ReplaceStmt(IV->getBase(), PE);
1205 // Cannot delete IV->getBase(), since PE points to it.
1206 // Replace the old base with the cast. This is important when doing
1207 // embedded rewrites. For example, [newInv->_container addObject:0].
1208 IV->setBase(PE);
1209 return IV;
1210 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001211 }
Steve Naroff84472a82008-04-18 21:55:08 +00001212 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001213}
1214
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001215/// SynthCountByEnumWithState - To print:
1216/// ((unsigned int (*)
1217/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1218/// (void *)objc_msgSend)((id)l_collection,
1219/// sel_registerName(
1220/// "countByEnumeratingWithState:objects:count:"),
1221/// &enumState,
1222/// (id *)items, (unsigned int)16)
1223///
Steve Naroffb29b4272008-04-14 22:03:09 +00001224void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001225 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1226 "id *, unsigned int))(void *)objc_msgSend)";
1227 buf += "\n\t\t";
1228 buf += "((id)l_collection,\n\t\t";
1229 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1230 buf += "\n\t\t";
1231 buf += "&enumState, "
1232 "(id *)items, (unsigned int)16)";
1233}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001234
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001235/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1236/// statement to exit to its outer synthesized loop.
1237///
Steve Naroffb29b4272008-04-14 22:03:09 +00001238Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001239 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1240 return S;
1241 // replace break with goto __break_label
1242 std::string buf;
1243
1244 SourceLocation startLoc = S->getLocStart();
1245 buf = "goto __break_label_";
1246 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001247 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001248
1249 return 0;
1250}
1251
1252/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1253/// statement to continue with its inner synthesized loop.
1254///
Steve Naroffb29b4272008-04-14 22:03:09 +00001255Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001256 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1257 return S;
1258 // replace continue with goto __continue_label
1259 std::string buf;
1260
1261 SourceLocation startLoc = S->getLocStart();
1262 buf = "goto __continue_label_";
1263 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001264 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001265
1266 return 0;
1267}
1268
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001269/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001270/// It rewrites:
1271/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001272
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001273/// Into:
1274/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001275/// type elem;
1276/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001277/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001278/// id l_collection = (id)collection;
1279/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1280/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001281/// if (limit) {
1282/// unsigned long startMutations = *enumState.mutationsPtr;
1283/// do {
1284/// unsigned long counter = 0;
1285/// do {
1286/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001287/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001288/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001289/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001290/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001291/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001292/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1293/// objects:items count:16]);
1294/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001295/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001296/// }
1297/// else
1298/// elem = nil;
1299/// }
1300///
Steve Naroffb29b4272008-04-14 22:03:09 +00001301Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001302 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001303 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1304 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1305 "ObjCForCollectionStmt Statement stack mismatch");
1306 assert(!ObjCBcLabelNo.empty() &&
1307 "ObjCForCollectionStmt - Label No stack empty");
1308
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001309 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001310 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001311 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001312 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001313 std::string buf;
1314 buf = "\n{\n\t";
1315 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1316 // type elem;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001317 NamedDecl* D = cast<NamedDecl>(DS->getSolitaryDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001318 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001319 elementTypeAsString = ElementType.getAsString();
1320 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001321 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001322 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001323 buf += elementName;
1324 buf += ";\n\t";
1325 }
Chris Lattner06767512008-04-08 05:52:18 +00001326 else {
1327 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001328 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001329 elementTypeAsString
1330 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001331 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001332
1333 // struct __objcFastEnumerationState enumState = { 0 };
1334 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1335 // id items[16];
1336 buf += "id items[16];\n\t";
1337 // id l_collection = (id)
1338 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001339 // Find start location of 'collection' the hard way!
1340 const char *startCollectionBuf = startBuf;
1341 startCollectionBuf += 3; // skip 'for'
1342 startCollectionBuf = strchr(startCollectionBuf, '(');
1343 startCollectionBuf++; // skip '('
1344 // find 'in' and skip it.
1345 while (*startCollectionBuf != ' ' ||
1346 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1347 (*(startCollectionBuf+3) != ' ' &&
1348 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1349 startCollectionBuf++;
1350 startCollectionBuf += 3;
1351
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001352 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001353 ReplaceText(startLoc, startCollectionBuf - startBuf,
1354 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001355 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001356 SourceLocation rightParenLoc = S->getRParenLoc();
1357 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1358 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001359 buf = ";\n\t";
1360
1361 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1362 // objects:items count:16];
1363 // which is synthesized into:
1364 // unsigned int limit =
1365 // ((unsigned int (*)
1366 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1367 // (void *)objc_msgSend)((id)l_collection,
1368 // sel_registerName(
1369 // "countByEnumeratingWithState:objects:count:"),
1370 // (struct __objcFastEnumerationState *)&state,
1371 // (id *)items, (unsigned int)16);
1372 buf += "unsigned long limit =\n\t\t";
1373 SynthCountByEnumWithState(buf);
1374 buf += ";\n\t";
1375 /// if (limit) {
1376 /// unsigned long startMutations = *enumState.mutationsPtr;
1377 /// do {
1378 /// unsigned long counter = 0;
1379 /// do {
1380 /// if (startMutations != *enumState.mutationsPtr)
1381 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001382 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001383 buf += "if (limit) {\n\t";
1384 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1385 buf += "do {\n\t\t";
1386 buf += "unsigned long counter = 0;\n\t\t";
1387 buf += "do {\n\t\t\t";
1388 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1389 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1390 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001391 buf += " = (";
1392 buf += elementTypeAsString;
1393 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001394 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001395 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001396
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001397 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001398 /// } while (counter < limit);
1399 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1400 /// objects:items count:16]);
1401 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001402 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001403 /// }
1404 /// else
1405 /// elem = nil;
1406 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001407 ///
1408 buf = ";\n\t";
1409 buf += "__continue_label_";
1410 buf += utostr(ObjCBcLabelNo.back());
1411 buf += ": ;";
1412 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001413 buf += "} while (counter < limit);\n\t";
1414 buf += "} while (limit = ";
1415 SynthCountByEnumWithState(buf);
1416 buf += ");\n\t";
1417 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001418 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001419 buf += "__break_label_";
1420 buf += utostr(ObjCBcLabelNo.back());
1421 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001422 buf += "}\n\t";
1423 buf += "else\n\t\t";
1424 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001425 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001426 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001427
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001428 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001429 if (isa<CompoundStmt>(S->getBody())) {
1430 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1431 InsertText(endBodyLoc, buf.c_str(), buf.size());
1432 } else {
1433 /* Need to treat single statements specially. For example:
1434 *
1435 * for (A *a in b) if (stuff()) break;
1436 * for (A *a in b) xxxyy;
1437 *
1438 * The following code simply scans ahead to the semi to find the actual end.
1439 */
1440 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1441 const char *semiBuf = strchr(stmtBuf, ';');
1442 assert(semiBuf && "Can't find ';'");
1443 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1444 InsertText(endBodyLoc, buf.c_str(), buf.size());
1445 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001446 Stmts.pop_back();
1447 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001448 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001449}
1450
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001451/// RewriteObjCSynchronizedStmt -
1452/// This routine rewrites @synchronized(expr) stmt;
1453/// into:
1454/// objc_sync_enter(expr);
1455/// @try stmt @finally { objc_sync_exit(expr); }
1456///
Steve Naroffb29b4272008-04-14 22:03:09 +00001457Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001458 // Get the start location and compute the semi location.
1459 SourceLocation startLoc = S->getLocStart();
1460 const char *startBuf = SM->getCharacterData(startLoc);
1461
1462 assert((*startBuf == '@') && "bogus @synchronized location");
1463
1464 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001465 buf = "objc_sync_enter((id)";
1466 const char *lparenBuf = startBuf;
1467 while (*lparenBuf != '(') lparenBuf++;
1468 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001469 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1470 // the sync expression is typically a message expression that's already
1471 // been rewritten! (which implies the SourceLocation's are invalid).
1472 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001473 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001474 while (*endBuf != ')') endBuf--;
1475 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001476 buf = ");\n";
1477 // declare a new scope with two variables, _stack and _rethrow.
1478 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1479 buf += "int buf[18/*32-bit i386*/];\n";
1480 buf += "char *pointers[4];} _stack;\n";
1481 buf += "id volatile _rethrow = 0;\n";
1482 buf += "objc_exception_try_enter(&_stack);\n";
1483 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001484 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001485 startLoc = S->getSynchBody()->getLocEnd();
1486 startBuf = SM->getCharacterData(startLoc);
1487
Steve Naroffc7089f12008-08-19 13:04:19 +00001488 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001489 SourceLocation lastCurlyLoc = startLoc;
1490 buf = "}\nelse {\n";
1491 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1492 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001493 buf += " objc_sync_exit(";
Ted Kremenek8189cde2009-02-07 01:47:29 +00001494 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1495 S->getSynchExpr(),
1496 Context->getObjCIdType(),
1497 SourceLocation(),
1498 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001499 std::string syncExprBufS;
1500 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001501 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001502 buf += syncExprBuf.str();
1503 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001504 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1505 buf += "}\n";
1506 buf += "}";
1507
Chris Lattneraadaf782008-01-31 19:51:04 +00001508 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001509 return 0;
1510}
1511
Steve Naroff8c565152008-12-05 17:03:39 +00001512void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1513 // Perform a bottom up traversal of all children.
1514 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1515 CI != E; ++CI)
1516 if (*CI)
1517 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1518
1519 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1520 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1521 Diags.Report(Context->getFullLoc(S->getLocStart()),
1522 TryFinallyContainsReturnDiag);
1523 }
1524 return;
1525}
1526
Steve Naroffb29b4272008-04-14 22:03:09 +00001527Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001528 // Get the start location and compute the semi location.
1529 SourceLocation startLoc = S->getLocStart();
1530 const char *startBuf = SM->getCharacterData(startLoc);
1531
1532 assert((*startBuf == '@') && "bogus @try location");
1533
1534 std::string buf;
1535 // declare a new scope with two variables, _stack and _rethrow.
1536 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1537 buf += "int buf[18/*32-bit i386*/];\n";
1538 buf += "char *pointers[4];} _stack;\n";
1539 buf += "id volatile _rethrow = 0;\n";
1540 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001541 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001542
Chris Lattneraadaf782008-01-31 19:51:04 +00001543 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001544
1545 startLoc = S->getTryBody()->getLocEnd();
1546 startBuf = SM->getCharacterData(startLoc);
1547
1548 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001549
Steve Naroff75730982007-11-07 04:08:17 +00001550 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001551 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1552 if (catchList) {
1553 startLoc = startLoc.getFileLocWithOffset(1);
1554 buf = " /* @catch begin */ else {\n";
1555 buf += " id _caught = objc_exception_extract(&_stack);\n";
1556 buf += " objc_exception_try_enter (&_stack);\n";
1557 buf += " if (_setjmp(_stack.buf))\n";
1558 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1559 buf += " else { /* @catch continue */";
1560
1561 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001562 } else { /* no catch list */
1563 buf = "}\nelse {\n";
1564 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1565 buf += "}";
1566 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001567 }
Steve Naroff75730982007-11-07 04:08:17 +00001568 bool sawIdTypedCatch = false;
1569 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001570 while (catchList) {
1571 Stmt *catchStmt = catchList->getCatchParamStmt();
1572
1573 if (catchList == S->getCatchStmts())
1574 buf = "if ("; // we are generating code for the first catch clause
1575 else
1576 buf = "else if (";
1577 startLoc = catchList->getLocStart();
1578 startBuf = SM->getCharacterData(startLoc);
1579
1580 assert((*startBuf == '@') && "bogus @catch location");
1581
1582 const char *lParenLoc = strchr(startBuf, '(');
1583
Steve Naroffbe4b3332008-02-01 22:08:12 +00001584 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001585 // Now rewrite the body...
1586 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001587 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1588 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001589 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1590 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001591 assert((*bodyBuf == '{') && "bogus @catch body location");
1592
1593 buf += "1) { id _tmp = _caught;";
1594 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1595 buf.c_str(), buf.size());
1596 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001597 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001598 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001599 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001600 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001601 sawIdTypedCatch = true;
1602 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001603 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001604
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001605 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001606 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001607 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001608 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001609 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001610 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001611 }
1612 }
1613 // Now rewrite the body...
1614 lastCatchBody = catchList->getCatchBody();
1615 SourceLocation rParenLoc = catchList->getRParenLoc();
1616 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1617 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1618 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1619 assert((*rParenBuf == ')') && "bogus @catch paren location");
1620 assert((*bodyBuf == '{') && "bogus @catch body location");
1621
1622 buf = " = _caught;";
1623 // Here we replace ") {" with "= _caught;" (which initializes and
1624 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001625 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001626 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001627 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001628 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001629 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001630 catchList = catchList->getNextCatchStmt();
1631 }
1632 // Complete the catch list...
1633 if (lastCatchBody) {
1634 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001635 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1636 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001637
Steve Naroff378f47a2008-09-11 15:29:03 +00001638 // Insert the last (implicit) else clause *before* the right curly brace.
1639 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1640 buf = "} /* last catch end */\n";
1641 buf += "else {\n";
1642 buf += " _rethrow = _caught;\n";
1643 buf += " objc_exception_try_exit(&_stack);\n";
1644 buf += "} } /* @catch end */\n";
1645 if (!S->getFinallyStmt())
1646 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001647 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001648
1649 // Set lastCurlyLoc
1650 lastCurlyLoc = lastCatchBody->getLocEnd();
1651 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001652 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001653 startLoc = finalStmt->getLocStart();
1654 startBuf = SM->getCharacterData(startLoc);
1655 assert((*startBuf == '@') && "bogus @finally start");
1656
1657 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001658 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001659
1660 Stmt *body = finalStmt->getFinallyBody();
1661 SourceLocation startLoc = body->getLocStart();
1662 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001663 assert(*SM->getCharacterData(startLoc) == '{' &&
1664 "bogus @finally body location");
1665 assert(*SM->getCharacterData(endLoc) == '}' &&
1666 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001667
1668 startLoc = startLoc.getFileLocWithOffset(1);
1669 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001670 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001671 endLoc = endLoc.getFileLocWithOffset(-1);
1672 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001673 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001674
1675 // Set lastCurlyLoc
1676 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001677
1678 // Now check for any return/continue/go statements within the @try.
1679 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001680 } else { /* no finally clause - make sure we synthesize an implicit one */
1681 buf = "{ /* implicit finally clause */\n";
1682 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1683 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1684 buf += "}";
1685 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001686 }
1687 // Now emit the final closing curly brace...
1688 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1689 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001690 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001691 return 0;
1692}
1693
Steve Naroffb29b4272008-04-14 22:03:09 +00001694Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001695 return 0;
1696}
1697
Steve Naroffb29b4272008-04-14 22:03:09 +00001698Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001699 return 0;
1700}
1701
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001702// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001703// the throw expression is typically a message expression that's already
1704// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001705Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001706 // Get the start location and compute the semi location.
1707 SourceLocation startLoc = S->getLocStart();
1708 const char *startBuf = SM->getCharacterData(startLoc);
1709
1710 assert((*startBuf == '@') && "bogus @throw location");
1711
1712 std::string buf;
1713 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001714 if (S->getThrowExpr())
1715 buf = "objc_exception_throw(";
1716 else // add an implicit argument
1717 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001718
1719 // handle "@ throw" correctly.
1720 const char *wBuf = strchr(startBuf, 'w');
1721 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1722 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1723
Steve Naroff2bd03922007-11-07 15:32:26 +00001724 const char *semiBuf = strchr(startBuf, ';');
1725 assert((*semiBuf == ';') && "@throw: can't find ';'");
1726 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1727 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001728 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001729 return 0;
1730}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001731
Steve Naroffb29b4272008-04-14 22:03:09 +00001732Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001733 // Create a new string expression.
1734 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001735 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001736 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001737 Expr *Replacement = new (Context) StringLiteral(*Context,StrEncoding.c_str(),
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001738 StrEncoding.length(), false, StrType,
Chris Lattner726e1682009-02-18 05:49:11 +00001739 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001740 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001741
Chris Lattner07506182007-11-30 22:53:43 +00001742 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001743 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001744 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001745}
1746
Steve Naroffb29b4272008-04-14 22:03:09 +00001747Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001748 if (!SelGetUidFunctionDecl)
1749 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001750 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1751 // Create a call to sel_registerName("selName").
1752 llvm::SmallVector<Expr*, 8> SelExprs;
1753 QualType argType = Context->getPointerType(Context->CharTy);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001754 SelExprs.push_back(new (Context) StringLiteral((*Context),
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001755 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001756 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001757 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001758 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1759 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001760 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001761 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001762 return SelExp;
1763}
1764
Steve Naroffb29b4272008-04-14 22:03:09 +00001765CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001766 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001767 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001768 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001769
1770 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001771 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001772
1773 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001774 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001775 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001776 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001777
1778 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001779
Ted Kremenek668bf912009-02-09 20:51:47 +00001780 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1781 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001782}
1783
Steve Naroffd5255f52007-11-01 13:24:47 +00001784static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1785 const char *&startRef, const char *&endRef) {
1786 while (startBuf < endBuf) {
1787 if (*startBuf == '<')
1788 startRef = startBuf; // mark the start.
1789 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001790 if (startRef && *startRef == '<') {
1791 endRef = startBuf; // mark the end.
1792 return true;
1793 }
1794 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001795 }
1796 startBuf++;
1797 }
1798 return false;
1799}
1800
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001801static void scanToNextArgument(const char *&argRef) {
1802 int angle = 0;
1803 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1804 if (*argRef == '<')
1805 angle++;
1806 else if (*argRef == '>')
1807 angle--;
1808 argRef++;
1809 }
1810 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1811}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001812
Steve Naroffb29b4272008-04-14 22:03:09 +00001813bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001814
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001815 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001816 return true;
1817
Steve Naroffd5255f52007-11-01 13:24:47 +00001818 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001819 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001820 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001821 return true; // we have "Class <Protocol> *".
1822 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001823 return false;
1824}
1825
Steve Naroff4f95b752008-07-29 18:15:38 +00001826void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1827 QualType Type = E->getType();
1828 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001829 SourceLocation Loc, EndLoc;
1830
1831 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1832 Loc = ECE->getLParenLoc();
1833 EndLoc = ECE->getRParenLoc();
1834 } else {
1835 Loc = E->getLocStart();
1836 EndLoc = E->getLocEnd();
1837 }
1838 // This will defend against trying to rewrite synthesized expressions.
1839 if (Loc.isInvalid() || EndLoc.isInvalid())
1840 return;
1841
Steve Naroff4f95b752008-07-29 18:15:38 +00001842 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001843 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001844 const char *startRef = 0, *endRef = 0;
1845 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1846 // Get the locations of the startRef, endRef.
1847 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1848 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1849 // Comment out the protocol references.
1850 InsertText(LessLoc, "/*", 2);
1851 InsertText(GreaterLoc, "*/", 2);
1852 }
1853 }
1854}
1855
Steve Naroffb29b4272008-04-14 22:03:09 +00001856void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001857 SourceLocation Loc;
1858 QualType Type;
1859 const FunctionTypeProto *proto = 0;
1860 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1861 Loc = VD->getLocation();
1862 Type = VD->getType();
1863 }
1864 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1865 Loc = FD->getLocation();
1866 // Check for ObjC 'id' and class types that have been adorned with protocol
1867 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1868 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1869 assert(funcType && "missing function type");
1870 proto = dyn_cast<FunctionTypeProto>(funcType);
1871 if (!proto)
1872 return;
1873 Type = proto->getResultType();
1874 }
1875 else
1876 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001877
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001878 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001879 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001880
1881 const char *endBuf = SM->getCharacterData(Loc);
1882 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001883 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001884 startBuf--; // scan backward (from the decl location) for return type.
1885 const char *startRef = 0, *endRef = 0;
1886 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1887 // Get the locations of the startRef, endRef.
1888 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1889 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1890 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001891 InsertText(LessLoc, "/*", 2);
1892 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001893 }
1894 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001895 if (!proto)
1896 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001897 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001898 const char *startBuf = SM->getCharacterData(Loc);
1899 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001900 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1901 if (needToScanForQualifiers(proto->getArgType(i))) {
1902 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001903
Steve Naroffd5255f52007-11-01 13:24:47 +00001904 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001905 // scan forward (from the decl location) for argument types.
1906 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001907 const char *startRef = 0, *endRef = 0;
1908 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1909 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001910 SourceLocation LessLoc =
1911 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1912 SourceLocation GreaterLoc =
1913 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001914 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001915 InsertText(LessLoc, "/*", 2);
1916 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001917 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001918 startBuf = ++endBuf;
1919 }
1920 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001921 // If the function name is derived from a macro expansion, then the
1922 // argument buffer will not follow the name. Need to speak with Chris.
1923 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001924 startBuf++; // scan forward (from the decl location) for argument types.
1925 startBuf++;
1926 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001927 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001928}
1929
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001930// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001931void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001932 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1933 llvm::SmallVector<QualType, 16> ArgTys;
1934 ArgTys.push_back(Context->getPointerType(
1935 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001936 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001937 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001938 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001939 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001940 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001941 SelGetUidIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001942 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001943}
1944
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001945// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001946void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001947 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1948 llvm::SmallVector<QualType, 16> ArgTys;
1949 ArgTys.push_back(Context->getPointerType(
1950 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001951 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001952 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001953 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001954 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001955 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001956 SelGetProtoIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001957 FunctionDecl::Extern, false);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001958}
1959
Steve Naroffb29b4272008-04-14 22:03:09 +00001960void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001961 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00001962 if (FD->getIdentifier() &&
1963 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001964 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001965 return;
1966 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001967 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001968}
1969
Steve Naroffc0a123c2008-03-11 17:37:02 +00001970// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001971void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001972 if (SuperContructorFunctionDecl)
1973 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00001974 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00001975 llvm::SmallVector<QualType, 16> ArgTys;
1976 QualType argT = Context->getObjCIdType();
1977 assert(!argT.isNull() && "Can't find 'id' type");
1978 ArgTys.push_back(argT);
1979 ArgTys.push_back(argT);
1980 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1981 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001982 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001983 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001984 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001985 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001986 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00001987}
1988
Steve Naroff09b266e2007-10-30 23:14:51 +00001989// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001990void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001991 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1992 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001993 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001994 assert(!argT.isNull() && "Can't find 'id' type");
1995 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001996 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001997 assert(!argT.isNull() && "Can't find 'SEL' type");
1998 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001999 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002000 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002001 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002002 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002003 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002004 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002005 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002006}
2007
Steve Naroff874e2322007-11-15 10:28:18 +00002008// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002009void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002010 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2011 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002012 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002013 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002014 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002015 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2016 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2017 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002018 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002019 assert(!argT.isNull() && "Can't find 'SEL' type");
2020 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002021 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002022 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002023 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002024 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002025 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002026 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002027 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002028}
2029
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002030// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002031void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002032 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2033 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002034 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002035 assert(!argT.isNull() && "Can't find 'id' type");
2036 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002037 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002038 assert(!argT.isNull() && "Can't find 'SEL' type");
2039 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002040 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002041 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002042 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002043 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002044 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002045 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002046 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002047}
2048
2049// SynthMsgSendSuperStretFunctionDecl -
2050// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002051void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002052 IdentifierInfo *msgSendIdent =
2053 &Context->Idents.get("objc_msgSendSuper_stret");
2054 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002055 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002056 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002057 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002058 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2059 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2060 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002061 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002062 assert(!argT.isNull() && "Can't find 'SEL' type");
2063 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002064 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002065 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002066 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002067 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002068 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002069 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002070 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002071}
2072
Steve Naroff1284db82008-05-08 22:02:18 +00002073// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002074void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002075 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2076 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002077 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002078 assert(!argT.isNull() && "Can't find 'id' type");
2079 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002080 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002081 assert(!argT.isNull() && "Can't find 'SEL' type");
2082 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002083 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002084 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002085 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002086 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002087 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002088 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002089 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002090}
2091
Steve Naroff09b266e2007-10-30 23:14:51 +00002092// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002093void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002094 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2095 llvm::SmallVector<QualType, 16> ArgTys;
2096 ArgTys.push_back(Context->getPointerType(
2097 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002098 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002099 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002100 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002101 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002102 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002103 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002104 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002105}
2106
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002107// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002108void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002109 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2110 llvm::SmallVector<QualType, 16> ArgTys;
2111 ArgTys.push_back(Context->getPointerType(
2112 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002113 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002114 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002115 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002116 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002117 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002118 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002119 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002120}
2121
Steve Naroffb29b4272008-04-14 22:03:09 +00002122Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002123 QualType strType = getConstantStringStructType();
2124
2125 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002126
2127 std::string tmpName = InFileName;
2128 unsigned i;
2129 for (i=0; i < tmpName.length(); i++) {
2130 char c = tmpName.at(i);
2131 // replace any non alphanumeric characters with '_'.
2132 if (!isalpha(c) && (c < '0' || c > '9'))
2133 tmpName[i] = '_';
2134 }
2135 S += tmpName;
2136 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002137 S += utostr(NumObjCStringLiterals++);
2138
Steve Naroffba92b2e2008-03-27 22:29:16 +00002139 Preamble += "static __NSConstantStringImpl " + S;
2140 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2141 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002142 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002143 std::string prettyBufS;
2144 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002145 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002146 Preamble += prettyBuf.str();
2147 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002148 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002149 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002150
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002151 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002152 &Context->Idents.get(S.c_str()), strType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002153 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002154 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2155 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002156 Context->getPointerType(DRE->getType()),
2157 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002158 // cast to NSConstantString *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002159 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002160 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002161 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002162 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002163 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002164}
2165
Steve Naroffb29b4272008-04-14 22:03:09 +00002166ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002167 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002168 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002169
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002170 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2171 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002172 assert(PT);
2173 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2174 return IT->getDecl();
2175 }
2176 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002177}
2178
2179// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002180QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002181 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002182 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002183 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002184 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002185 QualType FieldTypes[2];
2186
2187 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002188 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002189 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002190 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002191
Steve Naroff874e2322007-11-15 10:28:18 +00002192 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002193 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregor482b77d2009-01-12 23:27:07 +00002194 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002195 SourceLocation(), 0,
2196 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002197 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002198 }
Steve Naroff874e2322007-11-15 10:28:18 +00002199
Douglas Gregor44b43212008-12-11 16:49:14 +00002200 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002201 }
2202 return Context->getTagDeclType(SuperStructDecl);
2203}
2204
Steve Naroffb29b4272008-04-14 22:03:09 +00002205QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002206 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002207 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002208 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002209 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002210 QualType FieldTypes[4];
2211
2212 // struct objc_object *receiver;
2213 FieldTypes[0] = Context->getObjCIdType();
2214 // int flags;
2215 FieldTypes[1] = Context->IntTy;
2216 // char *str;
2217 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2218 // long length;
2219 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002220
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002221 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002222 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregor482b77d2009-01-12 23:27:07 +00002223 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
Douglas Gregor44b43212008-12-11 16:49:14 +00002224 ConstantStringDecl,
2225 SourceLocation(), 0,
2226 FieldTypes[i],
2227 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002228 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002229 }
2230
2231 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002232 }
2233 return Context->getTagDeclType(ConstantStringDecl);
2234}
2235
Steve Naroffb29b4272008-04-14 22:03:09 +00002236Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002237 if (!SelGetUidFunctionDecl)
2238 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002239 if (!MsgSendFunctionDecl)
2240 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002241 if (!MsgSendSuperFunctionDecl)
2242 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002243 if (!MsgSendStretFunctionDecl)
2244 SynthMsgSendStretFunctionDecl();
2245 if (!MsgSendSuperStretFunctionDecl)
2246 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002247 if (!MsgSendFpretFunctionDecl)
2248 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002249 if (!GetClassFunctionDecl)
2250 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002251 if (!GetMetaClassFunctionDecl)
2252 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002253
Steve Naroff874e2322007-11-15 10:28:18 +00002254 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002255 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2256 // May need to use objc_msgSend_stret() as well.
2257 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002258 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002259 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002260 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002261 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002262 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002263 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002264 }
Steve Naroff874e2322007-11-15 10:28:18 +00002265
Steve Naroff934f2762007-10-24 22:48:43 +00002266 // Synthesize a call to objc_msgSend().
2267 llvm::SmallVector<Expr*, 8> MsgExprs;
2268 IdentifierInfo *clsName = Exp->getClassName();
2269
2270 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2271 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002272 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2273 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002274 if (!strcmp(clsName->getName(), "super")) {
2275 MsgSendFlavor = MsgSendSuperFunctionDecl;
2276 if (MsgSendStretFlavor)
2277 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2278 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2279
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002280 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002281 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002282
2283 llvm::SmallVector<Expr*, 4> InitExprs;
2284
2285 // set the receiver to self, the first argument to all methods.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002286 InitExprs.push_back(new (Context) DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002287 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002288 Context->getObjCIdType(),
2289 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002290 llvm::SmallVector<Expr*, 8> ClsExprs;
2291 QualType argType = Context->getPointerType(Context->CharTy);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002292 ClsExprs.push_back(new (Context) StringLiteral(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002293 SuperDecl->getIdentifier()->getName(),
2294 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002295 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002296 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2297 &ClsExprs[0],
2298 ClsExprs.size());
2299 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002300 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002301 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002302 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002303 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002304 // struct objc_super
2305 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002306 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002307
Steve Naroff23f41272008-03-11 18:14:26 +00002308 if (LangOpts.Microsoft) {
2309 SynthSuperContructorFunctionDecl();
2310 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002311 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002312 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002313 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2314 InitExprs.size(),
2315 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002316 // The code for super is a little tricky to prevent collision with
2317 // the structure definition in the header. The rewriter has it's own
2318 // internal definition (__rw_objc_super) that is uses. This is why
2319 // we need the cast below. For example:
2320 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2321 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002322 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002323 Context->getPointerType(SuperRep->getType()),
2324 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002325 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002326 SuperRep, Context->getPointerType(superType),
2327 SourceLocation(), SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002328 } else {
2329 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002330 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroff23f41272008-03-11 18:14:26 +00002331 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002332 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002333 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner418f6c72008-10-26 23:43:26 +00002334 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002335 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002336 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002337 Context->getPointerType(SuperRep->getType()),
2338 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002339 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002340 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002341 } else {
2342 llvm::SmallVector<Expr*, 8> ClsExprs;
2343 QualType argType = Context->getPointerType(Context->CharTy);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002344 ClsExprs.push_back(new (Context) StringLiteral(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002345 clsName->getName(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002346 clsName->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002347 false, argType, 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);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002374 ClsExprs.push_back(new (Context) StringLiteral(*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);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002432 SelExprs.push_back(new (Context) StringLiteral(*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());
2477 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002478 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002479 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002480 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2481 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002482 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002483 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002484 if (isTopLevelBlockPointerType(t)) {
Steve Naroffa206b062008-10-29 14:49:46 +00002485 const BlockPointerType *BPT = t->getAsBlockPointerType();
2486 t = Context->getPointerType(BPT->getPointeeType());
2487 }
Steve Naroff352336b2007-11-05 14:36:37 +00002488 ArgTypes.push_back(t);
2489 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002490 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2491 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002492 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002493 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002494 }
2495 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002496 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002497
2498 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002499 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002500 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002501
2502 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2503 // If we don't do this cast, we get the following bizarre warning/note:
2504 // xx.m:13: warning: function called through a non-compatible type
2505 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek8189cde2009-02-07 01:47:29 +00002506 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002507 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002508 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002509
Steve Naroffab972d32007-11-04 22:37:50 +00002510 // Now do the "normal" pointer to function cast.
2511 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002512 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002513 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002514 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002515 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002516 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002517
2518 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002519 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002520
2521 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002522 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2523 MsgExprs.size(),
2524 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002525 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002526 if (MsgSendStretFlavor) {
2527 // We have the method which returns a struct/union. Must also generate
2528 // call to objc_msgSend_stret and hang both varieties on a conditional
2529 // expression which dictate which one to envoke depending on size of
2530 // method's return type.
2531
2532 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002533 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002534 SourceLocation());
2535 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek8189cde2009-02-07 01:47:29 +00002536 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002537 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002538 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002539 // Now do the "normal" pointer to function cast.
2540 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002541 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002542 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002543 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002544 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002545
2546 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002547 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002548
2549 FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002550 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2551 MsgExprs.size(),
2552 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002553
2554 // Build sizeof(returnType)
Ted Kremenek8189cde2009-02-07 01:47:29 +00002555 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true, true,
Sebastian Redl05189992008-11-11 17:56:53 +00002556 returnType.getAsOpaquePtr(),
2557 Context->getSizeType(),
2558 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002559 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2560 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2561 // For X86 it is more complicated and some kind of target specific routine
2562 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002563 unsigned IntSize =
2564 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek8189cde2009-02-07 01:47:29 +00002565 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002566 Context->IntTy,
2567 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002568 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002569 BinaryOperator::LE,
2570 Context->IntTy,
2571 SourceLocation());
2572 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2573 ConditionalOperator *CondExpr =
Ted Kremenek8189cde2009-02-07 01:47:29 +00002574 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2575 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002576 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002577 return ReplacingStmt;
2578}
2579
Steve Naroffb29b4272008-04-14 22:03:09 +00002580Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002581 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002582
Steve Naroffc77a6362008-12-04 16:24:46 +00002583 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002584 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002585 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002586
Steve Naroff4c3580e2008-12-04 23:50:32 +00002587 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002588 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002589}
2590
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002591/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2592/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002593Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002594 if (!GetProtocolFunctionDecl)
2595 SynthGetProtocolFunctionDecl();
2596 // Create a call to objc_getProtocol("ProtocolName").
2597 llvm::SmallVector<Expr*, 8> ProtoExprs;
2598 QualType argType = Context->getPointerType(Context->CharTy);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002599 ProtoExprs.push_back(new (Context)
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002600 StringLiteral(*Context,
2601 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 Lattner3db6cae2008-07-21 18:19:38 +00002698 if (!CDecl->getReferencedProtocols().empty()) {
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()) {
2874 unsigned NumMethods = PDecl->getNumInstanceMethods();
2875 /* struct _objc_protocol_method_list {
2876 int protocol_method_count;
2877 struct protocol_methods protocols[];
2878 }
2879 */
2880 Result += "\nstatic struct {\n";
2881 Result += "\tint protocol_method_count;\n";
2882 Result += "\tstruct protocol_methods protocols[";
2883 Result += utostr(NumMethods);
2884 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002885 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002886 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2887 "{\n\t" + utostr(NumMethods) + "\n";
2888
2889 // Output instance methods declared in this protocol.
2890 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2891 E = PDecl->instmeth_end(); I != E; ++I) {
2892 if (I == PDecl->instmeth_begin())
2893 Result += "\t ,{{(SEL)\"";
2894 else
2895 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002896 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002897 std::string MethodTypeString;
2898 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2899 Result += "\", \"";
2900 Result += MethodTypeString;
2901 Result += "\"}\n";
2902 }
2903 Result += "\t }\n};\n";
2904 }
2905
2906 // Output class methods declared in this protocol.
2907 int NumMethods = PDecl->getNumClassMethods();
2908 if (NumMethods > 0) {
2909 /* struct _objc_protocol_method_list {
2910 int protocol_method_count;
2911 struct protocol_methods protocols[];
2912 }
2913 */
2914 Result += "\nstatic struct {\n";
2915 Result += "\tint protocol_method_count;\n";
2916 Result += "\tstruct protocol_methods protocols[";
2917 Result += utostr(NumMethods);
2918 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002919 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002920 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2921 "{\n\t";
2922 Result += utostr(NumMethods);
2923 Result += "\n";
2924
2925 // Output instance methods declared in this protocol.
2926 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2927 E = PDecl->classmeth_end(); I != E; ++I) {
2928 if (I == PDecl->classmeth_begin())
2929 Result += "\t ,{{(SEL)\"";
2930 else
2931 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002932 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002933 std::string MethodTypeString;
2934 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2935 Result += "\", \"";
2936 Result += MethodTypeString;
2937 Result += "\"}\n";
2938 }
2939 Result += "\t }\n};\n";
2940 }
2941
2942 // Output:
2943 /* struct _objc_protocol {
2944 // Objective-C 1.0 extensions
2945 struct _objc_protocol_extension *isa;
2946 char *protocol_name;
2947 struct _objc_protocol **protocol_list;
2948 struct _objc_protocol_method_list *instance_methods;
2949 struct _objc_protocol_method_list *class_methods;
2950 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002951 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002952 static bool objc_protocol = false;
2953 if (!objc_protocol) {
2954 Result += "\nstruct _objc_protocol {\n";
2955 Result += "\tstruct _objc_protocol_extension *isa;\n";
2956 Result += "\tchar *protocol_name;\n";
2957 Result += "\tstruct _objc_protocol **protocol_list;\n";
2958 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2959 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2960 Result += "};\n";
2961
2962 objc_protocol = true;
2963 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002964
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002965 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002966 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002967 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2968 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002969 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002970 Result += "\", 0, ";
2971 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2972 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002973 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002974 Result += ", ";
2975 }
2976 else
2977 Result += "0, ";
2978 if (PDecl->getNumClassMethods() > 0) {
2979 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002980 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002981 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002982 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002983 else
2984 Result += "0\n";
2985 Result += "};\n";
2986
2987 // Mark this protocol as having been generated.
2988 if (!ObjCSynthesizedProtocols.insert(PDecl))
2989 assert(false && "protocol already synthesized");
2990 }
2991 // Output the top lovel protocol meta-data for the class.
2992 /* struct _objc_protocol_list {
2993 struct _objc_protocol_list *next;
2994 int protocol_count;
2995 struct _objc_protocol *class_protocols[];
2996 }
2997 */
2998 Result += "\nstatic struct {\n";
2999 Result += "\tstruct _objc_protocol_list *next;\n";
3000 Result += "\tint protocol_count;\n";
3001 Result += "\tstruct _objc_protocol *class_protocols[";
3002 Result += utostr(Protocols.size());
3003 Result += "];\n} _OBJC_";
3004 Result += prefix;
3005 Result += "_PROTOCOLS_";
3006 Result += ClassName;
3007 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3008 "{\n\t0, ";
3009 Result += utostr(Protocols.size());
3010 Result += "\n";
3011
3012 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003013 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003014 Result += " \n";
3015
3016 for (unsigned i = 1; i != Protocols.size(); i++) {
3017 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003018 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003019 Result += "\n";
3020 }
3021 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003022}
3023
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003024/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003025/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003026void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003027 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003028 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003029 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003030 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003031 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3032 CDecl = CDecl->getNextClassCategory())
3033 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3034 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003035
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003036 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003037 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003038 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003039
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003040 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003041 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003042 true, "CATEGORY_", FullCategoryName.c_str(),
3043 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003044
3045 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003046 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003047 false, "CATEGORY_", FullCategoryName.c_str(),
3048 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003049
3050 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003051 // Null CDecl is case of a category implementation with no category interface
3052 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003053 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003054 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003055
3056 /* struct _objc_category {
3057 char *category_name;
3058 char *class_name;
3059 struct _objc_method_list *instance_methods;
3060 struct _objc_method_list *class_methods;
3061 struct _objc_protocol_list *protocols;
3062 // Objective-C 1.0 extensions
3063 uint32_t size; // sizeof (struct _objc_category)
3064 struct _objc_property_list *instance_properties; // category's own
3065 // @property decl.
3066 };
3067 */
3068
3069 static bool objc_category = false;
3070 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003071 Result += "\nstruct _objc_category {\n";
3072 Result += "\tchar *category_name;\n";
3073 Result += "\tchar *class_name;\n";
3074 Result += "\tstruct _objc_method_list *instance_methods;\n";
3075 Result += "\tstruct _objc_method_list *class_methods;\n";
3076 Result += "\tstruct _objc_protocol_list *protocols;\n";
3077 Result += "\tunsigned int size;\n";
3078 Result += "\tstruct _objc_property_list *instance_properties;\n";
3079 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003080 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003081 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003082 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3083 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003084 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003085 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003086 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003087 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003088 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003089
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003090 if (IDecl->getNumInstanceMethods() > 0) {
3091 Result += "\t, (struct _objc_method_list *)"
3092 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3093 Result += FullCategoryName;
3094 Result += "\n";
3095 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003096 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003097 Result += "\t, 0\n";
3098 if (IDecl->getNumClassMethods() > 0) {
3099 Result += "\t, (struct _objc_method_list *)"
3100 "&_OBJC_CATEGORY_CLASS_METHODS_";
3101 Result += FullCategoryName;
3102 Result += "\n";
3103 }
3104 else
3105 Result += "\t, 0\n";
3106
Chris Lattner780f3292008-07-21 21:32:27 +00003107 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003108 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3109 Result += FullCategoryName;
3110 Result += "\n";
3111 }
3112 else
3113 Result += "\t, 0\n";
3114 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003115}
3116
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003117/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3118/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003119void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003120 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003121 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003122 if (ivar->isBitField()) {
3123 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3124 // place all bitfields at offset 0.
3125 Result += "0";
3126 } else {
3127 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003128 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003129 if (LangOpts.Microsoft)
3130 Result += "_IMPL";
3131 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003132 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003133 Result += ")";
3134 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003135}
3136
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003137//===----------------------------------------------------------------------===//
3138// Meta Data Emission
3139//===----------------------------------------------------------------------===//
3140
Steve Naroffb29b4272008-04-14 22:03:09 +00003141void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003142 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003143 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003144
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003145 // Explictly declared @interface's are already synthesized.
3146 if (CDecl->ImplicitInterfaceDecl()) {
3147 // FIXME: Implementation of a class with no @interface (legacy) doese not
3148 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003149 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003150 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003151
Chris Lattnerbe6df082007-12-12 07:56:42 +00003152 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003153 unsigned NumIvars = !IDecl->ivar_empty()
3154 ? IDecl->ivar_size()
3155 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003156 if (NumIvars > 0) {
3157 static bool objc_ivar = false;
3158 if (!objc_ivar) {
3159 /* struct _objc_ivar {
3160 char *ivar_name;
3161 char *ivar_type;
3162 int ivar_offset;
3163 };
3164 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003165 Result += "\nstruct _objc_ivar {\n";
3166 Result += "\tchar *ivar_name;\n";
3167 Result += "\tchar *ivar_type;\n";
3168 Result += "\tint ivar_offset;\n";
3169 Result += "};\n";
3170
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003171 objc_ivar = true;
3172 }
3173
Steve Naroff946a6932008-03-11 00:12:29 +00003174 /* struct {
3175 int ivar_count;
3176 struct _objc_ivar ivar_list[nIvars];
3177 };
3178 */
3179 Result += "\nstatic struct {\n";
3180 Result += "\tint ivar_count;\n";
3181 Result += "\tstruct _objc_ivar ivar_list[";
3182 Result += utostr(NumIvars);
3183 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003184 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003185 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003186 "{\n\t";
3187 Result += utostr(NumIvars);
3188 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003189
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003190 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003191 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003192 IVI = IDecl->ivar_begin();
3193 IVE = IDecl->ivar_end();
3194 } else {
3195 IVI = CDecl->ivar_begin();
3196 IVE = CDecl->ivar_end();
3197 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003198 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003199 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003200 Result += "\", \"";
3201 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003202 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003203 Result += StrEncoding;
3204 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003205 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003206 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003207 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003208 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003209 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003210 Result += "\", \"";
3211 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003212 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003213 Result += StrEncoding;
3214 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003215 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003216 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003217 }
3218
3219 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003220 }
3221
3222 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003223 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003224 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003225
3226 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003227 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003228 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003229
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003230 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003231 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003232 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003233
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003234
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003235 // Declaration of class/meta-class metadata
3236 /* struct _objc_class {
3237 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003238 const char *super_class_name;
3239 char *name;
3240 long version;
3241 long info;
3242 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003243 struct _objc_ivar_list *ivars;
3244 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003245 struct objc_cache *cache;
3246 struct objc_protocol_list *protocols;
3247 const char *ivar_layout;
3248 struct _objc_class_ext *ext;
3249 };
3250 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003251 static bool objc_class = false;
3252 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003253 Result += "\nstruct _objc_class {\n";
3254 Result += "\tstruct _objc_class *isa;\n";
3255 Result += "\tconst char *super_class_name;\n";
3256 Result += "\tchar *name;\n";
3257 Result += "\tlong version;\n";
3258 Result += "\tlong info;\n";
3259 Result += "\tlong instance_size;\n";
3260 Result += "\tstruct _objc_ivar_list *ivars;\n";
3261 Result += "\tstruct _objc_method_list *methods;\n";
3262 Result += "\tstruct objc_cache *cache;\n";
3263 Result += "\tstruct _objc_protocol_list *protocols;\n";
3264 Result += "\tconst char *ivar_layout;\n";
3265 Result += "\tstruct _objc_class_ext *ext;\n";
3266 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003267 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003268 }
3269
3270 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003271 ObjCInterfaceDecl *RootClass = 0;
3272 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003273 while (SuperClass) {
3274 RootClass = SuperClass;
3275 SuperClass = SuperClass->getSuperClass();
3276 }
3277 SuperClass = CDecl->getSuperClass();
3278
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003279 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003280 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003281 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003282 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003283 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003284 Result += "\"";
3285
3286 if (SuperClass) {
3287 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003288 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003289 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003290 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003291 Result += "\"";
3292 }
3293 else {
3294 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003295 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003296 Result += "\"";
3297 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003298 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003299 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003300 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003301 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003302 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003303 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003304 Result += "\n";
3305 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003306 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003307 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003308 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003309 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003310 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003311 Result += ",0,0\n";
3312 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003313 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003314 Result += "\t,0,0,0,0\n";
3315 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003316
3317 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003318 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003319 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003320 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003321 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003322 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003323 if (SuperClass) {
3324 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003325 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003326 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003327 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003328 Result += "\"";
3329 }
3330 else {
3331 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003332 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003333 Result += "\"";
3334 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003335 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003336 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003337 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003338 Result += ",0";
3339 else {
3340 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003341 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003342 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003343 if (LangOpts.Microsoft)
3344 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003345 Result += ")";
3346 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003347 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003348 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003349 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003350 Result += "\n\t";
3351 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003352 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003353 Result += ",0";
3354 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003355 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003356 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003357 Result += ", 0\n\t";
3358 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003359 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003360 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003361 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003362 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003363 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003364 Result += ", 0,0\n";
3365 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003366 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003367 Result += ",0,0,0\n";
3368 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003369}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003370
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003371/// RewriteImplementations - This routine rewrites all method implementations
3372/// and emits meta-data.
3373
Steve Narofface66252008-11-13 20:07:04 +00003374void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003375 int ClsDefCount = ClassImplementation.size();
3376 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003377
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003378 // Rewrite implemented methods
3379 for (int i = 0; i < ClsDefCount; i++)
3380 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003381
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003382 for (int i = 0; i < CatDefCount; i++)
3383 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003384}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003385
Steve Narofface66252008-11-13 20:07:04 +00003386void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3387 int ClsDefCount = ClassImplementation.size();
3388 int CatDefCount = CategoryImplementation.size();
3389
Steve Naroff5df5b762008-05-07 21:23:49 +00003390 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003391 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003392 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003393 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003394 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003395
3396 // For each implemented category, write out all its meta data.
3397 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003398 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003399
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003400 // Write objc_symtab metadata
3401 /*
3402 struct _objc_symtab
3403 {
3404 long sel_ref_cnt;
3405 SEL *refs;
3406 short cls_def_cnt;
3407 short cat_def_cnt;
3408 void *defs[cls_def_cnt + cat_def_cnt];
3409 };
3410 */
3411
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003412 Result += "\nstruct _objc_symtab {\n";
3413 Result += "\tlong sel_ref_cnt;\n";
3414 Result += "\tSEL *refs;\n";
3415 Result += "\tshort cls_def_cnt;\n";
3416 Result += "\tshort cat_def_cnt;\n";
3417 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3418 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003419
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003420 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003421 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003422 Result += "\t0, 0, " + utostr(ClsDefCount)
3423 + ", " + utostr(CatDefCount) + "\n";
3424 for (int i = 0; i < ClsDefCount; i++) {
3425 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003426 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003427 Result += "\n";
3428 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003429
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003430 for (int i = 0; i < CatDefCount; i++) {
3431 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003432 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003433 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003434 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003435 Result += "\n";
3436 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003437
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003438 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003439
3440 // Write objc_module metadata
3441
3442 /*
3443 struct _objc_module {
3444 long version;
3445 long size;
3446 const char *name;
3447 struct _objc_symtab *symtab;
3448 }
3449 */
3450
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003451 Result += "\nstruct _objc_module {\n";
3452 Result += "\tlong version;\n";
3453 Result += "\tlong size;\n";
3454 Result += "\tconst char *name;\n";
3455 Result += "\tstruct _objc_symtab *symtab;\n";
3456 Result += "};\n\n";
3457 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003458 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003459 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3460 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003461 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003462
3463 if (LangOpts.Microsoft) {
3464 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003465 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003466 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3467 Result += "&_OBJC_MODULES;\n";
3468 Result += "#pragma data_seg(pop)\n\n";
3469 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003470}
Chris Lattner311ff022007-10-16 22:36:42 +00003471
Steve Naroff54055232008-10-27 17:20:55 +00003472std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3473 const char *funcName,
3474 std::string Tag) {
3475 const FunctionType *AFT = CE->getFunctionType();
3476 QualType RT = AFT->getResultType();
3477 std::string StructRef = "struct " + Tag;
3478 std::string S = "static " + RT.getAsString() + " __" +
3479 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003480
Steve Naroff54055232008-10-27 17:20:55 +00003481 BlockDecl *BD = CE->getBlockDecl();
3482
3483 if (isa<FunctionTypeNoProto>(AFT)) {
Steve Naroffdf8570d2009-02-02 17:19:26 +00003484 // No user-supplied arguments. Still need to pass in a pointer to the
3485 // block (to reference imported block decl refs).
3486 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003487 } else if (BD->param_empty()) {
3488 S += "(" + StructRef + " *__cself)";
3489 } else {
3490 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3491 assert(FT && "SynthesizeBlockFunc: No function proto");
3492 S += '(';
3493 // first add the implicit argument.
3494 S += StructRef + " *__cself, ";
3495 std::string ParamStr;
3496 for (BlockDecl::param_iterator AI = BD->param_begin(),
3497 E = BD->param_end(); AI != E; ++AI) {
3498 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003499 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003500 (*AI)->getType().getAsStringInternal(ParamStr);
3501 S += ParamStr;
3502 }
3503 if (FT->isVariadic()) {
3504 if (!BD->param_empty()) S += ", ";
3505 S += "...";
3506 }
3507 S += ')';
3508 }
3509 S += " {\n";
3510
3511 // Create local declarations to avoid rewriting all closure decl ref exprs.
3512 // First, emit a declaration for all "by ref" decls.
3513 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3514 E = BlockByRefDecls.end(); I != E; ++I) {
3515 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003516 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003517 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003518 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003519 }
3520 // Next, emit a declaration for all "by copy" declarations.
3521 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3522 E = BlockByCopyDecls.end(); I != E; ++I) {
3523 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003524 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003525 // Handle nested closure invocation. For example:
3526 //
3527 // void (^myImportedClosure)(void);
3528 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3529 //
3530 // void (^anotherClosure)(void);
3531 // anotherClosure = ^(void) {
3532 // myImportedClosure(); // import and invoke the closure
3533 // };
3534 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003535 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003536 S += "struct __block_impl *";
3537 else
3538 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003539 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003540 }
3541 std::string RewrittenStr = RewrittenBlockExprs[CE];
3542 const char *cstr = RewrittenStr.c_str();
3543 while (*cstr++ != '{') ;
3544 S += cstr;
3545 S += "\n";
3546 return S;
3547}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003548
Steve Naroff54055232008-10-27 17:20:55 +00003549std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3550 const char *funcName,
3551 std::string Tag) {
3552 std::string StructRef = "struct " + Tag;
3553 std::string S = "static void __";
3554
3555 S += funcName;
3556 S += "_block_copy_" + utostr(i);
3557 S += "(" + StructRef;
3558 S += "*dst, " + StructRef;
3559 S += "*src) {";
3560 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3561 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003562 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003563 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003564 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003565 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003566 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff54055232008-10-27 17:20:55 +00003567 }
3568 S += "\nstatic void __";
3569 S += funcName;
3570 S += "_block_dispose_" + utostr(i);
3571 S += "(" + StructRef;
3572 S += "*src) {";
3573 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3574 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003575 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003576 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003577 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003578 }
3579 S += "}\n";
3580 return S;
3581}
3582
3583std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3584 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003585 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003586 std::string Constructor = " " + Tag;
3587
3588 S += " {\n struct __block_impl impl;\n";
3589
3590 if (hasCopyDisposeHelpers)
3591 S += " void *copy;\n void *dispose;\n";
3592
3593 Constructor += "(void *fp";
3594
3595 if (hasCopyDisposeHelpers)
3596 Constructor += ", void *copyHelp, void *disposeHelp";
3597
3598 if (BlockDeclRefs.size()) {
3599 // Output all "by copy" declarations.
3600 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3601 E = BlockByCopyDecls.end(); I != E; ++I) {
3602 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003603 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003604 std::string ArgName = "_" + FieldName;
3605 // Handle nested closure invocation. For example:
3606 //
3607 // void (^myImportedBlock)(void);
3608 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3609 //
3610 // void (^anotherBlock)(void);
3611 // anotherBlock = ^(void) {
3612 // myImportedBlock(); // import and invoke the closure
3613 // };
3614 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003615 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003616 S += "struct __block_impl *";
3617 Constructor += ", void *" + ArgName;
3618 } else {
3619 (*I)->getType().getAsStringInternal(FieldName);
3620 (*I)->getType().getAsStringInternal(ArgName);
3621 Constructor += ", " + ArgName;
3622 }
3623 S += FieldName + ";\n";
3624 }
3625 // Output all "by ref" declarations.
3626 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3627 E = BlockByRefDecls.end(); I != E; ++I) {
3628 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003629 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003630 std::string ArgName = "_" + FieldName;
3631 // Handle nested closure invocation. For example:
3632 //
3633 // void (^myImportedBlock)(void);
3634 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3635 //
3636 // void (^anotherBlock)(void);
3637 // anotherBlock = ^(void) {
3638 // myImportedBlock(); // import and invoke the closure
3639 // };
3640 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003641 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003642 S += "struct __block_impl *";
3643 Constructor += ", void *" + ArgName;
3644 } else {
3645 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3646 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3647 Constructor += ", " + ArgName;
3648 }
3649 S += FieldName + "; // by ref\n";
3650 }
3651 // Finish writing the constructor.
3652 // FIXME: handle NSConcreteGlobalBlock.
3653 Constructor += ", int flags=0) {\n";
3654 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3655 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3656
3657 if (hasCopyDisposeHelpers)
3658 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3659
3660 // Initialize all "by copy" arguments.
3661 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3662 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003663 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003664 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003665 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003666 Constructor += Name + " = (struct __block_impl *)_";
3667 else
3668 Constructor += Name + " = _";
3669 Constructor += Name + ";\n";
3670 }
3671 // Initialize all "by ref" arguments.
3672 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3673 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003674 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003675 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003676 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003677 Constructor += Name + " = (struct __block_impl *)_";
3678 else
3679 Constructor += Name + " = _";
3680 Constructor += Name + ";\n";
3681 }
3682 } else {
3683 // Finish writing the constructor.
3684 // FIXME: handle NSConcreteGlobalBlock.
3685 Constructor += ", int flags=0) {\n";
3686 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3687 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3688 if (hasCopyDisposeHelpers)
3689 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3690 }
3691 Constructor += " ";
3692 Constructor += "}\n";
3693 S += Constructor;
3694 S += "};\n";
3695 return S;
3696}
3697
3698void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3699 const char *FunName) {
3700 // Insert closures that were part of the function.
3701 for (unsigned i = 0; i < Blocks.size(); i++) {
3702
3703 CollectBlockDeclRefInfo(Blocks[i]);
3704
3705 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3706
3707 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3708 ImportedBlockDecls.size() > 0);
3709
3710 InsertText(FunLocStart, CI.c_str(), CI.size());
3711
3712 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3713
3714 InsertText(FunLocStart, CF.c_str(), CF.size());
3715
3716 if (ImportedBlockDecls.size()) {
3717 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3718 InsertText(FunLocStart, HF.c_str(), HF.size());
3719 }
3720
3721 BlockDeclRefs.clear();
3722 BlockByRefDecls.clear();
3723 BlockByCopyDecls.clear();
3724 BlockCallExprs.clear();
3725 ImportedBlockDecls.clear();
3726 }
3727 Blocks.clear();
3728 RewrittenBlockExprs.clear();
3729}
3730
3731void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3732 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003733 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003734
3735 SynthesizeBlockLiterals(FunLocStart, FuncName);
3736}
3737
3738void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003739 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3740 //SourceLocation FunLocStart = MD->getLocStart();
3741 // FIXME: This hack works around a bug in Rewrite.InsertText().
3742 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003743 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003744 // Convert colons to underscores.
3745 std::string::size_type loc = 0;
3746 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3747 FuncName.replace(loc, 1, "_");
3748
3749 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3750}
3751
3752void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3753 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3754 CI != E; ++CI)
3755 if (*CI) {
3756 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3757 GetBlockDeclRefExprs(CBE->getBody());
3758 else
3759 GetBlockDeclRefExprs(*CI);
3760 }
3761 // Handle specific things.
3762 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3763 // FIXME: Handle enums.
3764 if (!isa<FunctionDecl>(CDRE->getDecl()))
3765 BlockDeclRefs.push_back(CDRE);
3766 return;
3767}
3768
3769void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3770 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3771 CI != E; ++CI)
3772 if (*CI) {
3773 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3774 GetBlockCallExprs(CBE->getBody());
3775 else
3776 GetBlockCallExprs(*CI);
3777 }
3778
3779 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3780 if (CE->getCallee()->getType()->isBlockPointerType()) {
3781 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3782 }
3783 }
3784 return;
3785}
3786
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003787Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003788 // Navigate to relevant type information.
3789 const char *closureName = 0;
3790 const BlockPointerType *CPT = 0;
3791
3792 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003793 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003794 CPT = DRE->getType()->getAsBlockPointerType();
3795 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003796 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003797 CPT = CDRE->getType()->getAsBlockPointerType();
3798 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003799 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003800 CPT = MExpr->getType()->getAsBlockPointerType();
3801 } else {
3802 assert(1 && "RewriteBlockClass: Bad type");
3803 }
3804 assert(CPT && "RewriteBlockClass: Bad type");
3805 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3806 assert(FT && "RewriteBlockClass: Bad type");
3807 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3808 // FTP will be null for closures that don't take arguments.
3809
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003810 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3811 SourceLocation(),
3812 &Context->Idents.get("__block_impl"));
3813 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003814
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003815 // Generate a funky cast.
3816 llvm::SmallVector<QualType, 8> ArgTypes;
3817
3818 // Push the block argument type.
3819 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003820 if (FTP) {
3821 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003822 E = FTP->arg_type_end(); I && (I != E); ++I) {
3823 QualType t = *I;
3824 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003825 if (isTopLevelBlockPointerType(t)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003826 const BlockPointerType *BPT = t->getAsBlockPointerType();
3827 t = Context->getPointerType(BPT->getPointeeType());
3828 }
3829 ArgTypes.push_back(t);
3830 }
Steve Naroff54055232008-10-27 17:20:55 +00003831 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003832 // Now do the pointer to function cast.
3833 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3834 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3835
3836 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003837
Ted Kremenek8189cde2009-02-07 01:47:29 +00003838 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3839 PtrBlock, SourceLocation(),
3840 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003841 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003842 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3843 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003844 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003845
Douglas Gregor44b43212008-12-11 16:49:14 +00003846 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3847 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003848 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003849 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3850 FD->getType());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003851
Ted Kremenek8189cde2009-02-07 01:47:29 +00003852 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3853 PtrToFuncCastType,
3854 SourceLocation(),
3855 SourceLocation());
3856 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003857
3858 llvm::SmallVector<Expr*, 8> BlkExprs;
3859 // Add the implicit argument.
3860 BlkExprs.push_back(BlkCast);
3861 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003862 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3863 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003864 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003865 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003866 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3867 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00003868 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003869 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003870}
3871
3872void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003873 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3874 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003875}
3876
3877void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3878 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003879 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroffdf8570d2009-02-02 17:19:26 +00003880 Context->getPointerType(BDRE->getType()),
3881 SourceLocation());
3882 // Need parens to enforce precedence.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003883 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroffdf8570d2009-02-02 17:19:26 +00003884 ReplaceStmt(BDRE, PE);
Steve Naroff54055232008-10-27 17:20:55 +00003885}
3886
Steve Naroffb2f9e512008-11-03 23:29:32 +00003887void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3888 SourceLocation LocStart = CE->getLParenLoc();
3889 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003890
3891 // Need to avoid trying to rewrite synthesized casts.
3892 if (LocStart.isInvalid())
3893 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003894 // Need to avoid trying to rewrite casts contained in macros.
3895 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3896 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003897
Steve Naroff54055232008-10-27 17:20:55 +00003898 const char *startBuf = SM->getCharacterData(LocStart);
3899 const char *endBuf = SM->getCharacterData(LocEnd);
3900
3901 // advance the location to startArgList.
3902 const char *argPtr = startBuf;
3903
3904 while (*argPtr++ && (argPtr < endBuf)) {
3905 switch (*argPtr) {
3906 case '^':
3907 // Replace the '^' with '*'.
3908 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3909 ReplaceText(LocStart, 1, "*", 1);
3910 break;
3911 }
3912 }
3913 return;
3914}
3915
3916void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3917 SourceLocation DeclLoc = FD->getLocation();
3918 unsigned parenCount = 0;
3919
3920 // We have 1 or more arguments that have closure pointers.
3921 const char *startBuf = SM->getCharacterData(DeclLoc);
3922 const char *startArgList = strchr(startBuf, '(');
3923
3924 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3925
3926 parenCount++;
3927 // advance the location to startArgList.
3928 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3929 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3930
3931 const char *argPtr = startArgList;
3932
3933 while (*argPtr++ && parenCount) {
3934 switch (*argPtr) {
3935 case '^':
3936 // Replace the '^' with '*'.
3937 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3938 ReplaceText(DeclLoc, 1, "*", 1);
3939 break;
3940 case '(':
3941 parenCount++;
3942 break;
3943 case ')':
3944 parenCount--;
3945 break;
3946 }
3947 }
3948 return;
3949}
3950
3951bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3952 const FunctionTypeProto *FTP;
3953 const PointerType *PT = QT->getAsPointerType();
3954 if (PT) {
3955 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3956 } else {
3957 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3958 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3959 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3960 }
3961 if (FTP) {
3962 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3963 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003964 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00003965 return true;
3966 }
3967 return false;
3968}
3969
Ted Kremenek8189cde2009-02-07 01:47:29 +00003970void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
3971 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00003972 const char *argPtr = strchr(Name, '(');
3973 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3974
3975 LParen = argPtr; // output the start.
3976 argPtr++; // skip past the left paren.
3977 unsigned parenCount = 1;
3978
3979 while (*argPtr && parenCount) {
3980 switch (*argPtr) {
3981 case '(': parenCount++; break;
3982 case ')': parenCount--; break;
3983 default: break;
3984 }
3985 if (parenCount) argPtr++;
3986 }
3987 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3988 RParen = argPtr; // output the end
3989}
3990
3991void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3992 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3993 RewriteBlockPointerFunctionArgs(FD);
3994 return;
3995 }
3996 // Handle Variables and Typedefs.
3997 SourceLocation DeclLoc = ND->getLocation();
3998 QualType DeclT;
3999 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4000 DeclT = VD->getType();
4001 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4002 DeclT = TDD->getUnderlyingType();
4003 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4004 DeclT = FD->getType();
4005 else
4006 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4007
4008 const char *startBuf = SM->getCharacterData(DeclLoc);
4009 const char *endBuf = startBuf;
4010 // scan backward (from the decl location) for the end of the previous decl.
4011 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4012 startBuf--;
4013
4014 // *startBuf != '^' if we are dealing with a pointer to function that
4015 // may take block argument types (which will be handled below).
4016 if (*startBuf == '^') {
4017 // Replace the '^' with '*', computing a negative offset.
4018 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4019 ReplaceText(DeclLoc, 1, "*", 1);
4020 }
4021 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4022 // Replace the '^' with '*' for arguments.
4023 DeclLoc = ND->getLocation();
4024 startBuf = SM->getCharacterData(DeclLoc);
4025 const char *argListBegin, *argListEnd;
4026 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4027 while (argListBegin < argListEnd) {
4028 if (*argListBegin == '^') {
4029 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4030 ReplaceText(CaretLoc, 1, "*", 1);
4031 }
4032 argListBegin++;
4033 }
4034 }
4035 return;
4036}
4037
4038void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4039 // Add initializers for any closure decl refs.
4040 GetBlockDeclRefExprs(Exp->getBody());
4041 if (BlockDeclRefs.size()) {
4042 // Unique all "by copy" declarations.
4043 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4044 if (!BlockDeclRefs[i]->isByRef())
4045 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4046 // Unique all "by ref" declarations.
4047 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4048 if (BlockDeclRefs[i]->isByRef()) {
4049 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4050 }
4051 // Find any imported blocks...they will need special attention.
4052 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff47a24222008-12-11 20:51:38 +00004053 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004054 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004055 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4056 }
4057 }
4058}
4059
Steve Narofffa15fd92008-10-28 20:29:00 +00004060FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4061 IdentifierInfo *ID = &Context->Idents.get(name);
4062 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
4063 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004064 ID, FType, FunctionDecl::Extern, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004065}
4066
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004067Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004068 Blocks.push_back(Exp);
4069
4070 CollectBlockDeclRefInfo(Exp);
4071 std::string FuncName;
4072
4073 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004074 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004075 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004076 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004077 // Convert colons to underscores.
4078 std::string::size_type loc = 0;
4079 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4080 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004081 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004082 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004083
4084 std::string BlockNumber = utostr(Blocks.size()-1);
4085
4086 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4087 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4088
4089 // Get a pointer to the function type so we can cast appropriately.
4090 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4091
4092 FunctionDecl *FD;
4093 Expr *NewRep;
4094
4095 // Simulate a contructor call...
4096 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004097 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004098
4099 llvm::SmallVector<Expr*, 4> InitExprs;
4100
Steve Narofffdc03722008-10-29 21:23:59 +00004101 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004102 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004103 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4104 SourceLocation());
4105 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4106 Context->VoidPtrTy, SourceLocation(),
4107 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004108 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004109
4110 if (ImportedBlockDecls.size()) {
4111 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004112 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004113 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4114 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4115 Context->VoidPtrTy, SourceLocation(),
4116 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004117 InitExprs.push_back(castExpr);
4118
Steve Narofffa15fd92008-10-28 20:29:00 +00004119 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004120 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004121 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4122 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4123 Context->VoidPtrTy, SourceLocation(),
4124 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004125 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004126 }
4127 // Add initializers for any closure decl refs.
4128 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004129 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004130 // Output all "by copy" declarations.
4131 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4132 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004133 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004134 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004135 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004136 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004137 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004138 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004139 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4140 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4141 Context->VoidPtrTy, SourceLocation(),
4142 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004143 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004144 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004145 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004146 }
Steve Narofffdc03722008-10-29 21:23:59 +00004147 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004148 }
4149 // Output all "by ref" declarations.
4150 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4151 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004152 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004153 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4154 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Narofffdc03722008-10-29 21:23:59 +00004155 Context->getPointerType(Exp->getType()),
4156 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004157 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004158 }
4159 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004160 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4161 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004162 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Narofffa15fd92008-10-28 20:29:00 +00004163 Context->getPointerType(NewRep->getType()),
4164 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004165 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4166 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004167 BlockDeclRefs.clear();
4168 BlockByRefDecls.clear();
4169 BlockByCopyDecls.clear();
4170 ImportedBlockDecls.clear();
4171 return NewRep;
4172}
4173
4174//===----------------------------------------------------------------------===//
4175// Function Body / Expression rewriting
4176//===----------------------------------------------------------------------===//
4177
Steve Naroffc77a6362008-12-04 16:24:46 +00004178// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4179// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4180// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4181// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4182// Since the rewriter isn't capable of rewriting rewritten code, it's important
4183// we get this right.
4184void RewriteObjC::CollectPropertySetters(Stmt *S) {
4185 // Perform a bottom up traversal of all children.
4186 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4187 CI != E; ++CI)
4188 if (*CI)
4189 CollectPropertySetters(*CI);
4190
4191 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4192 if (BinOp->isAssignmentOp()) {
4193 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4194 PropSetters[PRE] = BinOp;
4195 }
4196 }
4197}
4198
Steve Narofffa15fd92008-10-28 20:29:00 +00004199Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4200 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4201 isa<DoStmt>(S) || isa<ForStmt>(S))
4202 Stmts.push_back(S);
4203 else if (isa<ObjCForCollectionStmt>(S)) {
4204 Stmts.push_back(S);
4205 ObjCBcLabelNo.push_back(++BcLabelCount);
4206 }
4207
4208 SourceRange OrigStmtRange = S->getSourceRange();
4209
4210 // Perform a bottom up rewrite of all children.
4211 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4212 CI != E; ++CI)
4213 if (*CI) {
4214 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4215 if (newStmt)
4216 *CI = newStmt;
4217 }
4218
4219 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4220 // Rewrite the block body in place.
4221 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4222
4223 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004224 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4225 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004226
4227 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4228 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004229 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004230 return blockTranscribed;
4231 }
4232 // Handle specific things.
4233 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4234 return RewriteAtEncode(AtEncode);
4235
4236 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4237 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4238
Steve Naroffc77a6362008-12-04 16:24:46 +00004239 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4240 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4241 if (BinOp) {
4242 // Because the rewriter doesn't allow us to rewrite rewritten code,
4243 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004244 DisableReplaceStmt = true;
4245 // Save the source range. Even if we disable the replacement, the
4246 // rewritten node will have been inserted into the tree. If the synthesized
4247 // node is at the 'end', the rewriter will fail. Consider this:
4248 // self.errorHandler = handler ? handler :
4249 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4250 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004251 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004252 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004253 //
4254 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4255 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4256 // to see the original expression). Consider this example:
4257 //
4258 // Foo *obj1, *obj2;
4259 //
4260 // obj1.i = [obj2 rrrr];
4261 //
4262 // 'BinOp' for the previous expression looks like:
4263 //
4264 // (BinaryOperator 0x231ccf0 'int' '='
4265 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4266 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4267 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4268 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4269 //
4270 // 'newStmt' represents the rewritten message expression. For example:
4271 //
4272 // (CallExpr 0x231d300 'id':'struct objc_object *'
4273 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4274 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4275 // (CStyleCastExpr 0x231d220 'void *'
4276 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4277 //
4278 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4279 // can be used as the setter argument. ReplaceStmt() will still 'see'
4280 // the original RHS (since we haven't altered BinOp).
4281 //
4282 // This implies the Rewrite* routines can no longer delete the original
4283 // node. As a result, we now leak the original AST nodes.
4284 //
Steve Naroffb619d952008-12-09 12:56:34 +00004285 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004286 } else {
4287 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004288 }
4289 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004290 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4291 return RewriteAtSelector(AtSelector);
4292
4293 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4294 return RewriteObjCStringLiteral(AtString);
4295
4296 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004297#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004298 // Before we rewrite it, put the original message expression in a comment.
4299 SourceLocation startLoc = MessExpr->getLocStart();
4300 SourceLocation endLoc = MessExpr->getLocEnd();
4301
4302 const char *startBuf = SM->getCharacterData(startLoc);
4303 const char *endBuf = SM->getCharacterData(endLoc);
4304
4305 std::string messString;
4306 messString += "// ";
4307 messString.append(startBuf, endBuf-startBuf+1);
4308 messString += "\n";
4309
4310 // FIXME: Missing definition of
4311 // InsertText(clang::SourceLocation, char const*, unsigned int).
4312 // InsertText(startLoc, messString.c_str(), messString.size());
4313 // Tried this, but it didn't work either...
4314 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004315#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004316 return RewriteMessageExpr(MessExpr);
4317 }
4318
4319 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4320 return RewriteObjCTryStmt(StmtTry);
4321
4322 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4323 return RewriteObjCSynchronizedStmt(StmtTry);
4324
4325 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4326 return RewriteObjCThrowStmt(StmtThrow);
4327
4328 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4329 return RewriteObjCProtocolExpr(ProtocolExp);
4330
4331 if (ObjCForCollectionStmt *StmtForCollection =
4332 dyn_cast<ObjCForCollectionStmt>(S))
4333 return RewriteObjCForCollectionStmt(StmtForCollection,
4334 OrigStmtRange.getEnd());
4335 if (BreakStmt *StmtBreakStmt =
4336 dyn_cast<BreakStmt>(S))
4337 return RewriteBreakStmt(StmtBreakStmt);
4338 if (ContinueStmt *StmtContinueStmt =
4339 dyn_cast<ContinueStmt>(S))
4340 return RewriteContinueStmt(StmtContinueStmt);
4341
4342 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4343 // and cast exprs.
4344 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4345 // FIXME: What we're doing here is modifying the type-specifier that
4346 // precedes the first Decl. In the future the DeclGroup should have
4347 // a separate type-specifier that we can rewrite.
4348 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4349
4350 // Blocks rewrite rules.
4351 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4352 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004353 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004354 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004355 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004356 RewriteBlockPointerDecl(ND);
4357 else if (ND->getType()->isFunctionPointerType())
4358 CheckFunctionPointerDecl(ND->getType(), ND);
4359 }
4360 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004361 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004362 RewriteBlockPointerDecl(TD);
4363 else if (TD->getUnderlyingType()->isFunctionPointerType())
4364 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4365 }
4366 }
4367 }
4368
4369 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4370 RewriteObjCQualifiedInterfaceTypes(CE);
4371
4372 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4373 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4374 assert(!Stmts.empty() && "Statement stack is empty");
4375 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4376 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4377 && "Statement stack mismatch");
4378 Stmts.pop_back();
4379 }
4380 // Handle blocks rewriting.
4381 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4382 if (BDRE->isByRef())
4383 RewriteBlockDeclRefExpr(BDRE);
4384 }
4385 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004386 if (CE->getCallee()->getType()->isBlockPointerType()) {
4387 Stmt *BlockCall = SynthesizeBlockCall(CE);
4388 ReplaceStmt(S, BlockCall);
4389 return BlockCall;
4390 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004391 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004392 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004393 RewriteCastExpr(CE);
4394 }
4395#if 0
4396 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004397 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004398 // Get the new text.
4399 std::string SStr;
4400 llvm::raw_string_ostream Buf(SStr);
4401 Replacement->printPretty(Buf);
4402 const std::string &Str = Buf.str();
4403
4404 printf("CAST = %s\n", &Str[0]);
4405 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4406 delete S;
4407 return Replacement;
4408 }
4409#endif
4410 // Return this stmt unmodified.
4411 return S;
4412}
4413
4414/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4415/// main file of the input.
4416void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4417 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004418 if (FD->isOverloadedOperator())
4419 return;
4420
Steve Narofffa15fd92008-10-28 20:29:00 +00004421 // Since function prototypes don't have ParmDecl's, we check the function
4422 // prototype. This enables us to rewrite function declarations and
4423 // definitions using the same code.
4424 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4425
4426 if (Stmt *Body = FD->getBody()) {
4427 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004428 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004429 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004430 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004431 CurrentBody = 0;
4432 if (PropParentMap) {
4433 delete PropParentMap;
4434 PropParentMap = 0;
4435 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004436 // This synthesizes and inserts the block "impl" struct, invoke function,
4437 // and any copy/dispose helper functions.
4438 InsertBlockLiteralsWithinFunction(FD);
4439 CurFunctionDef = 0;
4440 }
4441 return;
4442 }
4443 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4444 if (Stmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004445 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004446 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004447 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004448 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004449 CurrentBody = 0;
4450 if (PropParentMap) {
4451 delete PropParentMap;
4452 PropParentMap = 0;
4453 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004454 InsertBlockLiteralsWithinMethod(MD);
4455 CurMethodDef = 0;
4456 }
4457 }
4458 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4459 ClassImplementation.push_back(CI);
4460 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4461 CategoryImplementation.push_back(CI);
4462 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4463 RewriteForwardClassDecl(CD);
4464 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4465 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004466 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004467 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004468 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004469 CheckFunctionPointerDecl(VD->getType(), VD);
4470 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004471 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004472 RewriteCastExpr(CE);
4473 }
4474 }
4475 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004476 if (VD->getInit()) {
4477 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004478 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004479 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004480 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004481 CurrentBody = 0;
4482 if (PropParentMap) {
4483 delete PropParentMap;
4484 PropParentMap = 0;
4485 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004486 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004487 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004488 GlobalVarDecl = 0;
4489
4490 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004491 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004492 RewriteCastExpr(CE);
4493 }
4494 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004495 return;
4496 }
4497 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004498 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004499 RewriteBlockPointerDecl(TD);
4500 else if (TD->getUnderlyingType()->isFunctionPointerType())
4501 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4502 return;
4503 }
4504 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4505 if (RD->isDefinition()) {
Douglas Gregora4c46df2008-12-11 17:59:21 +00004506 for (RecordDecl::field_iterator i = RD->field_begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004507 e = RD->field_end(); i != e; ++i) {
4508 FieldDecl *FD = *i;
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004509 if (isTopLevelBlockPointerType(FD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004510 RewriteBlockPointerDecl(FD);
4511 }
4512 }
4513 return;
4514 }
4515 // Nothing yet.
4516}
4517
4518void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4519 // Get the top-level buffer that this corresponds to.
4520
4521 // Rewrite tabs if we care.
4522 //RewriteTabs();
4523
4524 if (Diags.hasErrorOccurred())
4525 return;
4526
4527 // Create the output file.
4528
4529 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4530 llvm::raw_ostream *OutFile;
4531 if (OutFileName == "-") {
4532 OutFile = &llvm::outs();
4533 } else if (!OutFileName.empty()) {
4534 std::string Err;
Steve Naroff62c26322009-02-03 20:39:18 +00004535 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(),
4536 // set binary mode (critical for Windoze)
4537 true,
4538 Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004539 OwnedStream.reset(OutFile);
4540 } else if (InFileName == "-") {
4541 OutFile = &llvm::outs();
4542 } else {
4543 llvm::sys::Path Path(InFileName);
4544 Path.eraseSuffix();
4545 Path.appendSuffix("cpp");
4546 std::string Err;
Steve Naroff62c26322009-02-03 20:39:18 +00004547 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(),
4548 // set binary mode (critical for Windoze)
4549 true,
4550 Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004551 OwnedStream.reset(OutFile);
4552 }
4553
4554 RewriteInclude();
4555
Chris Lattner2b2453a2009-01-17 06:22:33 +00004556 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00004557 Preamble.c_str(), Preamble.size(), false);
4558
Steve Naroff0aab7962008-11-14 14:10:01 +00004559 if (ClassImplementation.size() || CategoryImplementation.size())
4560 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004561
4562 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4563 // we are done.
4564 if (const RewriteBuffer *RewriteBuf =
4565 Rewrite.getRewriteBufferFor(MainFileID)) {
4566 //printf("Changed:\n");
4567 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4568 } else {
4569 fprintf(stderr, "No changes\n");
4570 }
Steve Narofface66252008-11-13 20:07:04 +00004571
Steve Naroff0aab7962008-11-14 14:10:01 +00004572 if (ClassImplementation.size() || CategoryImplementation.size()) {
4573 // Rewrite Objective-c meta data*
4574 std::string ResultStr;
4575 SynthesizeMetaDataIntoBuffer(ResultStr);
4576 // Emit metadata.
4577 *OutFile << ResultStr;
4578 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004579 OutFile->flush();
4580}
4581