blob: 2a3460492c505a01026e800d5161a249fa4a4171 [file] [log] [blame]
Steve Naroff44e81222008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnerb429ae42007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb429ae42007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremenek79b50cb2008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Steve Narofffbed6802008-12-08 16:43:47 +000019#include "clang/AST/ParentMap.h"
Chris Lattner569faa62007-10-11 18:38:32 +000020#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000021#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000022#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000023#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000024#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000025#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000026#include "llvm/ADT/OwningPtr.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000027#include "llvm/Support/MemoryBuffer.h"
Steve Naroff1c46cf12008-01-28 21:34:52 +000028#include "llvm/Support/CommandLine.h"
Dan Gohman6da15102008-05-21 20:19:16 +000029#include "llvm/Support/Streams.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattner673f2bd2008-03-22 00:08:40 +000031#include "llvm/System/Path.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000032using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000033using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000034
Steve Naroff1c46cf12008-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 Lattnerb429ae42007-10-11 00:43:27 +000039namespace {
Steve Naroff44e81222008-04-14 22:03:09 +000040 class RewriteObjC : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000041 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000042 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000043 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000044 unsigned RewriteFailedDiag;
Steve Naroff43964fb2008-12-05 17:03:39 +000045 unsigned TryFinallyContainsReturnDiag;
46
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000047 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000048 SourceManager *SM;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000049 TranslationUnitDecl *TUDecl;
Chris Lattnerf4f776a2009-01-17 06:22:33 +000050 FileID MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000051 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000052 SourceLocation LastIncLoc;
Steve Narofffef037c2008-03-27 22:29:16 +000053
Ted Kremenek42730c52008-01-07 19:49:32 +000054 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
55 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
56 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff04eaa192008-05-06 18:26:51 +000057 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek42730c52008-01-07 19:49:32 +000058 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
59 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000060 llvm::SmallVector<Stmt *, 32> Stmts;
61 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffe9780582007-10-23 23:50:29 +000062
Steve Naroff47e7fa22008-03-15 00:55:56 +000063 unsigned NumObjCStringLiterals;
64
Steve Naroffe9780582007-10-23 23:50:29 +000065 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000066 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000067 FunctionDecl *MsgSendStretFunctionDecl;
68 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000069 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000070 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000071 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000072 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000073 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000074 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000075 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000076
Steve Naroff0add5d22007-11-03 11:27:19 +000077 // ObjC string constant support.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000078 VarDecl *ConstantStringClassReference;
Steve Naroff0add5d22007-11-03 11:27:19 +000079 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000080
Fariborz Jahanian22277422008-01-16 00:09:11 +000081 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000082 int BcLabelCount;
83
Steve Naroff764c1ae2007-11-15 10:28:18 +000084 // Needed for super.
Steve Naroff38a9e3f2008-10-27 17:20:55 +000085 ObjCMethodDecl *CurMethodDef;
Steve Naroff764c1ae2007-11-15 10:28:18 +000086 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000087 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000088
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000089 // Needed for header files being rewritten
90 bool IsHeader;
91
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000092 std::string InFileName;
93 std::string OutFileName;
94
Steve Narofffef037c2008-03-27 22:29:16 +000095 std::string Preamble;
Steve Naroff38a9e3f2008-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 Narofffef037c2008-03-27 22:29:16 +0000101
Steve Naroff38a9e3f2008-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 Naroff0e948412008-12-04 16:24:46 +0000109 // This maps a property to it's assignment statement.
110 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Narofffbed6802008-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 Naroff102c3f22008-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 Narofff6ce8a12008-12-03 00:56:33 +0000119
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000120 FunctionDecl *CurFunctionDef;
Steve Naroff80c54752008-10-29 18:15:37 +0000121 VarDecl *GlobalVarDecl;
122
Steve Naroffedb4bc92008-12-09 12:56:34 +0000123 bool DisableReplaceStmt;
124
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000125 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +0000126 public:
Ted Kremenek79b50cb2008-05-31 20:11:04 +0000127 virtual void Initialize(ASTContext &context);
128
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000129 // Top Level Driver code.
130 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000131 void HandleDeclInMainFile(Decl *D);
Steve Naroff44e81222008-04-14 22:03:09 +0000132 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000133 Diagnostic &D, const LangOptions &LOpts);
Ted Kremenekcab0b0c2008-08-08 04:15:52 +0000134
135 ~RewriteObjC() {}
136
137 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerb1548372008-01-31 19:37:57 +0000138
139 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff102c3f22008-12-04 23:50:32 +0000140 Stmt *ReplacingStmt = ReplacedNodes[Old];
141
142 if (ReplacingStmt)
143 return; // We can't rewrite the same node twice.
Chris Lattnerb1548372008-01-31 19:37:57 +0000144
Steve Naroffedb4bc92008-12-09 12:56:34 +0000145 if (DisableReplaceStmt)
146 return; // Used when rewriting the assignment of a property setter.
147
Steve Naroff102c3f22008-12-04 23:50:32 +0000148 // If replacement succeeded or warning disabled return with no warning.
149 if (!Rewrite.ReplaceStmt(Old, New)) {
150 ReplacedNodes[Old] = New;
151 return;
152 }
153 if (SilenceRewriteMacroWarning)
154 return;
Chris Lattner6948ae62008-11-18 07:04:44 +0000155 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
156 << Old->getSourceRange();
Chris Lattnerb1548372008-01-31 19:37:57 +0000157 }
Steve Naroffedb4bc92008-12-09 12:56:34 +0000158
159 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
160 // Measaure the old text.
161 int Size = Rewrite.getRangeSize(SrcRange);
162 if (Size == -1) {
163 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
164 << Old->getSourceRange();
165 return;
166 }
167 // Get the new text.
168 std::string SStr;
169 llvm::raw_string_ostream S(SStr);
170 New->printPretty(S);
171 const std::string &Str = S.str();
172
173 // If replacement succeeded or warning disabled return with no warning.
174 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
175 ReplacedNodes[Old] = New;
176 return;
177 }
178 if (SilenceRewriteMacroWarning)
179 return;
180 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
181 << Old->getSourceRange();
182 }
183
Steve Narofffef037c2008-03-27 22:29:16 +0000184 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
185 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000186 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000187 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000188 SilenceRewriteMacroWarning)
189 return;
190
191 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
192 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000193
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000194 void RemoveText(SourceLocation Loc, unsigned StrLen) {
195 // If removal succeeded or warning disabled return with no warning.
196 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
197 return;
198
199 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
200 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000201
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000202 void ReplaceText(SourceLocation Start, unsigned OrigLength,
203 const char *NewStr, unsigned NewLength) {
204 // If removal succeeded or warning disabled return with no warning.
205 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
206 SilenceRewriteMacroWarning)
207 return;
208
209 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
210 }
211
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000212 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000213 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000214 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000215 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000216 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffea6610f2008-12-02 17:36:43 +0000217 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
218 ObjCImplementationDecl *IMD,
219 ObjCCategoryImplDecl *CID);
Ted Kremenek42730c52008-01-07 19:49:32 +0000220 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000221 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000222 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
223 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
224 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
225 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
226 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff56af2002009-01-11 01:06:09 +0000227 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000228 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000229 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000230 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000231 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000232 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000233 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000234 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000235 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000236
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000237 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000238 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff0e948412008-12-04 16:24:46 +0000239 void CollectPropertySetters(Stmt *S);
240
Steve Narofffbed6802008-12-08 16:43:47 +0000241 Stmt *CurrentBody;
242 ParentMap *PropParentMap; // created lazily.
243
Chris Lattner0021f452007-10-24 16:57:36 +0000244 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000245 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff0e948412008-12-04 16:24:46 +0000246 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffedb4bc92008-12-09 12:56:34 +0000247 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
248 SourceRange SrcRange);
Steve Naroff296b74f2007-11-05 14:50:49 +0000249 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000250 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000251 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000252 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff43964fb2008-12-05 17:03:39 +0000253 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000254 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000255 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000256 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
257 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
258 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000259 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
260 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000261 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
262 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000263 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000264 Stmt *RewriteBreakStmt(BreakStmt *S);
265 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000266 void SynthCountByEnumWithState(std::string &buf);
267
Steve Naroff02a82aa2007-10-30 23:14:51 +0000268 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000269 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000270 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000271 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000272 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000273 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000274 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000275 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000276 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000277 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000278
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000279 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000280 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000281 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000282
Ted Kremenek42730c52008-01-07 19:49:32 +0000283 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000284 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000285
Ted Kremenek42730c52008-01-07 19:49:32 +0000286 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
287 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000288 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000289 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000290 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000291 const char *ClassName,
292 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000293
Chris Lattner0be08822008-07-21 21:32:27 +0000294 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
295 &Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000296 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000297 const char *ClassName,
298 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000299 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000300 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000301 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
302 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000303 std::string &Result);
Steve Naroff21658f62008-11-13 20:07:04 +0000304 void RewriteImplementations();
305 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000306
307 // Block rewriting.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000308 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000309 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
310
311 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
312 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
313
Steve Naroff80c54752008-10-29 18:15:37 +0000314 // Block specific rewrite rules.
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000315 void RewriteBlockCall(CallExpr *Exp);
316 void RewriteBlockPointerDecl(NamedDecl *VD);
317 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
318 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
319
320 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
321 const char *funcName, std::string Tag);
322 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
323 const char *funcName, std::string Tag);
324 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
325 bool hasCopyDisposeHelpers);
Steve Naroff85eb17b2008-10-30 10:07:53 +0000326 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000327 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
328 const char *FunName);
329
330 void CollectBlockDeclRefInfo(BlockExpr *Exp);
331 void GetBlockCallExprs(Stmt *S);
332 void GetBlockDeclRefExprs(Stmt *S);
333
334 // We avoid calling Type::isBlockPointerType(), since it operates on the
335 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000336 bool isTopLevelBlockPointerType(QualType T) {
337 return isa<BlockPointerType>(T);
338 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000339
340 // FIXME: This predicate seems like it would be useful to add to ASTContext.
341 bool isObjCType(QualType T) {
342 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
343 return false;
344
345 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
346
347 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
348 OCT == Context->getCanonicalType(Context->getObjCClassType()))
349 return true;
350
351 if (const PointerType *PT = OCT->getAsPointerType()) {
352 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
353 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
354 return true;
355 }
356 return false;
357 }
358 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek0c97e042009-02-07 01:47:29 +0000359 void GetExtentOfArgList(const char *Name, const char *&LParen,
360 const char *&RParen);
Steve Naroff7f1412d2008-11-03 23:29:32 +0000361 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +0000362
363 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff80c54752008-10-29 18:15:37 +0000364 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000365 };
366}
367
Douglas Gregor4fa58902009-02-26 23:50:07 +0000368void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000369 NamedDecl *D) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000370 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
371 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000372 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +0000373 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000374 // All the args are checked/rewritten. Don't call twice!
375 RewriteBlockPointerDecl(D);
376 break;
377 }
378 }
379}
380
381void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
382 const PointerType *PT = funcType->getAsPointerType();
383 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor4fa58902009-02-26 23:50:07 +0000384 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000385}
386
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000387static bool IsHeaderFile(const std::string &Filename) {
388 std::string::size_type DotPos = Filename.rfind('.');
389
390 if (DotPos == std::string::npos) {
391 // no file extension
392 return false;
393 }
394
395 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
396 // C header: .h
397 // C++ header: .hh or .H;
398 return Ext == "h" || Ext == "hh" || Ext == "H";
399}
400
Steve Naroff44e81222008-04-14 22:03:09 +0000401RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000402 Diagnostic &D, const LangOptions &LOpts)
403 : Diags(D), LangOpts(LOpts) {
404 IsHeader = IsHeaderFile(inFile);
405 InFileName = inFile;
406 OutFileName = outFile;
407 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
408 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff43964fb2008-12-05 17:03:39 +0000409 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000410 "rewriter doesn't support user-specified control flow semantics "
411 "for @try/@finally (code may not execute properly)");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000412}
413
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000414ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000415 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000416 Diagnostic &Diags,
417 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000418 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000419}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000420
Steve Naroff44e81222008-04-14 22:03:09 +0000421void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000422 Context = &context;
423 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000424 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000425 MsgSendFunctionDecl = 0;
426 MsgSendSuperFunctionDecl = 0;
427 MsgSendStretFunctionDecl = 0;
428 MsgSendSuperStretFunctionDecl = 0;
429 MsgSendFpretFunctionDecl = 0;
430 GetClassFunctionDecl = 0;
431 GetMetaClassFunctionDecl = 0;
432 SelGetUidFunctionDecl = 0;
433 CFStringFunctionDecl = 0;
434 GetProtocolFunctionDecl = 0;
435 ConstantStringClassReference = 0;
436 NSStringRecord = 0;
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000437 CurMethodDef = 0;
438 CurFunctionDef = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000439 GlobalVarDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000440 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000441 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000442 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000443 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000444 NumObjCStringLiterals = 0;
Steve Naroffbad6f3b2008-12-08 20:01:41 +0000445 PropParentMap = 0;
446 CurrentBody = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000447 DisableReplaceStmt = false;
448
Chris Lattner12499682008-01-31 19:38:44 +0000449 // Get the ID and start/end of the main file.
450 MainFileID = SM->getMainFileID();
451 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
452 MainFileStart = MainBuf->getBufferStart();
453 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000454
Chris Lattner12499682008-01-31 19:38:44 +0000455 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000456
Chris Lattner12499682008-01-31 19:38:44 +0000457 // declaring objc_selector outside the parameter list removes a silly
458 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000459 if (IsHeader)
Steve Naroff08299f82009-02-03 20:39:18 +0000460 Preamble = "#pragma once\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000461 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff12673622008-12-23 20:11:22 +0000462 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Narofffef037c2008-03-27 22:29:16 +0000463 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000464 if (LangOpts.Microsoft) {
465 // Add a constructor for creating temporary objects.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000466 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
467 ": ";
Steve Narofffef037c2008-03-27 22:29:16 +0000468 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000469 }
Steve Narofffef037c2008-03-27 22:29:16 +0000470 Preamble += "};\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000471 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
472 Preamble += "typedef struct objc_object Protocol;\n";
473 Preamble += "#define _REWRITER_typedef_Protocol\n";
474 Preamble += "#endif\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000475 if (LangOpts.Microsoft) {
476 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
477 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
478 } else
479 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
480 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000481 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000482 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000483 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000484 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000485 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000486 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000487 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000488 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000489 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000490 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000491 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000492 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000493 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000494 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
495 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
496 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
497 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
498 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000499 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000500 // @synchronized hooks.
Steve Naroff1b208d72008-12-08 17:30:33 +0000501 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
502 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
503 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000504 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
505 Preamble += "struct __objcFastEnumerationState {\n\t";
506 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000507 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000508 Preamble += "unsigned long *mutationsPtr;\n\t";
509 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000510 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000511 Preamble += "#define __FASTENUMERATIONSTATE\n";
512 Preamble += "#endif\n";
513 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
514 Preamble += "struct __NSConstantStringImpl {\n";
515 Preamble += " int *isa;\n";
516 Preamble += " int flags;\n";
517 Preamble += " char *str;\n";
518 Preamble += " long length;\n";
519 Preamble += "};\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000520 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
521 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
522 Preamble += "#else\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000523 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000524 Preamble += "#endif\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000525 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
526 Preamble += "#endif\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000527 // Blocks preamble.
528 Preamble += "#ifndef BLOCK_IMPL\n";
529 Preamble += "#define BLOCK_IMPL\n";
530 Preamble += "struct __block_impl {\n";
531 Preamble += " void *isa;\n";
532 Preamble += " int Flags;\n";
533 Preamble += " int Size;\n";
534 Preamble += " void *FuncPtr;\n";
535 Preamble += "};\n";
Steve Naroff44fe1e32008-12-16 15:50:30 +0000536 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
537 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
538 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
539 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
540 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000541 Preamble += "#endif\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000542 if (LangOpts.Microsoft) {
Steve Naroff1b208d72008-12-08 17:30:33 +0000543 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
544 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000545 Preamble += "#define __attribute__(X)\n";
546 }
Chris Lattner12499682008-01-31 19:38:44 +0000547}
548
549
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000550//===----------------------------------------------------------------------===//
551// Top Level Driver Code
552//===----------------------------------------------------------------------===//
553
Steve Naroff44e81222008-04-14 22:03:09 +0000554void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000555 // Two cases: either the decl could be in the main file, or it could be in a
556 // #included file. If the former, rewrite it now. If the later, check to see
557 // if we rewrote the #include/#import.
558 SourceLocation Loc = D->getLocation();
Chris Lattner18c8dc02009-01-16 07:36:28 +0000559 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000560
561 // If this is for a builtin, ignore it.
562 if (Loc.isInvalid()) return;
563
Steve Naroffe9780582007-10-23 23:50:29 +0000564 // Look for built-in declarations that we need to refer during the rewrite.
565 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000566 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000567 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000568 // declared in <Foundation/NSString.h>
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000569 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000570 ConstantStringClassReference = FVD;
571 return;
572 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000573 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000574 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000575 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000576 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000577 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000578 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000579 } else if (ObjCForwardProtocolDecl *FP =
580 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000581 RewriteForwardProtocolDecl(FP);
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000582 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
583 // Recurse into linkage specifications
584 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
585 DIEnd = LSD->decls_end();
586 DI != DIEnd; ++DI)
587 HandleTopLevelDecl(*DI);
Steve Naroffe9780582007-10-23 23:50:29 +0000588 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000589 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000590 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000591 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000592}
593
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000594//===----------------------------------------------------------------------===//
595// Syntactic (non-AST) Rewriting Code
596//===----------------------------------------------------------------------===//
597
Steve Naroff44e81222008-04-14 22:03:09 +0000598void RewriteObjC::RewriteInclude() {
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000599 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000600 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
601 const char *MainBufStart = MainBuf.first;
602 const char *MainBufEnd = MainBuf.second;
603 size_t ImportLen = strlen("import");
604 size_t IncludeLen = strlen("include");
605
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000606 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000607 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
608 if (*BufPtr == '#') {
609 if (++BufPtr == MainBufEnd)
610 return;
611 while (*BufPtr == ' ' || *BufPtr == '\t')
612 if (++BufPtr == MainBufEnd)
613 return;
614 if (!strncmp(BufPtr, "import", ImportLen)) {
615 // replace import with include
616 SourceLocation ImportLoc =
617 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000618 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000619 BufPtr += ImportLen;
620 }
621 }
622 }
Chris Lattner74db1682007-10-16 21:07:07 +0000623}
624
Steve Naroff44e81222008-04-14 22:03:09 +0000625void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000626 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
627 const char *MainBufStart = MainBuf.first;
628 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000629
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000630 // Loop over the whole file, looking for tabs.
631 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
632 if (*BufPtr != '\t')
633 continue;
634
635 // Okay, we found a tab. This tab will turn into at least one character,
636 // but it depends on which 'virtual column' it is in. Compute that now.
637 unsigned VCol = 0;
638 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
639 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
640 ++VCol;
641
642 // Okay, now that we know the virtual column, we know how many spaces to
643 // insert. We assume 8-character tab-stops.
644 unsigned Spaces = 8-(VCol & 7);
645
646 // Get the location of the tab.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000647 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
648 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000649
650 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000651 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000652 }
Chris Lattner569faa62007-10-11 18:38:32 +0000653}
654
Steve Naroff121ed222008-12-02 15:48:25 +0000655static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
656 ObjCIvarDecl *OID) {
657 std::string S;
658 S = "((struct ";
659 S += ClassDecl->getIdentifier()->getName();
660 S += "_IMPL *)self)->";
661 S += OID->getNameAsCString();
662 return S;
663}
664
Steve Naroffea6610f2008-12-02 17:36:43 +0000665void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
666 ObjCImplementationDecl *IMD,
667 ObjCCategoryImplDecl *CID) {
Steve Naroff110be842008-12-01 20:33:01 +0000668 SourceLocation startLoc = PID->getLocStart();
669 InsertText(startLoc, "// ", 3);
Steve Naroff121ed222008-12-02 15:48:25 +0000670 const char *startBuf = SM->getCharacterData(startLoc);
671 assert((*startBuf == '@') && "bogus @synthesize location");
672 const char *semiBuf = strchr(startBuf, ';');
673 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek0c97e042009-02-07 01:47:29 +0000674 SourceLocation onePastSemiLoc =
675 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff121ed222008-12-02 15:48:25 +0000676
677 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
678 return; // FIXME: is this correct?
679
680 // Generate the 'getter' function.
Steve Naroff121ed222008-12-02 15:48:25 +0000681 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff121ed222008-12-02 15:48:25 +0000682 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff121ed222008-12-02 15:48:25 +0000683 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000684
685 if (!OID)
686 return;
687
688 std::string Getr;
689 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
690 Getr += "{ ";
691 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000692 // FIXME: deal with code generation implications for various property
693 // attributes (copy, retain, nonatomic).
694 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000695 Getr += "return " + getIvarAccessString(ClassDecl, OID);
696 Getr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000697 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffea6610f2008-12-02 17:36:43 +0000698
699 // Add the rewritten getter to trigger meta data generation. An alternate, and
700 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
701 // with properties explicitly. The following addInstanceMethod() required far
702 // less code change (and actually models what the rewriter is doing).
703 if (IMD)
704 IMD->addInstanceMethod(PD->getGetterMethodDecl());
705 else
706 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroff121ed222008-12-02 15:48:25 +0000707
708 if (PD->isReadOnly())
709 return;
710
711 // Generate the 'setter' function.
712 std::string Setr;
713 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff121ed222008-12-02 15:48:25 +0000714 Setr += "{ ";
Steve Naroff1e7b7962008-12-02 16:05:55 +0000715 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000716 // FIXME: deal with code generation implications for various property
717 // attributes (copy, retain, nonatomic).
Steve Narofff6ce8a12008-12-03 00:56:33 +0000718 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000719 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff20f67392008-12-11 19:29:16 +0000720 Setr += PD->getNameAsCString();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000721 Setr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000722 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffea6610f2008-12-02 17:36:43 +0000723
724 // Add the rewritten setter to trigger meta data generation.
725 if (IMD)
726 IMD->addInstanceMethod(PD->getSetterMethodDecl());
727 else
728 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroff110be842008-12-01 20:33:01 +0000729}
Chris Lattner569faa62007-10-11 18:38:32 +0000730
Steve Naroff44e81222008-04-14 22:03:09 +0000731void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000732 // Get the start location and compute the semi location.
733 SourceLocation startLoc = ClassDecl->getLocation();
734 const char *startBuf = SM->getCharacterData(startLoc);
735 const char *semiPtr = strchr(startBuf, ';');
736
737 // Translate to typedef's that forward reference structs with the same name
738 // as the class. As a convenience, we include the original declaration
739 // as a comment.
740 std::string typedefString;
741 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000742 typedefString.append(startBuf, semiPtr-startBuf+1);
743 typedefString += "\n";
Chris Lattner6a028742009-02-20 18:04:31 +0000744 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
745 I != E; ++I) {
746 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff2aeae312007-11-09 12:50:28 +0000747 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000748 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000749 typedefString += "\n";
750 typedefString += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000751 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000752 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000753 typedefString += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000754 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000755 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000756 }
757
758 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000759 ReplaceText(startLoc, semiPtr-startBuf+1,
760 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000761}
762
Steve Naroff44e81222008-04-14 22:03:09 +0000763void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000764 SourceLocation LocStart = Method->getLocStart();
765 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000766
Chris Lattner2d89c562009-02-04 01:06:56 +0000767 if (SM->getInstantiationLineNumber(LocEnd) >
768 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff99f50fe2008-10-21 13:37:27 +0000769 InsertText(LocStart, "#if 0\n", 6);
770 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000771 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000772 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000773 }
774}
775
Steve Naroff56af2002009-01-11 01:06:09 +0000776void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000777{
Steve Naroff56af2002009-01-11 01:06:09 +0000778 SourceLocation Loc = prop->getLocation();
779
780 ReplaceText(Loc, 0, "// ", 3);
781
782 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000783}
784
Steve Naroff44e81222008-04-14 22:03:09 +0000785void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000786 SourceLocation LocStart = CatDecl->getLocStart();
787
788 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000789 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000790
Ted Kremenek42730c52008-01-07 19:49:32 +0000791 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000792 E = CatDecl->instmeth_end(); I != E; ++I)
793 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000794 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000795 E = CatDecl->classmeth_end(); I != E; ++I)
796 RewriteMethodDeclaration(*I);
797
Steve Naroff667f1682007-10-30 13:30:57 +0000798 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000799 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000800}
801
Steve Naroff44e81222008-04-14 22:03:09 +0000802void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000803 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000804
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000805 SourceLocation LocStart = PDecl->getLocStart();
806
807 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000808 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000809
Ted Kremenek42730c52008-01-07 19:49:32 +0000810 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000811 E = PDecl->instmeth_end(); I != E; ++I)
812 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000813 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000814 E = PDecl->classmeth_end(); I != E; ++I)
815 RewriteMethodDeclaration(*I);
816
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000817 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000818 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000819 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000820
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000821 // Must comment out @optional/@required
822 const char *startBuf = SM->getCharacterData(LocStart);
823 const char *endBuf = SM->getCharacterData(LocEnd);
824 for (const char *p = startBuf; p < endBuf; p++) {
825 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
826 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000827 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000828 ReplaceText(OptionalLoc, strlen("@optional"),
829 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000830
831 }
832 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
833 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000834 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000835 ReplaceText(OptionalLoc, strlen("@required"),
836 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000837
838 }
839 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000840}
841
Steve Naroff44e81222008-04-14 22:03:09 +0000842void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000843 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000844 if (LocStart.isInvalid())
845 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000846 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000847 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000848}
849
Steve Naroff44e81222008-04-14 22:03:09 +0000850void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000851 std::string &ResultStr) {
Steve Naroff6449c6c2008-10-30 12:09:33 +0000852 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff91044cf2008-07-16 14:40:40 +0000853 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000854 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000855 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000856 ResultStr += "id";
Steve Naroff20f67392008-12-11 19:29:16 +0000857 else if (OMD->getResultType()->isFunctionPointerType() ||
858 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000859 // needs special handling, since pointer-to-functions have special
860 // syntax (where a decaration models use).
861 QualType retType = OMD->getResultType();
Steve Naroff20f67392008-12-11 19:29:16 +0000862 QualType PointeeTy;
863 if (const PointerType* PT = retType->getAsPointerType())
864 PointeeTy = PT->getPointeeType();
865 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
866 PointeeTy = BPT->getPointeeType();
867 if ((FPRetType = PointeeTy->getAsFunctionType())) {
868 ResultStr += FPRetType->getResultType().getAsString();
869 ResultStr += "(*";
Steve Naroff91044cf2008-07-16 14:40:40 +0000870 }
871 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000872 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000873 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000874
875 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000876 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000877
Douglas Gregor5d764842009-01-09 17:18:27 +0000878 if (OMD->isInstanceMethod())
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000879 NameStr += "_I_";
880 else
881 NameStr += "_C_";
882
Chris Lattner271d4c22008-11-24 05:29:24 +0000883 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000884 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000885
Ted Kremenek42730c52008-01-07 19:49:32 +0000886 if (ObjCCategoryImplDecl *CID =
Steve Naroff438be772009-01-08 19:41:02 +0000887 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000888 NameStr += CID->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000889 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000890 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000891 // Append selector names, replacing ':' with '_'
Chris Lattner3a8f2942008-11-24 03:33:13 +0000892 {
893 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000894 int len = selString.size();
895 for (int i = 0; i < len; i++)
896 if (selString[i] == ':')
897 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000898 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000899 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000900 // Remember this name for metadata emission
901 MethodInternalNames[OMD] = NameStr;
902 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000903
904 // Rewrite arguments
905 ResultStr += "(";
906
907 // invisible arguments
Douglas Gregor5d764842009-01-09 17:18:27 +0000908 if (OMD->isInstanceMethod()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000909 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000910 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000911 if (!LangOpts.Microsoft) {
912 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
913 ResultStr += "struct ";
914 }
915 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattner271d4c22008-11-24 05:29:24 +0000916 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +0000917 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000918 }
919 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000920 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000921
922 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000923 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000924 ResultStr += " _cmd";
925
926 // Method arguments.
Chris Lattner5c6b2c62009-02-20 18:43:26 +0000927 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
928 E = OMD->param_end(); PI != E; ++PI) {
929 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000930 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000931 if (PDecl->getType()->isObjCQualifiedIdType()) {
932 ResultStr += "id ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000933 ResultStr += PDecl->getNameAsString();
Steve Naroff133dfda2008-04-18 21:13:19 +0000934 } else {
Chris Lattner271d4c22008-11-24 05:29:24 +0000935 std::string Name = PDecl->getNameAsString();
Steve Naroffd896f4b2008-12-11 21:05:33 +0000936 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff4e2ae512008-10-30 14:45:29 +0000937 // Make sure we convert "t (^)(...)" to "t (*)(...)".
938 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
939 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
940 } else
941 PDecl->getType().getAsStringInternal(Name);
Steve Naroff133dfda2008-04-18 21:13:19 +0000942 ResultStr += Name;
943 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000944 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000945 if (OMD->isVariadic())
946 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000947 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000948
Steve Naroff91044cf2008-07-16 14:40:40 +0000949 if (FPRetType) {
950 ResultStr += ")"; // close the precedence "scope" for "*".
951
952 // Now, emit the argument types (if any).
Douglas Gregor4fa58902009-02-26 23:50:07 +0000953 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000954 ResultStr += "(";
955 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
956 if (i) ResultStr += ", ";
957 std::string ParamStr = FT->getArgType(i).getAsString();
958 ResultStr += ParamStr;
959 }
960 if (FT->isVariadic()) {
961 if (FT->getNumArgs()) ResultStr += ", ";
962 ResultStr += "...";
963 }
964 ResultStr += ")";
965 } else {
966 ResultStr += "()";
967 }
968 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000969}
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000970void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000971 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
972 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000973
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000974 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000975 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000976 else
Chris Lattner6216f292008-01-31 19:42:41 +0000977 InsertText(CID->getLocStart(), "// ", 3);
Steve Naroff21658f62008-11-13 20:07:04 +0000978
Ted Kremenek42730c52008-01-07 19:49:32 +0000979 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000980 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
981 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000982 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000983 ObjCMethodDecl *OMD = *I;
984 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000985 SourceLocation LocStart = OMD->getLocStart();
986 SourceLocation LocEnd = OMD->getBody()->getLocStart();
987
988 const char *startBuf = SM->getCharacterData(LocStart);
989 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000990 ReplaceText(LocStart, endBuf-startBuf,
991 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000992 }
993
Ted Kremenek42730c52008-01-07 19:49:32 +0000994 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000995 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
996 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000997 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000998 ObjCMethodDecl *OMD = *I;
999 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001000 SourceLocation LocStart = OMD->getLocStart();
1001 SourceLocation LocEnd = OMD->getBody()->getLocStart();
1002
1003 const char *startBuf = SM->getCharacterData(LocStart);
1004 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001005 ReplaceText(LocStart, endBuf-startBuf,
1006 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001007 }
Steve Naroff110be842008-12-01 20:33:01 +00001008 for (ObjCCategoryImplDecl::propimpl_iterator
1009 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1010 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffea6610f2008-12-02 17:36:43 +00001011 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroff110be842008-12-01 20:33:01 +00001012 }
1013
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001014 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +00001015 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001016 else
Chris Lattner6216f292008-01-31 19:42:41 +00001017 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001018}
1019
Steve Naroff44e81222008-04-14 22:03:09 +00001020void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +00001021 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +00001022 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +00001023 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +00001024 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001025 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001026 ResultStr += "\n";
1027 ResultStr += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001028 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001029 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +00001030 ResultStr += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +00001031 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001032 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +00001033 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00001034 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +00001035 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001036 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +00001037
Steve Naroff56af2002009-01-11 01:06:09 +00001038 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1039 E = ClassDecl->prop_end(); I != E; ++I)
1040 RewriteProperty(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +00001041 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +00001042 E = ClassDecl->instmeth_end(); I != E; ++I)
1043 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +00001044 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +00001045 E = ClassDecl->classmeth_end(); I != E; ++I)
1046 RewriteMethodDeclaration(*I);
1047
Steve Naroff1ccf4632007-10-30 03:43:13 +00001048 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001049 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +00001050}
1051
Steve Naroffedb4bc92008-12-09 12:56:34 +00001052Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1053 SourceRange SrcRange) {
Steve Naroff0e948412008-12-04 16:24:46 +00001054 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1055 // This allows us to reuse all the fun and games in SynthMessageExpr().
1056 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1057 ObjCMessageExpr *MsgExpr;
1058 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1059 llvm::SmallVector<Expr *, 1> ExprVec;
1060 ExprVec.push_back(newStmt);
1061
Steve Narofffbed6802008-12-08 16:43:47 +00001062 Stmt *Receiver = PropRefExpr->getBase();
1063 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1064 if (PRE && PropGetters[PRE]) {
1065 // This allows us to handle chain/nested property getters.
1066 Receiver = PropGetters[PRE];
1067 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001068 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff0e948412008-12-04 16:24:46 +00001069 PDecl->getSetterName(), PDecl->getType(),
1070 PDecl->getSetterMethodDecl(),
1071 SourceLocation(), SourceLocation(),
1072 &ExprVec[0], 1);
1073 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1074
1075 // Now do the actual rewrite.
Steve Naroffedb4bc92008-12-09 12:56:34 +00001076 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroff478f7382008-12-10 14:53:27 +00001077 //delete BinOp;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001078 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1079 // to things that stay around.
1080 Context->Deallocate(MsgExpr);
Steve Naroff0e948412008-12-04 16:24:46 +00001081 return ReplacingStmt;
Steve Narofff6ce8a12008-12-03 00:56:33 +00001082}
1083
Steve Naroff0e948412008-12-04 16:24:46 +00001084Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff6ce8a12008-12-03 00:56:33 +00001085 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1086 // This allows us to reuse all the fun and games in SynthMessageExpr().
1087 ObjCMessageExpr *MsgExpr;
1088 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1089
Steve Narofffbed6802008-12-08 16:43:47 +00001090 Stmt *Receiver = PropRefExpr->getBase();
1091
1092 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1093 if (PRE && PropGetters[PRE]) {
1094 // This allows us to handle chain/nested property getters.
1095 Receiver = PropGetters[PRE];
1096 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001097 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Narofff6ce8a12008-12-03 00:56:33 +00001098 PDecl->getGetterName(), PDecl->getType(),
1099 PDecl->getGetterMethodDecl(),
1100 SourceLocation(), SourceLocation(),
1101 0, 0);
1102
Steve Naroff102c3f22008-12-04 23:50:32 +00001103 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001104
1105 if (!PropParentMap)
1106 PropParentMap = new ParentMap(CurrentBody);
1107
1108 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1109 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1110 // We stash away the ReplacingStmt since actually doing the
1111 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1112 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001113 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1114 // to things that stay around.
1115 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001116 return PropRefExpr; // return the original...
1117 } else {
1118 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001119 // delete PropRefExpr; elsewhere...
1120 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1121 // to things that stay around.
1122 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001123 return ReplacingStmt;
1124 }
Steve Narofff6ce8a12008-12-03 00:56:33 +00001125}
1126
Chris Lattner343c82b2008-05-23 20:40:52 +00001127Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1128 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001129 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001130 if (CurMethodDef) {
Steve Naroff60dfb6b2008-03-12 00:25:36 +00001131 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001132 ObjCInterfaceType *iFaceDecl =
1133 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffa9636222008-05-08 17:52:16 +00001134 // lookup which class implements the instance variable.
1135 ObjCInterfaceDecl *clsDeclared = 0;
1136 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1137 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1138
1139 // Synthesize an explicit cast to gain access to the ivar.
1140 std::string RecName = clsDeclared->getIdentifier()->getName();
1141 RecName += "_IMPL";
1142 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001143 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001144 SourceLocation(), II);
Steve Naroffa9636222008-05-08 17:52:16 +00001145 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1146 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek0c97e042009-02-07 01:47:29 +00001147 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1148 castT,SourceLocation(),
1149 SourceLocation());
Steve Naroffa9636222008-05-08 17:52:16 +00001150 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001151 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1152 IV->getBase()->getLocEnd(),
1153 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +00001154 if (IV->isFreeIvar() &&
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001155 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001156 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1157 IV->getLocation(),
1158 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +00001159 ReplaceStmt(IV, ME);
Steve Naroff102c3f22008-12-04 23:50:32 +00001160 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffa9636222008-05-08 17:52:16 +00001161 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +00001162 }
Chris Lattner343c82b2008-05-23 20:40:52 +00001163
1164 ReplaceStmt(IV->getBase(), PE);
1165 // Cannot delete IV->getBase(), since PE points to it.
1166 // Replace the old base with the cast. This is important when doing
1167 // embedded rewrites. For example, [newInv->_container addObject:0].
1168 IV->setBase(PE);
1169 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +00001170 }
Steve Naroffe6155362008-04-18 21:55:08 +00001171 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +00001172 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1173
1174 // Explicit ivar refs need to have a cast inserted.
1175 // FIXME: consider sharing some of this code with the code above.
1176 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +00001177 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001178 // lookup which class implements the instance variable.
1179 ObjCInterfaceDecl *clsDeclared = 0;
Steve Naroffa9636222008-05-08 17:52:16 +00001180 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001181 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1182
1183 // Synthesize an explicit cast to gain access to the ivar.
1184 std::string RecName = clsDeclared->getIdentifier()->getName();
1185 RecName += "_IMPL";
1186 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001187 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001188 SourceLocation(), II);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001189 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1190 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek0c97e042009-02-07 01:47:29 +00001191 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1192 castT, SourceLocation(),
1193 SourceLocation());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001194 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001195 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner3cca6612008-05-28 16:38:23 +00001196 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001197 ReplaceStmt(IV->getBase(), PE);
1198 // Cannot delete IV->getBase(), since PE points to it.
1199 // Replace the old base with the cast. This is important when doing
1200 // embedded rewrites. For example, [newInv->_container addObject:0].
1201 IV->setBase(PE);
1202 return IV;
1203 }
Steve Naroff292b7b92007-11-15 11:33:00 +00001204 }
Steve Naroffe6155362008-04-18 21:55:08 +00001205 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +00001206}
1207
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001208/// SynthCountByEnumWithState - To print:
1209/// ((unsigned int (*)
1210/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1211/// (void *)objc_msgSend)((id)l_collection,
1212/// sel_registerName(
1213/// "countByEnumeratingWithState:objects:count:"),
1214/// &enumState,
1215/// (id *)items, (unsigned int)16)
1216///
Steve Naroff44e81222008-04-14 22:03:09 +00001217void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001218 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1219 "id *, unsigned int))(void *)objc_msgSend)";
1220 buf += "\n\t\t";
1221 buf += "((id)l_collection,\n\t\t";
1222 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1223 buf += "\n\t\t";
1224 buf += "&enumState, "
1225 "(id *)items, (unsigned int)16)";
1226}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001227
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001228/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1229/// statement to exit to its outer synthesized loop.
1230///
Steve Naroff44e81222008-04-14 22:03:09 +00001231Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001232 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1233 return S;
1234 // replace break with goto __break_label
1235 std::string buf;
1236
1237 SourceLocation startLoc = S->getLocStart();
1238 buf = "goto __break_label_";
1239 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001240 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001241
1242 return 0;
1243}
1244
1245/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1246/// statement to continue with its inner synthesized loop.
1247///
Steve Naroff44e81222008-04-14 22:03:09 +00001248Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001249 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1250 return S;
1251 // replace continue with goto __continue_label
1252 std::string buf;
1253
1254 SourceLocation startLoc = S->getLocStart();
1255 buf = "goto __continue_label_";
1256 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001257 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001258
1259 return 0;
1260}
1261
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001262/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001263/// It rewrites:
1264/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001265
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001266/// Into:
1267/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001268/// type elem;
1269/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001270/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001271/// id l_collection = (id)collection;
1272/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1273/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001274/// if (limit) {
1275/// unsigned long startMutations = *enumState.mutationsPtr;
1276/// do {
1277/// unsigned long counter = 0;
1278/// do {
1279/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001280/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001281/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001282/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001283/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001284/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001285/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1286/// objects:items count:16]);
1287/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001288/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001289/// }
1290/// else
1291/// elem = nil;
1292/// }
1293///
Steve Naroff44e81222008-04-14 22:03:09 +00001294Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001295 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001296 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1297 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1298 "ObjCForCollectionStmt Statement stack mismatch");
1299 assert(!ObjCBcLabelNo.empty() &&
1300 "ObjCForCollectionStmt - Label No stack empty");
1301
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001302 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001303 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001304 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001305 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001306 std::string buf;
1307 buf = "\n{\n\t";
1308 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1309 // type elem;
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001310 NamedDecl* D = cast<NamedDecl>(DS->getSolitaryDecl());
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001311 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001312 elementTypeAsString = ElementType.getAsString();
1313 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001314 buf += " ";
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001315 elementName = D->getNameAsCString();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001316 buf += elementName;
1317 buf += ";\n\t";
1318 }
Chris Lattner690c2872008-04-08 05:52:18 +00001319 else {
1320 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001321 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001322 elementTypeAsString
1323 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001324 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001325
1326 // struct __objcFastEnumerationState enumState = { 0 };
1327 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1328 // id items[16];
1329 buf += "id items[16];\n\t";
1330 // id l_collection = (id)
1331 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001332 // Find start location of 'collection' the hard way!
1333 const char *startCollectionBuf = startBuf;
1334 startCollectionBuf += 3; // skip 'for'
1335 startCollectionBuf = strchr(startCollectionBuf, '(');
1336 startCollectionBuf++; // skip '('
1337 // find 'in' and skip it.
1338 while (*startCollectionBuf != ' ' ||
1339 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1340 (*(startCollectionBuf+3) != ' ' &&
1341 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1342 startCollectionBuf++;
1343 startCollectionBuf += 3;
1344
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001345 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001346 ReplaceText(startLoc, startCollectionBuf - startBuf,
1347 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001348 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001349 SourceLocation rightParenLoc = S->getRParenLoc();
1350 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1351 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001352 buf = ";\n\t";
1353
1354 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1355 // objects:items count:16];
1356 // which is synthesized into:
1357 // unsigned int limit =
1358 // ((unsigned int (*)
1359 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1360 // (void *)objc_msgSend)((id)l_collection,
1361 // sel_registerName(
1362 // "countByEnumeratingWithState:objects:count:"),
1363 // (struct __objcFastEnumerationState *)&state,
1364 // (id *)items, (unsigned int)16);
1365 buf += "unsigned long limit =\n\t\t";
1366 SynthCountByEnumWithState(buf);
1367 buf += ";\n\t";
1368 /// if (limit) {
1369 /// unsigned long startMutations = *enumState.mutationsPtr;
1370 /// do {
1371 /// unsigned long counter = 0;
1372 /// do {
1373 /// if (startMutations != *enumState.mutationsPtr)
1374 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001375 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001376 buf += "if (limit) {\n\t";
1377 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1378 buf += "do {\n\t\t";
1379 buf += "unsigned long counter = 0;\n\t\t";
1380 buf += "do {\n\t\t\t";
1381 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1382 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1383 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001384 buf += " = (";
1385 buf += elementTypeAsString;
1386 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001387 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001388 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001389
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001390 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001391 /// } while (counter < limit);
1392 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1393 /// objects:items count:16]);
1394 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001395 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001396 /// }
1397 /// else
1398 /// elem = nil;
1399 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001400 ///
1401 buf = ";\n\t";
1402 buf += "__continue_label_";
1403 buf += utostr(ObjCBcLabelNo.back());
1404 buf += ": ;";
1405 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001406 buf += "} while (counter < limit);\n\t";
1407 buf += "} while (limit = ";
1408 SynthCountByEnumWithState(buf);
1409 buf += ");\n\t";
1410 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001411 buf += " = ((id)0);\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001412 buf += "__break_label_";
1413 buf += utostr(ObjCBcLabelNo.back());
1414 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001415 buf += "}\n\t";
1416 buf += "else\n\t\t";
1417 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001418 buf += " = ((id)0);\n";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001419 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001420
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001421 // Insert all these *after* the statement body.
Steve Naroff5f238fe2008-07-21 18:26:02 +00001422 if (isa<CompoundStmt>(S->getBody())) {
1423 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1424 InsertText(endBodyLoc, buf.c_str(), buf.size());
1425 } else {
1426 /* Need to treat single statements specially. For example:
1427 *
1428 * for (A *a in b) if (stuff()) break;
1429 * for (A *a in b) xxxyy;
1430 *
1431 * The following code simply scans ahead to the semi to find the actual end.
1432 */
1433 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1434 const char *semiBuf = strchr(stmtBuf, ';');
1435 assert(semiBuf && "Can't find ';'");
1436 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1437 InsertText(endBodyLoc, buf.c_str(), buf.size());
1438 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001439 Stmts.pop_back();
1440 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001441 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001442}
1443
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001444/// RewriteObjCSynchronizedStmt -
1445/// This routine rewrites @synchronized(expr) stmt;
1446/// into:
1447/// objc_sync_enter(expr);
1448/// @try stmt @finally { objc_sync_exit(expr); }
1449///
Steve Naroff44e81222008-04-14 22:03:09 +00001450Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001451 // Get the start location and compute the semi location.
1452 SourceLocation startLoc = S->getLocStart();
1453 const char *startBuf = SM->getCharacterData(startLoc);
1454
1455 assert((*startBuf == '@') && "bogus @synchronized location");
1456
1457 std::string buf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001458 buf = "objc_sync_enter((id)";
1459 const char *lparenBuf = startBuf;
1460 while (*lparenBuf != '(') lparenBuf++;
1461 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroff027cd0b2008-08-19 13:04:19 +00001462 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1463 // the sync expression is typically a message expression that's already
1464 // been rewritten! (which implies the SourceLocation's are invalid).
1465 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001466 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroff027cd0b2008-08-19 13:04:19 +00001467 while (*endBuf != ')') endBuf--;
1468 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001469 buf = ");\n";
1470 // declare a new scope with two variables, _stack and _rethrow.
1471 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1472 buf += "int buf[18/*32-bit i386*/];\n";
1473 buf += "char *pointers[4];} _stack;\n";
1474 buf += "id volatile _rethrow = 0;\n";
1475 buf += "objc_exception_try_enter(&_stack);\n";
1476 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001477 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001478 startLoc = S->getSynchBody()->getLocEnd();
1479 startBuf = SM->getCharacterData(startLoc);
1480
Steve Naroff027cd0b2008-08-19 13:04:19 +00001481 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001482 SourceLocation lastCurlyLoc = startLoc;
1483 buf = "}\nelse {\n";
1484 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1485 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001486 buf += " objc_sync_exit(";
Ted Kremenek0c97e042009-02-07 01:47:29 +00001487 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1488 S->getSynchExpr(),
1489 Context->getObjCIdType(),
1490 SourceLocation(),
1491 SourceLocation());
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001492 std::string syncExprBufS;
1493 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroffc1656a62008-08-21 13:03:03 +00001494 syncExpr->printPretty(syncExprBuf);
Steve Naroff17919b52008-07-16 19:47:39 +00001495 buf += syncExprBuf.str();
1496 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001497 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1498 buf += "}\n";
1499 buf += "}";
1500
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001501 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001502 return 0;
1503}
1504
Steve Naroff43964fb2008-12-05 17:03:39 +00001505void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1506 // Perform a bottom up traversal of all children.
1507 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1508 CI != E; ++CI)
1509 if (*CI)
1510 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1511
1512 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1513 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1514 Diags.Report(Context->getFullLoc(S->getLocStart()),
1515 TryFinallyContainsReturnDiag);
1516 }
1517 return;
1518}
1519
Steve Naroff44e81222008-04-14 22:03:09 +00001520Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001521 // Get the start location and compute the semi location.
1522 SourceLocation startLoc = S->getLocStart();
1523 const char *startBuf = SM->getCharacterData(startLoc);
1524
1525 assert((*startBuf == '@') && "bogus @try location");
1526
1527 std::string buf;
1528 // declare a new scope with two variables, _stack and _rethrow.
1529 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1530 buf += "int buf[18/*32-bit i386*/];\n";
1531 buf += "char *pointers[4];} _stack;\n";
1532 buf += "id volatile _rethrow = 0;\n";
1533 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001534 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001535
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001536 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001537
1538 startLoc = S->getTryBody()->getLocEnd();
1539 startBuf = SM->getCharacterData(startLoc);
1540
1541 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001542
Steve Naroffe9f69842007-11-07 04:08:17 +00001543 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001544 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1545 if (catchList) {
1546 startLoc = startLoc.getFileLocWithOffset(1);
1547 buf = " /* @catch begin */ else {\n";
1548 buf += " id _caught = objc_exception_extract(&_stack);\n";
1549 buf += " objc_exception_try_enter (&_stack);\n";
1550 buf += " if (_setjmp(_stack.buf))\n";
1551 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1552 buf += " else { /* @catch continue */";
1553
1554 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff36269d22008-09-09 19:59:12 +00001555 } else { /* no catch list */
1556 buf = "}\nelse {\n";
1557 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1558 buf += "}";
1559 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff9d0ff352008-07-16 15:31:30 +00001560 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001561 bool sawIdTypedCatch = false;
1562 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001563 while (catchList) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001564 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffe9f69842007-11-07 04:08:17 +00001565
1566 if (catchList == S->getCatchStmts())
1567 buf = "if ("; // we are generating code for the first catch clause
1568 else
1569 buf = "else if (";
1570 startLoc = catchList->getLocStart();
1571 startBuf = SM->getCharacterData(startLoc);
1572
1573 assert((*startBuf == '@') && "bogus @catch location");
1574
1575 const char *lParenLoc = strchr(startBuf, '(');
1576
Steve Naroff397c4ce2008-02-01 22:08:12 +00001577 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001578 // Now rewrite the body...
1579 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001580 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1581 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001582 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1583 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001584 assert((*bodyBuf == '{') && "bogus @catch body location");
1585
1586 buf += "1) { id _tmp = _caught;";
1587 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1588 buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001589 } else if (catchDecl) {
1590 QualType t = catchDecl->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001591 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001592 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001593 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001594 sawIdTypedCatch = true;
1595 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001596 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001597
Ted Kremenek42730c52008-01-07 19:49:32 +00001598 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001599 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001600 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00001601 buf += cls->getDecl()->getNameAsString();
Steve Naroffd3287d82007-11-07 18:43:40 +00001602 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001603 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001604 }
1605 }
1606 // Now rewrite the body...
1607 lastCatchBody = catchList->getCatchBody();
1608 SourceLocation rParenLoc = catchList->getRParenLoc();
1609 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1610 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1611 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1612 assert((*rParenBuf == ')') && "bogus @catch paren location");
1613 assert((*bodyBuf == '{') && "bogus @catch body location");
1614
1615 buf = " = _caught;";
1616 // Here we replace ") {" with "= _caught;" (which initializes and
1617 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001618 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001619 } else {
Steve Naroffe9f69842007-11-07 04:08:17 +00001620 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001621 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001622 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001623 catchList = catchList->getNextCatchStmt();
1624 }
1625 // Complete the catch list...
1626 if (lastCatchBody) {
1627 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001628 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1629 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001630
Steve Naroff31325c12008-09-11 15:29:03 +00001631 // Insert the last (implicit) else clause *before* the right curly brace.
1632 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1633 buf = "} /* last catch end */\n";
1634 buf += "else {\n";
1635 buf += " _rethrow = _caught;\n";
1636 buf += " objc_exception_try_exit(&_stack);\n";
1637 buf += "} } /* @catch end */\n";
1638 if (!S->getFinallyStmt())
1639 buf += "}\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001640 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001641
1642 // Set lastCurlyLoc
1643 lastCurlyLoc = lastCatchBody->getLocEnd();
1644 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001645 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001646 startLoc = finalStmt->getLocStart();
1647 startBuf = SM->getCharacterData(startLoc);
1648 assert((*startBuf == '@') && "bogus @finally start");
1649
1650 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001651 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001652
1653 Stmt *body = finalStmt->getFinallyBody();
1654 SourceLocation startLoc = body->getLocStart();
1655 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001656 assert(*SM->getCharacterData(startLoc) == '{' &&
1657 "bogus @finally body location");
1658 assert(*SM->getCharacterData(endLoc) == '}' &&
1659 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001660
1661 startLoc = startLoc.getFileLocWithOffset(1);
1662 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001663 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001664 endLoc = endLoc.getFileLocWithOffset(-1);
1665 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001666 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001667
1668 // Set lastCurlyLoc
1669 lastCurlyLoc = body->getLocEnd();
Steve Naroff43964fb2008-12-05 17:03:39 +00001670
1671 // Now check for any return/continue/go statements within the @try.
1672 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff31325c12008-09-11 15:29:03 +00001673 } else { /* no finally clause - make sure we synthesize an implicit one */
1674 buf = "{ /* implicit finally clause */\n";
1675 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1676 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1677 buf += "}";
1678 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001679 }
1680 // Now emit the final closing curly brace...
1681 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1682 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001683 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001684 return 0;
1685}
1686
Steve Naroff44e81222008-04-14 22:03:09 +00001687Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001688 return 0;
1689}
1690
Steve Naroff44e81222008-04-14 22:03:09 +00001691Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001692 return 0;
1693}
1694
Chris Lattnerb1548372008-01-31 19:37:57 +00001695// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001696// the throw expression is typically a message expression that's already
1697// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001698Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001699 // Get the start location and compute the semi location.
1700 SourceLocation startLoc = S->getLocStart();
1701 const char *startBuf = SM->getCharacterData(startLoc);
1702
1703 assert((*startBuf == '@') && "bogus @throw location");
1704
1705 std::string buf;
1706 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001707 if (S->getThrowExpr())
1708 buf = "objc_exception_throw(";
1709 else // add an implicit argument
1710 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001711
1712 // handle "@ throw" correctly.
1713 const char *wBuf = strchr(startBuf, 'w');
1714 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1715 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1716
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001717 const char *semiBuf = strchr(startBuf, ';');
1718 assert((*semiBuf == ';') && "@throw: can't find ';'");
1719 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1720 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001721 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001722 return 0;
1723}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001724
Steve Naroff44e81222008-04-14 22:03:09 +00001725Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001726 // Create a new string expression.
1727 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001728 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001729 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattneraa491192009-02-18 06:40:38 +00001730 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1731 StrEncoding.length(), false,StrType,
1732 SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001733 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001734
Chris Lattner4478db92007-11-30 22:53:43 +00001735 // Replace this subexpr in the parent.
Steve Naroff102c3f22008-12-04 23:50:32 +00001736 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner0021f452007-10-24 16:57:36 +00001737 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001738}
1739
Steve Naroff44e81222008-04-14 22:03:09 +00001740Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff95f6bce2008-12-22 22:16:07 +00001741 if (!SelGetUidFunctionDecl)
1742 SynthSelGetUidFunctionDecl();
Steve Naroff296b74f2007-11-05 14:50:49 +00001743 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1744 // Create a call to sel_registerName("selName").
1745 llvm::SmallVector<Expr*, 8> SelExprs;
1746 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00001747 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00001748 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00001749 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00001750 false, argType, SourceLocation()));
Steve Naroff296b74f2007-11-05 14:50:49 +00001751 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1752 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001753 ReplaceStmt(Exp, SelExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00001754 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff296b74f2007-11-05 14:50:49 +00001755 return SelExp;
1756}
1757
Steve Naroff44e81222008-04-14 22:03:09 +00001758CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001759 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001760 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001761 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001762
1763 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001764 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001765
1766 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001767 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001768 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregor70d26122008-11-12 17:17:38 +00001769 /*isLvalue=*/false);
Steve Naroffe9780582007-10-23 23:50:29 +00001770
1771 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001772
Ted Kremenek362abcd2009-02-09 20:51:47 +00001773 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1774 SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001775}
1776
Steve Naroffc8a92d12007-11-01 13:24:47 +00001777static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1778 const char *&startRef, const char *&endRef) {
1779 while (startBuf < endBuf) {
1780 if (*startBuf == '<')
1781 startRef = startBuf; // mark the start.
1782 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001783 if (startRef && *startRef == '<') {
1784 endRef = startBuf; // mark the end.
1785 return true;
1786 }
1787 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001788 }
1789 startBuf++;
1790 }
1791 return false;
1792}
1793
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001794static void scanToNextArgument(const char *&argRef) {
1795 int angle = 0;
1796 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1797 if (*argRef == '<')
1798 angle++;
1799 else if (*argRef == '>')
1800 angle--;
1801 argRef++;
1802 }
1803 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1804}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001805
Steve Naroff44e81222008-04-14 22:03:09 +00001806bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001807
Ted Kremenek42730c52008-01-07 19:49:32 +00001808 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001809 return true;
1810
Steve Naroffc8a92d12007-11-01 13:24:47 +00001811 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001812 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001813 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001814 return true; // we have "Class <Protocol> *".
1815 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001816 return false;
1817}
1818
Steve Naroffd06c88d2008-07-29 18:15:38 +00001819void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1820 QualType Type = E->getType();
1821 if (needToScanForQualifiers(Type)) {
Steve Narofff31ece92008-11-19 21:15:47 +00001822 SourceLocation Loc, EndLoc;
1823
1824 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1825 Loc = ECE->getLParenLoc();
1826 EndLoc = ECE->getRParenLoc();
1827 } else {
1828 Loc = E->getLocStart();
1829 EndLoc = E->getLocEnd();
1830 }
1831 // This will defend against trying to rewrite synthesized expressions.
1832 if (Loc.isInvalid() || EndLoc.isInvalid())
1833 return;
1834
Steve Naroffd06c88d2008-07-29 18:15:38 +00001835 const char *startBuf = SM->getCharacterData(Loc);
Steve Narofff31ece92008-11-19 21:15:47 +00001836 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroffd06c88d2008-07-29 18:15:38 +00001837 const char *startRef = 0, *endRef = 0;
1838 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1839 // Get the locations of the startRef, endRef.
1840 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1841 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1842 // Comment out the protocol references.
1843 InsertText(LessLoc, "/*", 2);
1844 InsertText(GreaterLoc, "*/", 2);
1845 }
1846 }
1847}
1848
Steve Naroff44e81222008-04-14 22:03:09 +00001849void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001850 SourceLocation Loc;
1851 QualType Type;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001852 const FunctionProtoType *proto = 0;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001853 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1854 Loc = VD->getLocation();
1855 Type = VD->getType();
1856 }
1857 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1858 Loc = FD->getLocation();
1859 // Check for ObjC 'id' and class types that have been adorned with protocol
1860 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1861 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1862 assert(funcType && "missing function type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00001863 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001864 if (!proto)
1865 return;
1866 Type = proto->getResultType();
1867 }
1868 else
1869 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001870
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001871 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001872 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001873
1874 const char *endBuf = SM->getCharacterData(Loc);
1875 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001876 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001877 startBuf--; // scan backward (from the decl location) for return type.
1878 const char *startRef = 0, *endRef = 0;
1879 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1880 // Get the locations of the startRef, endRef.
1881 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1882 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1883 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001884 InsertText(LessLoc, "/*", 2);
1885 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001886 }
1887 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001888 if (!proto)
1889 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001890 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001891 const char *startBuf = SM->getCharacterData(Loc);
1892 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001893 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1894 if (needToScanForQualifiers(proto->getArgType(i))) {
1895 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001896
Steve Naroffc8a92d12007-11-01 13:24:47 +00001897 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001898 // scan forward (from the decl location) for argument types.
1899 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001900 const char *startRef = 0, *endRef = 0;
1901 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1902 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001903 SourceLocation LessLoc =
1904 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1905 SourceLocation GreaterLoc =
1906 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001907 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001908 InsertText(LessLoc, "/*", 2);
1909 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001910 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001911 startBuf = ++endBuf;
1912 }
1913 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001914 // If the function name is derived from a macro expansion, then the
1915 // argument buffer will not follow the name. Need to speak with Chris.
1916 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001917 startBuf++; // scan forward (from the decl location) for argument types.
1918 startBuf++;
1919 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001920 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001921}
1922
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001923// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001924void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001925 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1926 llvm::SmallVector<QualType, 16> ArgTys;
1927 ArgTys.push_back(Context->getPointerType(
1928 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001929 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001930 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001931 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001932 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001933 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001934 SelGetUidIdent, getFuncType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001935 FunctionDecl::Extern, false);
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001936}
1937
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001938// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001939void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001940 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1941 llvm::SmallVector<QualType, 16> ArgTys;
1942 ArgTys.push_back(Context->getPointerType(
1943 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001944 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001945 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001946 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001947 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001948 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001949 SelGetProtoIdent, getFuncType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001950 FunctionDecl::Extern, false);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001951}
1952
Steve Naroff44e81222008-04-14 22:03:09 +00001953void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001954 // declared in <objc/objc.h>
Douglas Gregor7339c9e2009-01-09 01:47:02 +00001955 if (FD->getIdentifier() &&
1956 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001957 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001958 return;
1959 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001960 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001961}
1962
Steve Naroffbec4bf52008-03-11 17:37:02 +00001963// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001964void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001965 if (SuperContructorFunctionDecl)
1966 return;
Steve Naroff12673622008-12-23 20:11:22 +00001967 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffbec4bf52008-03-11 17:37:02 +00001968 llvm::SmallVector<QualType, 16> ArgTys;
1969 QualType argT = Context->getObjCIdType();
1970 assert(!argT.isNull() && "Can't find 'id' type");
1971 ArgTys.push_back(argT);
1972 ArgTys.push_back(argT);
1973 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1974 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001975 false, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001976 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001977 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001978 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001979 FunctionDecl::Extern, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00001980}
1981
Steve Naroff02a82aa2007-10-30 23:14:51 +00001982// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001983void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001984 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1985 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001986 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001987 assert(!argT.isNull() && "Can't find 'id' type");
1988 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001989 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001990 assert(!argT.isNull() && "Can't find 'SEL' type");
1991 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001992 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001993 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001994 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001995 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001996 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001997 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001998 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001999}
2000
Steve Naroff764c1ae2007-11-15 10:28:18 +00002001// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002002void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002003 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2004 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002005 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002006 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002007 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002008 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2009 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2010 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002011 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002012 assert(!argT.isNull() && "Can't find 'SEL' type");
2013 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002014 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002015 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002016 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002017 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002018 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002019 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002020 FunctionDecl::Extern, false);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002021}
2022
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002023// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002024void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002025 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2026 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002027 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002028 assert(!argT.isNull() && "Can't find 'id' type");
2029 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002030 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002031 assert(!argT.isNull() && "Can't find 'SEL' type");
2032 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002033 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002034 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002035 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002036 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002037 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002038 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002039 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002040}
2041
2042// SynthMsgSendSuperStretFunctionDecl -
2043// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002044void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002045 IdentifierInfo *msgSendIdent =
2046 &Context->Idents.get("objc_msgSendSuper_stret");
2047 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002048 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002049 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002050 &Context->Idents.get("objc_super"));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002051 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2052 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2053 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002054 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002055 assert(!argT.isNull() && "Can't find 'SEL' type");
2056 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002057 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002058 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002059 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002060 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00002061 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002062 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002063 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002064}
2065
Steve Naroff31316a12008-05-08 22:02:18 +00002066// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002067void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002068 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2069 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002070 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002071 assert(!argT.isNull() && "Can't find 'id' type");
2072 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002073 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002074 assert(!argT.isNull() && "Can't find 'SEL' type");
2075 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00002076 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002077 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002078 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002079 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002080 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002081 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002082 FunctionDecl::Extern, false);
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002083}
2084
Steve Naroff02a82aa2007-10-30 23:14:51 +00002085// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002086void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00002087 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2088 llvm::SmallVector<QualType, 16> ArgTys;
2089 ArgTys.push_back(Context->getPointerType(
2090 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002091 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002092 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002093 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002094 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002095 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002096 getClassIdent, getClassType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002097 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00002098}
2099
Steve Naroff3b1caac2007-12-07 03:50:46 +00002100// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002101void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002102 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2103 llvm::SmallVector<QualType, 16> ArgTys;
2104 ArgTys.push_back(Context->getPointerType(
2105 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002106 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002107 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002108 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002109 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002110 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002111 getClassIdent, getClassType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002112 FunctionDecl::Extern, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002113}
2114
Steve Naroff44e81222008-04-14 22:03:09 +00002115Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002116 QualType strType = getConstantStringStructType();
2117
2118 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00002119
2120 std::string tmpName = InFileName;
2121 unsigned i;
2122 for (i=0; i < tmpName.length(); i++) {
2123 char c = tmpName.at(i);
2124 // replace any non alphanumeric characters with '_'.
2125 if (!isalpha(c) && (c < '0' || c > '9'))
2126 tmpName[i] = '_';
2127 }
2128 S += tmpName;
2129 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002130 S += utostr(NumObjCStringLiterals++);
2131
Steve Narofffef037c2008-03-27 22:29:16 +00002132 Preamble += "static __NSConstantStringImpl " + S;
2133 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2134 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00002135 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00002136 std::string prettyBufS;
2137 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002138 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00002139 Preamble += prettyBuf.str();
2140 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00002141 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00002142 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002143
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002144 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002145 &Context->Idents.get(S.c_str()), strType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002146 VarDecl::Static);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002147 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2148 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroff47e7fa22008-03-15 00:55:56 +00002149 Context->getPointerType(DRE->getType()),
2150 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00002151 // cast to NSConstantString *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002152 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroff7f1412d2008-11-03 23:29:32 +00002153 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00002154 ReplaceStmt(Exp, cast);
Steve Naroff102c3f22008-12-04 23:50:32 +00002155 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffabb96362007-11-08 14:30:50 +00002156 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00002157}
2158
Steve Naroff44e81222008-04-14 22:03:09 +00002159ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002160 // check if we are sending a message to 'super'
Douglas Gregor5d764842009-01-09 17:18:27 +00002161 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattnere4650482008-03-15 06:12:44 +00002162
Douglas Gregord8606632008-11-04 14:56:14 +00002163 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2164 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner4423d372008-06-21 18:04:54 +00002165 assert(PT);
2166 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2167 return IT->getDecl();
2168 }
2169 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002170}
2171
2172// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00002173QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002174 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002175 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002176 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002177 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002178 QualType FieldTypes[2];
2179
2180 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00002181 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002182 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00002183 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002184
Steve Naroff764c1ae2007-11-15 10:28:18 +00002185 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002186 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002187 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002188 SourceLocation(), 0,
2189 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002190 /*Mutable=*/false));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002191 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002192
Douglas Gregor8acb7272008-12-11 16:49:14 +00002193 SuperStructDecl->completeDefinition(*Context);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002194 }
2195 return Context->getTagDeclType(SuperStructDecl);
2196}
2197
Steve Naroff44e81222008-04-14 22:03:09 +00002198QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002199 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002200 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002201 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002202 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroff47e7fa22008-03-15 00:55:56 +00002203 QualType FieldTypes[4];
2204
2205 // struct objc_object *receiver;
2206 FieldTypes[0] = Context->getObjCIdType();
2207 // int flags;
2208 FieldTypes[1] = Context->IntTy;
2209 // char *str;
2210 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2211 // long length;
2212 FieldTypes[3] = Context->LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002213
Steve Naroff47e7fa22008-03-15 00:55:56 +00002214 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002215 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002216 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002217 ConstantStringDecl,
2218 SourceLocation(), 0,
2219 FieldTypes[i],
2220 /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002221 /*Mutable=*/true));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002222 }
2223
2224 ConstantStringDecl->completeDefinition(*Context);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002225 }
2226 return Context->getTagDeclType(ConstantStringDecl);
2227}
2228
Steve Naroff44e81222008-04-14 22:03:09 +00002229Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00002230 if (!SelGetUidFunctionDecl)
2231 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002232 if (!MsgSendFunctionDecl)
2233 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002234 if (!MsgSendSuperFunctionDecl)
2235 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002236 if (!MsgSendStretFunctionDecl)
2237 SynthMsgSendStretFunctionDecl();
2238 if (!MsgSendSuperStretFunctionDecl)
2239 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002240 if (!MsgSendFpretFunctionDecl)
2241 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002242 if (!GetClassFunctionDecl)
2243 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002244 if (!GetMetaClassFunctionDecl)
2245 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002246
Steve Naroff764c1ae2007-11-15 10:28:18 +00002247 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002248 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2249 // May need to use objc_msgSend_stret() as well.
2250 FunctionDecl *MsgSendStretFlavor = 0;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002251 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2252 QualType resultType = OMD->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00002253 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002254 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00002255 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002256 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002257 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002258
Steve Naroff71226032007-10-24 22:48:43 +00002259 // Synthesize a call to objc_msgSend().
2260 llvm::SmallVector<Expr*, 8> MsgExprs;
2261 IdentifierInfo *clsName = Exp->getClassName();
2262
2263 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2264 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00002265 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2266 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002267 if (!strcmp(clsName->getName(), "super")) {
2268 MsgSendFlavor = MsgSendSuperFunctionDecl;
2269 if (MsgSendStretFlavor)
2270 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2271 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2272
Ted Kremenek42730c52008-01-07 19:49:32 +00002273 ObjCInterfaceDecl *SuperDecl =
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002274 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002275
2276 llvm::SmallVector<Expr*, 4> InitExprs;
2277
2278 // set the receiver to self, the first argument to all methods.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002279 InitExprs.push_back(new (Context) DeclRefExpr(
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002280 CurMethodDef->getSelfDecl(),
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002281 Context->getObjCIdType(),
2282 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002283 llvm::SmallVector<Expr*, 8> ClsExprs;
2284 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002285 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002286 SuperDecl->getIdentifier()->getName(),
2287 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002288 false, argType, SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002289 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2290 &ClsExprs[0],
2291 ClsExprs.size());
2292 // To turn off a warning, type-cast to 'id'
Douglas Gregor21a04f32008-10-27 19:41:14 +00002293 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002294 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002295 Cls, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002296 SourceLocation(), SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002297 // struct objc_super
2298 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002299 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002300
Steve Naroffdee066b2008-03-11 18:14:26 +00002301 if (LangOpts.Microsoft) {
2302 SynthSuperContructorFunctionDecl();
2303 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002304 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffdee066b2008-03-11 18:14:26 +00002305 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002306 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2307 InitExprs.size(),
2308 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002309 // The code for super is a little tricky to prevent collision with
2310 // the structure definition in the header. The rewriter has it's own
2311 // internal definition (__rw_objc_super) that is uses. This is why
2312 // we need the cast below. For example:
2313 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2314 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002315 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002316 Context->getPointerType(SuperRep->getType()),
2317 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002318 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002319 SuperRep, Context->getPointerType(superType),
2320 SourceLocation(), SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002321 } else {
2322 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002323 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffdee066b2008-03-11 18:14:26 +00002324 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002325 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002326 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner71ca8c82008-10-26 23:43:26 +00002327 false);
Steve Naroff12673622008-12-23 20:11:22 +00002328 // struct objc_super *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002329 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002330 Context->getPointerType(SuperRep->getType()),
2331 SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002332 }
Steve Naroff12673622008-12-23 20:11:22 +00002333 MsgExprs.push_back(SuperRep);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002334 } else {
2335 llvm::SmallVector<Expr*, 8> ClsExprs;
2336 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002337 ClsExprs.push_back(StringLiteral::Create(*Context,
2338 clsName->getName(),
2339 clsName->getLength(),
2340 false, argType,
2341 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002342 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2343 &ClsExprs[0],
2344 ClsExprs.size());
2345 MsgExprs.push_back(Cls);
2346 }
Steve Naroff885e2122007-11-14 23:54:14 +00002347 } else { // instance message.
2348 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002349
Ted Kremenek42730c52008-01-07 19:49:32 +00002350 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002351 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002352 if (MsgSendStretFlavor)
2353 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002354 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2355
2356 llvm::SmallVector<Expr*, 4> InitExprs;
2357
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002358 InitExprs.push_back(
Ted Kremenek0c97e042009-02-07 01:47:29 +00002359 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2360 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff23528612008-07-16 22:35:27 +00002361 Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002362 SourceLocation()),
2363 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002364 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002365
2366 llvm::SmallVector<Expr*, 8> ClsExprs;
2367 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002368 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002369 SuperDecl->getIdentifier()->getName(),
2370 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002371 false, argType, SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002372 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002373 &ClsExprs[0],
2374 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002375 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002376 InitExprs.push_back(
Douglas Gregor21a04f32008-10-27 19:41:14 +00002377 // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002378 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002379 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002380 // struct objc_super
2381 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002382 Expr *SuperRep;
2383
2384 if (LangOpts.Microsoft) {
2385 SynthSuperContructorFunctionDecl();
2386 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002387 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffbec4bf52008-03-11 17:37:02 +00002388 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002389 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2390 InitExprs.size(),
2391 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002392 // The code for super is a little tricky to prevent collision with
2393 // the structure definition in the header. The rewriter has it's own
2394 // internal definition (__rw_objc_super) that is uses. This is why
2395 // we need the cast below. For example:
2396 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2397 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002398 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002399 Context->getPointerType(SuperRep->getType()),
2400 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002401 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002402 SuperRep, Context->getPointerType(superType),
2403 SourceLocation(), SourceLocation());
Steve Naroffbec4bf52008-03-11 17:37:02 +00002404 } else {
2405 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002406 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00002407 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002408 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002409 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00002410 }
Steve Naroff12673622008-12-23 20:11:22 +00002411 MsgExprs.push_back(SuperRep);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002412 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002413 // Remove all type-casts because it may contain objc-style types; e.g.
2414 // Foo<Proto> *.
Douglas Gregor035d0882008-10-28 15:36:24 +00002415 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002416 recExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002417 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002418 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002419 SourceLocation(), SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002420 MsgExprs.push_back(recExpr);
2421 }
Steve Naroff885e2122007-11-14 23:54:14 +00002422 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002423 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002424 llvm::SmallVector<Expr*, 8> SelExprs;
2425 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002426 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002427 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00002428 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002429 false, argType, SourceLocation()));
Steve Naroff71226032007-10-24 22:48:43 +00002430 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2431 &SelExprs[0], SelExprs.size());
2432 MsgExprs.push_back(SelExp);
2433
2434 // Now push any user supplied arguments.
2435 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002436 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002437 // Make all implicit casts explicit...ICE comes in handy:-)
2438 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2439 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor21a04f32008-10-27 19:41:14 +00002440 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002441 ? Context->getObjCIdType()
Douglas Gregor21a04f32008-10-27 19:41:14 +00002442 : ICE->getType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002443 userExpr = new (Context) CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002444 }
2445 // Make id<P...> cast into an 'id' cast.
Douglas Gregor035d0882008-10-28 15:36:24 +00002446 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002447 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor035d0882008-10-28 15:36:24 +00002448 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002449 userExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002450 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002451 userExpr, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002452 SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002453 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002454 }
Steve Naroff885e2122007-11-14 23:54:14 +00002455 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002456 // We've transferred the ownership to MsgExprs. Null out the argument in
2457 // the original expression, since we will delete it below.
2458 Exp->setArg(i, 0);
2459 }
Steve Naroff0744c472007-11-04 22:37:50 +00002460 // Generate the funky cast.
2461 CastExpr *cast;
2462 llvm::SmallVector<QualType, 8> ArgTypes;
2463 QualType returnType;
2464
2465 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002466 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2467 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2468 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002469 ArgTypes.push_back(Context->getObjCIdType());
2470 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002471 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002472 // Push any user argument types.
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002473 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2474 E = OMD->param_end(); PI != E; ++PI) {
2475 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002476 ? Context->getObjCIdType()
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002477 : (*PI)->getType();
Steve Naroff66c842f2008-10-29 14:49:46 +00002478 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00002479 if (isTopLevelBlockPointerType(t)) {
Steve Naroff66c842f2008-10-29 14:49:46 +00002480 const BlockPointerType *BPT = t->getAsBlockPointerType();
2481 t = Context->getPointerType(BPT->getPointeeType());
2482 }
Steve Naroff4242b972007-11-05 14:36:37 +00002483 ArgTypes.push_back(t);
2484 }
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002485 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2486 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002487 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002488 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002489 }
2490 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002491 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002492
2493 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002494 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002495 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002496
2497 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2498 // If we don't do this cast, we get the following bizarre warning/note:
2499 // xx.m:13: warning: function called through a non-compatible type
2500 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek0c97e042009-02-07 01:47:29 +00002501 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002502 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002503 SourceLocation(), SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002504
Steve Naroff0744c472007-11-04 22:37:50 +00002505 // Now do the "normal" pointer to function cast.
2506 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002507 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002508 // If we don't have a method decl, force a variadic cast.
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002509 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroff0744c472007-11-04 22:37:50 +00002510 castType = Context->getPointerType(castType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002511 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002512
2513 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002514 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroff0744c472007-11-04 22:37:50 +00002515
2516 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002517 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2518 MsgExprs.size(),
2519 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002520 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002521 if (MsgSendStretFlavor) {
2522 // We have the method which returns a struct/union. Must also generate
2523 // call to objc_msgSend_stret and hang both varieties on a conditional
2524 // expression which dictate which one to envoke depending on size of
2525 // method's return type.
2526
2527 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002528 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002529 SourceLocation());
2530 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek0c97e042009-02-07 01:47:29 +00002531 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002532 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002533 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002534 // Now do the "normal" pointer to function cast.
2535 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002536 &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002537 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002538 castType = Context->getPointerType(castType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002539 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002540
2541 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002542 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002543
2544 FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002545 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2546 MsgExprs.size(),
2547 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002548
2549 // Build sizeof(returnType)
Douglas Gregor396f1142009-03-13 21:01:28 +00002550 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
2551 returnType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002552 Context->getSizeType(),
2553 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002554 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2555 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2556 // For X86 it is more complicated and some kind of target specific routine
2557 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002558 unsigned IntSize =
2559 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek0c97e042009-02-07 01:47:29 +00002560 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002561 Context->IntTy,
2562 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002563 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002564 BinaryOperator::LE,
2565 Context->IntTy,
2566 SourceLocation());
2567 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2568 ConditionalOperator *CondExpr =
Ted Kremenek0c97e042009-02-07 01:47:29 +00002569 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2570 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002571 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002572 return ReplacingStmt;
2573}
2574
Steve Naroff44e81222008-04-14 22:03:09 +00002575Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002576 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroffe8efe892008-10-27 20:54:44 +00002577
Steve Naroff0e948412008-12-04 16:24:46 +00002578 //ReplacingStmt->dump();
Steve Naroff71226032007-10-24 22:48:43 +00002579 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002580 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002581
Steve Naroff102c3f22008-12-04 23:50:32 +00002582 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002583 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002584}
2585
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002586/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2587/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002588Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002589 if (!GetProtocolFunctionDecl)
2590 SynthGetProtocolFunctionDecl();
2591 // Create a call to objc_getProtocol("ProtocolName").
2592 llvm::SmallVector<Expr*, 8> ProtoExprs;
2593 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002594 ProtoExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002595 Exp->getProtocol()->getNameAsCString(),
2596 strlen(Exp->getProtocol()->getNameAsCString()),
Chris Lattnerc3144742009-02-18 05:49:11 +00002597 false, argType, SourceLocation()));
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002598 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2599 &ProtoExprs[0],
2600 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002601 ReplaceStmt(Exp, ProtoExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00002602 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002603 return ProtoExp;
2604
2605}
2606
Steve Naroffef82b742008-05-31 14:15:04 +00002607bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2608 const char *endBuf) {
2609 while (startBuf < endBuf) {
2610 if (*startBuf == '#') {
2611 // Skip whitespace.
2612 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2613 ;
2614 if (!strncmp(startBuf, "if", strlen("if")) ||
2615 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2616 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2617 !strncmp(startBuf, "define", strlen("define")) ||
2618 !strncmp(startBuf, "undef", strlen("undef")) ||
2619 !strncmp(startBuf, "else", strlen("else")) ||
2620 !strncmp(startBuf, "elif", strlen("elif")) ||
2621 !strncmp(startBuf, "endif", strlen("endif")) ||
2622 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2623 !strncmp(startBuf, "include", strlen("include")) ||
2624 !strncmp(startBuf, "import", strlen("import")) ||
2625 !strncmp(startBuf, "include_next", strlen("include_next")))
2626 return true;
2627 }
2628 startBuf++;
2629 }
2630 return false;
2631}
2632
Ted Kremenek42730c52008-01-07 19:49:32 +00002633/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002634/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002635void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002636 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002637 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002638 assert(CDecl->getNameAsCString() &&
Douglas Gregor24afd4a2008-11-17 14:58:09 +00002639 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002640 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002641 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002642 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002643 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002644 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002645 SourceLocation LocStart = CDecl->getLocStart();
2646 SourceLocation LocEnd = CDecl->getLocEnd();
2647
2648 const char *startBuf = SM->getCharacterData(LocStart);
2649 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002650
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002651 // If no ivars and no root or if its root, directly or indirectly,
2652 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002653 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2654 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002655 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002656 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002657 return;
2658 }
2659
2660 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002661 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002662 Result += "\nstruct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002663 Result += CDecl->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +00002664 if (LangOpts.Microsoft)
2665 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002666
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002667 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002668 const char *cursor = strchr(startBuf, '{');
2669 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002670 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002671 // If the buffer contains preprocessor directives, we do more fine-grained
2672 // rewrites. This is intended to fix code that looks like (which occurs in
2673 // NSURL.h, for example):
2674 //
2675 // #ifdef XYZ
2676 // @interface Foo : NSObject
2677 // #else
2678 // @interface FooBar : NSObject
2679 // #endif
2680 // {
2681 // int i;
2682 // }
2683 // @end
2684 //
2685 // This clause is segregated to avoid breaking the common case.
2686 if (BufferContainsPPDirectives(startBuf, cursor)) {
2687 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2688 CDecl->getClassLoc();
2689 const char *endHeader = SM->getCharacterData(L);
2690 endHeader += Lexer::MeasureTokenLength(L, *SM);
2691
Chris Lattner179fd522009-02-20 18:18:36 +00002692 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002693 // advance to the end of the referenced protocols.
2694 while (endHeader < cursor && *endHeader != '>') endHeader++;
2695 endHeader++;
2696 }
2697 // rewrite the original header
2698 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2699 } else {
2700 // rewrite the original header *without* disturbing the '{'
2701 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2702 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002703 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002704 Result = "\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002705 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002706 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002707 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002708 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002709
2710 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002711 SourceLocation OnePastCurly =
2712 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2713 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002714 }
2715 cursor++; // past '{'
2716
2717 // Now comment out any visibility specifiers.
2718 while (cursor < endBuf) {
2719 if (*cursor == '@') {
2720 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002721 // Skip whitespace.
2722 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2723 /*scan*/;
2724
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002725 // FIXME: presence of @public, etc. inside comment results in
2726 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002727 if (!strncmp(cursor, "public", strlen("public")) ||
2728 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002729 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002730 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002731 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002732 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002733 // FIXME: If there are cases where '<' is used in ivar declaration part
2734 // of user code, then scan the ivar list and use needToScanForQualifiers
2735 // for type checking.
2736 else if (*cursor == '<') {
2737 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002738 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002739 cursor = strchr(cursor, '>');
2740 cursor++;
2741 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002742 InsertText(atLoc, " */", 3);
Steve Naroff6449c6c2008-10-30 12:09:33 +00002743 } else if (*cursor == '^') { // rewrite block specifier.
2744 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2745 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002746 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002747 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002748 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002749 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002750 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002751 } else { // we don't have any instance variables - insert super struct.
2752 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2753 Result += " {\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002754 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002755 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002756 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002757 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002758 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002759 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002760 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002761 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002762 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002763}
2764
Ted Kremenek42730c52008-01-07 19:49:32 +00002765// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002766/// class methods.
Steve Naroff44e81222008-04-14 22:03:09 +00002767void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002768 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002769 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002770 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002771 const char *ClassName,
2772 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002773 if (MethodBegin == MethodEnd) return;
2774
Fariborz Jahanian04455192007-10-22 21:41:37 +00002775 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002776 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002777 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002778 SEL _cmd;
2779 char *method_types;
2780 void *_imp;
2781 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002782 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002783 Result += "\nstruct _objc_method {\n";
2784 Result += "\tSEL _cmd;\n";
2785 Result += "\tchar *method_types;\n";
2786 Result += "\tvoid *_imp;\n";
2787 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002788
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002789 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002790 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002791
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002792 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002793
2794 /* struct {
2795 struct _objc_method_list *next_method;
2796 int method_count;
2797 struct _objc_method method_list[];
2798 }
2799 */
2800 Result += "\nstatic struct {\n";
2801 Result += "\tstruct _objc_method_list *next_method;\n";
2802 Result += "\tint method_count;\n";
2803 Result += "\tstruct _objc_method method_list[";
2804 Result += utostr(MethodEnd-MethodBegin);
2805 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002806 Result += prefix;
2807 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2808 Result += "_METHODS_";
2809 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002810 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002811 Result += IsInstanceMethod ? "inst" : "cls";
2812 Result += "_meth\")))= ";
2813 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002814
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002815 Result += "\t,{{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002816 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002817 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002818 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002819 Result += "\", \"";
2820 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002821 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002822 Result += MethodInternalNames[*MethodBegin];
2823 Result += "}\n";
2824 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2825 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002826 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002827 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002828 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002829 Result += "\", \"";
2830 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002831 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002832 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002833 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002834 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002835 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002836}
2837
Ted Kremenek42730c52008-01-07 19:49:32 +00002838/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002839void RewriteObjC::
2840RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2841 const char *prefix,
2842 const char *ClassName,
2843 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002844 static bool objc_protocol_methods = false;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002845 if (Protocols.empty()) return;
2846
2847 for (unsigned i = 0; i != Protocols.size(); i++) {
2848 ObjCProtocolDecl *PDecl = Protocols[i];
2849 // Output struct protocol_methods holder of method selector and type.
2850 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2851 /* struct protocol_methods {
2852 SEL _cmd;
2853 char *method_types;
2854 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002855 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002856 Result += "\nstruct protocol_methods {\n";
2857 Result += "\tSEL _cmd;\n";
2858 Result += "\tchar *method_types;\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002859 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002860
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002861 objc_protocol_methods = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002862 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002863 // Do not synthesize the protocol more than once.
2864 if (ObjCSynthesizedProtocols.count(PDecl))
2865 continue;
2866
2867 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Chris Lattner179fd522009-02-20 18:18:36 +00002868 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
2869 PDecl->instmeth_end());
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002870 /* struct _objc_protocol_method_list {
2871 int protocol_method_count;
2872 struct protocol_methods protocols[];
2873 }
2874 */
2875 Result += "\nstatic struct {\n";
2876 Result += "\tint protocol_method_count;\n";
2877 Result += "\tstruct protocol_methods protocols[";
2878 Result += utostr(NumMethods);
2879 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002880 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002881 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2882 "{\n\t" + utostr(NumMethods) + "\n";
2883
2884 // Output instance methods declared in this protocol.
2885 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2886 E = PDecl->instmeth_end(); I != E; ++I) {
2887 if (I == PDecl->instmeth_begin())
2888 Result += "\t ,{{(SEL)\"";
2889 else
2890 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002891 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002892 std::string MethodTypeString;
2893 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2894 Result += "\", \"";
2895 Result += MethodTypeString;
2896 Result += "\"}\n";
2897 }
2898 Result += "\t }\n};\n";
2899 }
2900
2901 // Output class methods declared in this protocol.
Chris Lattner179fd522009-02-20 18:18:36 +00002902 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
2903 PDecl->classmeth_end());
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002904 if (NumMethods > 0) {
2905 /* struct _objc_protocol_method_list {
2906 int protocol_method_count;
2907 struct protocol_methods protocols[];
2908 }
2909 */
2910 Result += "\nstatic struct {\n";
2911 Result += "\tint protocol_method_count;\n";
2912 Result += "\tstruct protocol_methods protocols[";
2913 Result += utostr(NumMethods);
2914 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002915 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002916 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2917 "{\n\t";
2918 Result += utostr(NumMethods);
2919 Result += "\n";
2920
2921 // Output instance methods declared in this protocol.
2922 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2923 E = PDecl->classmeth_end(); I != E; ++I) {
2924 if (I == PDecl->classmeth_begin())
2925 Result += "\t ,{{(SEL)\"";
2926 else
2927 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002928 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002929 std::string MethodTypeString;
2930 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2931 Result += "\", \"";
2932 Result += MethodTypeString;
2933 Result += "\"}\n";
2934 }
2935 Result += "\t }\n};\n";
2936 }
2937
2938 // Output:
2939 /* struct _objc_protocol {
2940 // Objective-C 1.0 extensions
2941 struct _objc_protocol_extension *isa;
2942 char *protocol_name;
2943 struct _objc_protocol **protocol_list;
2944 struct _objc_protocol_method_list *instance_methods;
2945 struct _objc_protocol_method_list *class_methods;
2946 };
Steve Naroff27429432008-03-12 01:06:30 +00002947 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002948 static bool objc_protocol = false;
2949 if (!objc_protocol) {
2950 Result += "\nstruct _objc_protocol {\n";
2951 Result += "\tstruct _objc_protocol_extension *isa;\n";
2952 Result += "\tchar *protocol_name;\n";
2953 Result += "\tstruct _objc_protocol **protocol_list;\n";
2954 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2955 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2956 Result += "};\n";
2957
2958 objc_protocol = true;
2959 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002960
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002961 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002962 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002963 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2964 "{\n\t0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00002965 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002966 Result += "\", 0, ";
2967 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2968 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002969 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002970 Result += ", ";
2971 }
2972 else
2973 Result += "0, ";
Chris Lattner179fd522009-02-20 18:18:36 +00002974 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002975 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002976 Result += PDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002977 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002978 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002979 else
2980 Result += "0\n";
2981 Result += "};\n";
2982
2983 // Mark this protocol as having been generated.
2984 if (!ObjCSynthesizedProtocols.insert(PDecl))
2985 assert(false && "protocol already synthesized");
2986 }
2987 // Output the top lovel protocol meta-data for the class.
2988 /* struct _objc_protocol_list {
2989 struct _objc_protocol_list *next;
2990 int protocol_count;
2991 struct _objc_protocol *class_protocols[];
2992 }
2993 */
2994 Result += "\nstatic struct {\n";
2995 Result += "\tstruct _objc_protocol_list *next;\n";
2996 Result += "\tint protocol_count;\n";
2997 Result += "\tstruct _objc_protocol *class_protocols[";
2998 Result += utostr(Protocols.size());
2999 Result += "];\n} _OBJC_";
3000 Result += prefix;
3001 Result += "_PROTOCOLS_";
3002 Result += ClassName;
3003 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3004 "{\n\t0, ";
3005 Result += utostr(Protocols.size());
3006 Result += "\n";
3007
3008 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003009 Result += Protocols[0]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003010 Result += " \n";
3011
3012 for (unsigned i = 1; i != Protocols.size(); i++) {
3013 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003014 Result += Protocols[i]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003015 Result += "\n";
3016 }
3017 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003018}
3019
Ted Kremenek42730c52008-01-07 19:49:32 +00003020/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003021/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00003022void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003023 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003024 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003025 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003026 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003027 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3028 CDecl = CDecl->getNextClassCategory())
3029 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3030 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003031
Chris Lattner271d4c22008-11-24 05:29:24 +00003032 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00003033 FullCategoryName += '_';
Chris Lattner271d4c22008-11-24 05:29:24 +00003034 FullCategoryName += IDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00003035
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003036 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00003037 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003038 true, "CATEGORY_", FullCategoryName.c_str(),
3039 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003040
3041 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00003042 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003043 false, "CATEGORY_", FullCategoryName.c_str(),
3044 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003045
3046 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00003047 // Null CDecl is case of a category implementation with no category interface
3048 if (CDecl)
Chris Lattner0be08822008-07-21 21:32:27 +00003049 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00003050 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003051
3052 /* struct _objc_category {
3053 char *category_name;
3054 char *class_name;
3055 struct _objc_method_list *instance_methods;
3056 struct _objc_method_list *class_methods;
3057 struct _objc_protocol_list *protocols;
3058 // Objective-C 1.0 extensions
3059 uint32_t size; // sizeof (struct _objc_category)
3060 struct _objc_property_list *instance_properties; // category's own
3061 // @property decl.
3062 };
3063 */
3064
3065 static bool objc_category = false;
3066 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003067 Result += "\nstruct _objc_category {\n";
3068 Result += "\tchar *category_name;\n";
3069 Result += "\tchar *class_name;\n";
3070 Result += "\tstruct _objc_method_list *instance_methods;\n";
3071 Result += "\tstruct _objc_method_list *class_methods;\n";
3072 Result += "\tstruct _objc_protocol_list *protocols;\n";
3073 Result += "\tunsigned int size;\n";
3074 Result += "\tstruct _objc_property_list *instance_properties;\n";
3075 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003076 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00003077 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003078 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3079 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00003080 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003081 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003082 Result += "\"\n\t, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003083 Result += ClassDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003084 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003085
Chris Lattner179fd522009-02-20 18:18:36 +00003086 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003087 Result += "\t, (struct _objc_method_list *)"
3088 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3089 Result += FullCategoryName;
3090 Result += "\n";
3091 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003092 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003093 Result += "\t, 0\n";
Chris Lattner179fd522009-02-20 18:18:36 +00003094 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003095 Result += "\t, (struct _objc_method_list *)"
3096 "&_OBJC_CATEGORY_CLASS_METHODS_";
3097 Result += FullCategoryName;
3098 Result += "\n";
3099 }
3100 else
3101 Result += "\t, 0\n";
3102
Chris Lattner179fd522009-02-20 18:18:36 +00003103 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003104 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3105 Result += FullCategoryName;
3106 Result += "\n";
3107 }
3108 else
3109 Result += "\t, 0\n";
3110 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003111}
3112
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003113/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3114/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00003115void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00003116 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003117 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00003118 if (ivar->isBitField()) {
3119 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3120 // place all bitfields at offset 0.
3121 Result += "0";
3122 } else {
3123 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003124 Result += IDecl->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003125 if (LangOpts.Microsoft)
3126 Result += "_IMPL";
3127 Result += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003128 Result += ivar->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003129 Result += ")";
3130 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003131}
3132
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003133//===----------------------------------------------------------------------===//
3134// Meta Data Emission
3135//===----------------------------------------------------------------------===//
3136
Steve Naroff44e81222008-04-14 22:03:09 +00003137void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003138 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003139 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003140
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003141 // Explictly declared @interface's are already synthesized.
3142 if (CDecl->ImplicitInterfaceDecl()) {
3143 // FIXME: Implementation of a class with no @interface (legacy) doese not
3144 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00003145 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003146 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003147
Chris Lattnerc7b06752007-12-12 07:56:42 +00003148 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00003149 unsigned NumIvars = !IDecl->ivar_empty()
3150 ? IDecl->ivar_size()
3151 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003152 if (NumIvars > 0) {
3153 static bool objc_ivar = false;
3154 if (!objc_ivar) {
3155 /* struct _objc_ivar {
3156 char *ivar_name;
3157 char *ivar_type;
3158 int ivar_offset;
3159 };
3160 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003161 Result += "\nstruct _objc_ivar {\n";
3162 Result += "\tchar *ivar_name;\n";
3163 Result += "\tchar *ivar_type;\n";
3164 Result += "\tint ivar_offset;\n";
3165 Result += "};\n";
3166
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003167 objc_ivar = true;
3168 }
3169
Steve Naroffc723eec2008-03-11 00:12:29 +00003170 /* struct {
3171 int ivar_count;
3172 struct _objc_ivar ivar_list[nIvars];
3173 };
3174 */
3175 Result += "\nstatic struct {\n";
3176 Result += "\tint ivar_count;\n";
3177 Result += "\tstruct _objc_ivar ivar_list[";
3178 Result += utostr(NumIvars);
3179 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003180 Result += IDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003181 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003182 "{\n\t";
3183 Result += utostr(NumIvars);
3184 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003185
Ted Kremenek42730c52008-01-07 19:49:32 +00003186 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00003187 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00003188 IVI = IDecl->ivar_begin();
3189 IVE = IDecl->ivar_end();
3190 } else {
3191 IVI = CDecl->ivar_begin();
3192 IVE = CDecl->ivar_end();
3193 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003194 Result += "\t,{{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003195 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003196 Result += "\", \"";
3197 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00003198 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003199 Result += StrEncoding;
3200 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003201 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003202 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003203 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003204 Result += "\t ,{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003205 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003206 Result += "\", \"";
3207 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00003208 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003209 Result += StrEncoding;
3210 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003211 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003212 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003213 }
3214
3215 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003216 }
3217
3218 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00003219 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003220 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003221
3222 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00003223 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003224 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003225
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003226 // Protocols referenced in class declaration?
Chris Lattner0be08822008-07-21 21:32:27 +00003227 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003228 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003229
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003230
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003231 // Declaration of class/meta-class metadata
3232 /* struct _objc_class {
3233 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003234 const char *super_class_name;
3235 char *name;
3236 long version;
3237 long info;
3238 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003239 struct _objc_ivar_list *ivars;
3240 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003241 struct objc_cache *cache;
3242 struct objc_protocol_list *protocols;
3243 const char *ivar_layout;
3244 struct _objc_class_ext *ext;
3245 };
3246 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003247 static bool objc_class = false;
3248 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003249 Result += "\nstruct _objc_class {\n";
3250 Result += "\tstruct _objc_class *isa;\n";
3251 Result += "\tconst char *super_class_name;\n";
3252 Result += "\tchar *name;\n";
3253 Result += "\tlong version;\n";
3254 Result += "\tlong info;\n";
3255 Result += "\tlong instance_size;\n";
3256 Result += "\tstruct _objc_ivar_list *ivars;\n";
3257 Result += "\tstruct _objc_method_list *methods;\n";
3258 Result += "\tstruct objc_cache *cache;\n";
3259 Result += "\tstruct _objc_protocol_list *protocols;\n";
3260 Result += "\tconst char *ivar_layout;\n";
3261 Result += "\tstruct _objc_class_ext *ext;\n";
3262 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003263 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003264 }
3265
3266 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003267 ObjCInterfaceDecl *RootClass = 0;
3268 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003269 while (SuperClass) {
3270 RootClass = SuperClass;
3271 SuperClass = SuperClass->getSuperClass();
3272 }
3273 SuperClass = CDecl->getSuperClass();
3274
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003275 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003276 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003277 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003278 "{\n\t(struct _objc_class *)\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003279 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003280 Result += "\"";
3281
3282 if (SuperClass) {
3283 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003284 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003285 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003286 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003287 Result += "\"";
3288 }
3289 else {
3290 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003291 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003292 Result += "\"";
3293 }
Ted Kremenek42730c52008-01-07 19:49:32 +00003294 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003295 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003296 Result += ", 0,2, sizeof(struct _objc_class), 0";
Chris Lattner5c6b2c62009-02-20 18:43:26 +00003297 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003298 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003299 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003300 Result += "\n";
3301 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003302 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003303 Result += ", 0\n";
Chris Lattner179fd522009-02-20 18:18:36 +00003304 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003305 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003306 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003307 Result += ",0,0\n";
3308 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003309 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003310 Result += "\t,0,0,0,0\n";
3311 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003312
3313 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003314 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003315 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003316 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003317 "{\n\t&_OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003318 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003319 if (SuperClass) {
3320 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003321 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003322 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003323 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003324 Result += "\"";
3325 }
3326 else {
3327 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003328 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003329 Result += "\"";
3330 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003331 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003332 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003333 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003334 Result += ",0";
3335 else {
3336 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003337 Result += ",sizeof(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003338 Result += CDecl->getNameAsString();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003339 if (LangOpts.Microsoft)
3340 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003341 Result += ")";
3342 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003343 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003344 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003345 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003346 Result += "\n\t";
3347 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003348 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003349 Result += ",0";
Chris Lattner5c6b2c62009-02-20 18:43:26 +00003350 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003351 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003352 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003353 Result += ", 0\n\t";
3354 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003355 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003356 Result += ",0,0";
Chris Lattner179fd522009-02-20 18:18:36 +00003357 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003358 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003359 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003360 Result += ", 0,0\n";
3361 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003362 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003363 Result += ",0,0,0\n";
3364 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003365}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003366
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003367/// RewriteImplementations - This routine rewrites all method implementations
3368/// and emits meta-data.
3369
Steve Naroff21658f62008-11-13 20:07:04 +00003370void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003371 int ClsDefCount = ClassImplementation.size();
3372 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003373
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003374 // Rewrite implemented methods
3375 for (int i = 0; i < ClsDefCount; i++)
3376 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003377
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003378 for (int i = 0; i < CatDefCount; i++)
3379 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Naroff21658f62008-11-13 20:07:04 +00003380}
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003381
Steve Naroff21658f62008-11-13 20:07:04 +00003382void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3383 int ClsDefCount = ClassImplementation.size();
3384 int CatDefCount = CategoryImplementation.size();
3385
Steve Naroff5bf10222008-05-07 21:23:49 +00003386 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003387 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003388 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003389 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003390 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003391
3392 // For each implemented category, write out all its meta data.
3393 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003394 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003395
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003396 // Write objc_symtab metadata
3397 /*
3398 struct _objc_symtab
3399 {
3400 long sel_ref_cnt;
3401 SEL *refs;
3402 short cls_def_cnt;
3403 short cat_def_cnt;
3404 void *defs[cls_def_cnt + cat_def_cnt];
3405 };
3406 */
3407
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003408 Result += "\nstruct _objc_symtab {\n";
3409 Result += "\tlong sel_ref_cnt;\n";
3410 Result += "\tSEL *refs;\n";
3411 Result += "\tshort cls_def_cnt;\n";
3412 Result += "\tshort cat_def_cnt;\n";
3413 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3414 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003415
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003416 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003417 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003418 Result += "\t0, 0, " + utostr(ClsDefCount)
3419 + ", " + utostr(CatDefCount) + "\n";
3420 for (int i = 0; i < ClsDefCount; i++) {
3421 Result += "\t,&_OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003422 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003423 Result += "\n";
3424 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003425
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003426 for (int i = 0; i < CatDefCount; i++) {
3427 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003428 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003429 Result += "_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003430 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003431 Result += "\n";
3432 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003433
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003434 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003435
3436 // Write objc_module metadata
3437
3438 /*
3439 struct _objc_module {
3440 long version;
3441 long size;
3442 const char *name;
3443 struct _objc_symtab *symtab;
3444 }
3445 */
3446
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003447 Result += "\nstruct _objc_module {\n";
3448 Result += "\tlong version;\n";
3449 Result += "\tlong size;\n";
3450 Result += "\tconst char *name;\n";
3451 Result += "\tstruct _objc_symtab *symtab;\n";
3452 Result += "};\n\n";
3453 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003454 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003455 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3456 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003457 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003458
3459 if (LangOpts.Microsoft) {
3460 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003461 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003462 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3463 Result += "&_OBJC_MODULES;\n";
3464 Result += "#pragma data_seg(pop)\n\n";
3465 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003466}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003467
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003468std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3469 const char *funcName,
3470 std::string Tag) {
3471 const FunctionType *AFT = CE->getFunctionType();
3472 QualType RT = AFT->getResultType();
3473 std::string StructRef = "struct " + Tag;
3474 std::string S = "static " + RT.getAsString() + " __" +
3475 funcName + "_" + "block_func_" + utostr(i);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003476
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003477 BlockDecl *BD = CE->getBlockDecl();
3478
Douglas Gregor4fa58902009-02-26 23:50:07 +00003479 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroff16478cf2009-02-02 17:19:26 +00003480 // No user-supplied arguments. Still need to pass in a pointer to the
3481 // block (to reference imported block decl refs).
3482 S += "(" + StructRef + " *__cself)";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003483 } else if (BD->param_empty()) {
3484 S += "(" + StructRef + " *__cself)";
3485 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003486 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003487 assert(FT && "SynthesizeBlockFunc: No function proto");
3488 S += '(';
3489 // first add the implicit argument.
3490 S += StructRef + " *__cself, ";
3491 std::string ParamStr;
3492 for (BlockDecl::param_iterator AI = BD->param_begin(),
3493 E = BD->param_end(); AI != E; ++AI) {
3494 if (AI != BD->param_begin()) S += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003495 ParamStr = (*AI)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003496 (*AI)->getType().getAsStringInternal(ParamStr);
3497 S += ParamStr;
3498 }
3499 if (FT->isVariadic()) {
3500 if (!BD->param_empty()) S += ", ";
3501 S += "...";
3502 }
3503 S += ')';
3504 }
3505 S += " {\n";
3506
3507 // Create local declarations to avoid rewriting all closure decl ref exprs.
3508 // First, emit a declaration for all "by ref" decls.
3509 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3510 E = BlockByRefDecls.end(); I != E; ++I) {
3511 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003512 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003513 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003514 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003515 }
3516 // Next, emit a declaration for all "by copy" declarations.
3517 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3518 E = BlockByCopyDecls.end(); I != E; ++I) {
3519 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003520 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003521 // Handle nested closure invocation. For example:
3522 //
3523 // void (^myImportedClosure)(void);
3524 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3525 //
3526 // void (^anotherClosure)(void);
3527 // anotherClosure = ^(void) {
3528 // myImportedClosure(); // import and invoke the closure
3529 // };
3530 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003531 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003532 S += "struct __block_impl *";
3533 else
3534 (*I)->getType().getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003535 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003536 }
3537 std::string RewrittenStr = RewrittenBlockExprs[CE];
3538 const char *cstr = RewrittenStr.c_str();
3539 while (*cstr++ != '{') ;
3540 S += cstr;
3541 S += "\n";
3542 return S;
3543}
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003544
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003545std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3546 const char *funcName,
3547 std::string Tag) {
3548 std::string StructRef = "struct " + Tag;
3549 std::string S = "static void __";
3550
3551 S += funcName;
3552 S += "_block_copy_" + utostr(i);
3553 S += "(" + StructRef;
3554 S += "*dst, " + StructRef;
3555 S += "*src) {";
3556 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3557 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003558 S += "_Block_object_assign((void*)&dst->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003559 S += (*I)->getNameAsString();
Steve Naroff1d56d9e2008-12-11 20:51:38 +00003560 S += ", (void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003561 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003562 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003563 }
3564 S += "\nstatic void __";
3565 S += funcName;
3566 S += "_block_dispose_" + utostr(i);
3567 S += "(" + StructRef;
3568 S += "*src) {";
3569 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3570 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003571 S += "_Block_object_dispose((void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003572 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003573 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003574 }
3575 S += "}\n";
3576 return S;
3577}
3578
3579std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3580 bool hasCopyDisposeHelpers) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003581 std::string S = "\nstruct " + Tag;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003582 std::string Constructor = " " + Tag;
3583
3584 S += " {\n struct __block_impl impl;\n";
3585
3586 if (hasCopyDisposeHelpers)
3587 S += " void *copy;\n void *dispose;\n";
3588
3589 Constructor += "(void *fp";
3590
3591 if (hasCopyDisposeHelpers)
3592 Constructor += ", void *copyHelp, void *disposeHelp";
3593
3594 if (BlockDeclRefs.size()) {
3595 // Output all "by copy" declarations.
3596 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3597 E = BlockByCopyDecls.end(); I != E; ++I) {
3598 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003599 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003600 std::string ArgName = "_" + FieldName;
3601 // Handle nested closure invocation. For example:
3602 //
3603 // void (^myImportedBlock)(void);
3604 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3605 //
3606 // void (^anotherBlock)(void);
3607 // anotherBlock = ^(void) {
3608 // myImportedBlock(); // import and invoke the closure
3609 // };
3610 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003611 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003612 S += "struct __block_impl *";
3613 Constructor += ", void *" + ArgName;
3614 } else {
3615 (*I)->getType().getAsStringInternal(FieldName);
3616 (*I)->getType().getAsStringInternal(ArgName);
3617 Constructor += ", " + ArgName;
3618 }
3619 S += FieldName + ";\n";
3620 }
3621 // Output all "by ref" declarations.
3622 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3623 E = BlockByRefDecls.end(); I != E; ++I) {
3624 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003625 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003626 std::string ArgName = "_" + FieldName;
3627 // Handle nested closure invocation. For example:
3628 //
3629 // void (^myImportedBlock)(void);
3630 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3631 //
3632 // void (^anotherBlock)(void);
3633 // anotherBlock = ^(void) {
3634 // myImportedBlock(); // import and invoke the closure
3635 // };
3636 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003637 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003638 S += "struct __block_impl *";
3639 Constructor += ", void *" + ArgName;
3640 } else {
3641 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3642 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3643 Constructor += ", " + ArgName;
3644 }
3645 S += FieldName + "; // by ref\n";
3646 }
3647 // Finish writing the constructor.
3648 // FIXME: handle NSConcreteGlobalBlock.
3649 Constructor += ", int flags=0) {\n";
3650 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3651 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3652
3653 if (hasCopyDisposeHelpers)
3654 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3655
3656 // Initialize all "by copy" arguments.
3657 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3658 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003659 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003660 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003661 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003662 Constructor += Name + " = (struct __block_impl *)_";
3663 else
3664 Constructor += Name + " = _";
3665 Constructor += Name + ";\n";
3666 }
3667 // Initialize all "by ref" arguments.
3668 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3669 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003670 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003671 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003672 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003673 Constructor += Name + " = (struct __block_impl *)_";
3674 else
3675 Constructor += Name + " = _";
3676 Constructor += Name + ";\n";
3677 }
3678 } else {
3679 // Finish writing the constructor.
3680 // FIXME: handle NSConcreteGlobalBlock.
3681 Constructor += ", int flags=0) {\n";
3682 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3683 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3684 if (hasCopyDisposeHelpers)
3685 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3686 }
3687 Constructor += " ";
3688 Constructor += "}\n";
3689 S += Constructor;
3690 S += "};\n";
3691 return S;
3692}
3693
3694void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3695 const char *FunName) {
3696 // Insert closures that were part of the function.
3697 for (unsigned i = 0; i < Blocks.size(); i++) {
3698
3699 CollectBlockDeclRefInfo(Blocks[i]);
3700
3701 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3702
3703 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3704 ImportedBlockDecls.size() > 0);
3705
3706 InsertText(FunLocStart, CI.c_str(), CI.size());
3707
3708 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3709
3710 InsertText(FunLocStart, CF.c_str(), CF.size());
3711
3712 if (ImportedBlockDecls.size()) {
3713 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3714 InsertText(FunLocStart, HF.c_str(), HF.size());
3715 }
3716
3717 BlockDeclRefs.clear();
3718 BlockByRefDecls.clear();
3719 BlockByCopyDecls.clear();
3720 BlockCallExprs.clear();
3721 ImportedBlockDecls.clear();
3722 }
3723 Blocks.clear();
3724 RewrittenBlockExprs.clear();
3725}
3726
3727void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3728 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003729 const char *FuncName = FD->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003730
3731 SynthesizeBlockLiterals(FunLocStart, FuncName);
3732}
3733
3734void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003735 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3736 //SourceLocation FunLocStart = MD->getLocStart();
3737 // FIXME: This hack works around a bug in Rewrite.InsertText().
3738 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner3a8f2942008-11-24 03:33:13 +00003739 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003740 // Convert colons to underscores.
3741 std::string::size_type loc = 0;
3742 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3743 FuncName.replace(loc, 1, "_");
3744
3745 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3746}
3747
3748void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3749 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3750 CI != E; ++CI)
3751 if (*CI) {
3752 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3753 GetBlockDeclRefExprs(CBE->getBody());
3754 else
3755 GetBlockDeclRefExprs(*CI);
3756 }
3757 // Handle specific things.
3758 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3759 // FIXME: Handle enums.
3760 if (!isa<FunctionDecl>(CDRE->getDecl()))
3761 BlockDeclRefs.push_back(CDRE);
3762 return;
3763}
3764
3765void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3766 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3767 CI != E; ++CI)
3768 if (*CI) {
3769 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3770 GetBlockCallExprs(CBE->getBody());
3771 else
3772 GetBlockCallExprs(*CI);
3773 }
3774
3775 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3776 if (CE->getCallee()->getType()->isBlockPointerType()) {
3777 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3778 }
3779 }
3780 return;
3781}
3782
Steve Naroff85eb17b2008-10-30 10:07:53 +00003783Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003784 // Navigate to relevant type information.
3785 const char *closureName = 0;
3786 const BlockPointerType *CPT = 0;
3787
3788 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003789 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003790 CPT = DRE->getType()->getAsBlockPointerType();
3791 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003792 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003793 CPT = CDRE->getType()->getAsBlockPointerType();
3794 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003795 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003796 CPT = MExpr->getType()->getAsBlockPointerType();
3797 } else {
3798 assert(1 && "RewriteBlockClass: Bad type");
3799 }
3800 assert(CPT && "RewriteBlockClass: Bad type");
3801 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3802 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00003803 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003804 // FTP will be null for closures that don't take arguments.
3805
Steve Naroff85eb17b2008-10-30 10:07:53 +00003806 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3807 SourceLocation(),
3808 &Context->Idents.get("__block_impl"));
3809 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003810
Steve Naroff85eb17b2008-10-30 10:07:53 +00003811 // Generate a funky cast.
3812 llvm::SmallVector<QualType, 8> ArgTypes;
3813
3814 // Push the block argument type.
3815 ArgTypes.push_back(PtrBlock);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003816 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003817 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff85eb17b2008-10-30 10:07:53 +00003818 E = FTP->arg_type_end(); I && (I != E); ++I) {
3819 QualType t = *I;
3820 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00003821 if (isTopLevelBlockPointerType(t)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003822 const BlockPointerType *BPT = t->getAsBlockPointerType();
3823 t = Context->getPointerType(BPT->getPointeeType());
3824 }
3825 ArgTypes.push_back(t);
3826 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003827 }
Steve Naroff85eb17b2008-10-30 10:07:53 +00003828 // Now do the pointer to function cast.
3829 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3830 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3831
3832 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003833
Ted Kremenek0c97e042009-02-07 01:47:29 +00003834 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3835 PtrBlock, SourceLocation(),
3836 SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003837 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003838 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3839 BlkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003840 //PE->dump();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003841
Douglas Gregor8acb7272008-12-11 16:49:14 +00003842 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3843 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003844 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek0c97e042009-02-07 01:47:29 +00003845 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3846 FD->getType());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003847
Ted Kremenek0c97e042009-02-07 01:47:29 +00003848 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3849 PtrToFuncCastType,
3850 SourceLocation(),
3851 SourceLocation());
3852 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003853
3854 llvm::SmallVector<Expr*, 8> BlkExprs;
3855 // Add the implicit argument.
3856 BlkExprs.push_back(BlkCast);
3857 // Add the user arguments.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003858 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3859 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003860 BlkExprs.push_back(*I);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003861 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00003862 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3863 BlkExprs.size(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00003864 Exp->getType(), SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003865 return CE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003866}
3867
3868void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003869 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3870 ReplaceStmt(Exp, BlockCall);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003871}
3872
3873void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3874 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003875 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroff16478cf2009-02-02 17:19:26 +00003876 Context->getPointerType(BDRE->getType()),
3877 SourceLocation());
3878 // Need parens to enforce precedence.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003879 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroff16478cf2009-02-02 17:19:26 +00003880 ReplaceStmt(BDRE, PE);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003881}
3882
Steve Naroff7f1412d2008-11-03 23:29:32 +00003883void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3884 SourceLocation LocStart = CE->getLParenLoc();
3885 SourceLocation LocEnd = CE->getRParenLoc();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003886
3887 // Need to avoid trying to rewrite synthesized casts.
3888 if (LocStart.isInvalid())
3889 return;
Steve Naroff1c53c022008-11-03 11:20:24 +00003890 // Need to avoid trying to rewrite casts contained in macros.
3891 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3892 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003893
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003894 const char *startBuf = SM->getCharacterData(LocStart);
3895 const char *endBuf = SM->getCharacterData(LocEnd);
3896
3897 // advance the location to startArgList.
3898 const char *argPtr = startBuf;
3899
3900 while (*argPtr++ && (argPtr < endBuf)) {
3901 switch (*argPtr) {
3902 case '^':
3903 // Replace the '^' with '*'.
3904 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3905 ReplaceText(LocStart, 1, "*", 1);
3906 break;
3907 }
3908 }
3909 return;
3910}
3911
3912void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3913 SourceLocation DeclLoc = FD->getLocation();
3914 unsigned parenCount = 0;
3915
3916 // We have 1 or more arguments that have closure pointers.
3917 const char *startBuf = SM->getCharacterData(DeclLoc);
3918 const char *startArgList = strchr(startBuf, '(');
3919
3920 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3921
3922 parenCount++;
3923 // advance the location to startArgList.
3924 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3925 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3926
3927 const char *argPtr = startArgList;
3928
3929 while (*argPtr++ && parenCount) {
3930 switch (*argPtr) {
3931 case '^':
3932 // Replace the '^' with '*'.
3933 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3934 ReplaceText(DeclLoc, 1, "*", 1);
3935 break;
3936 case '(':
3937 parenCount++;
3938 break;
3939 case ')':
3940 parenCount--;
3941 break;
3942 }
3943 }
3944 return;
3945}
3946
3947bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003948 const FunctionProtoType *FTP;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003949 const PointerType *PT = QT->getAsPointerType();
3950 if (PT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003951 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003952 } else {
3953 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3954 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00003955 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003956 }
3957 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003958 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003959 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +00003960 if (isTopLevelBlockPointerType(*I))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003961 return true;
3962 }
3963 return false;
3964}
3965
Ted Kremenek0c97e042009-02-07 01:47:29 +00003966void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
3967 const char *&RParen) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003968 const char *argPtr = strchr(Name, '(');
3969 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3970
3971 LParen = argPtr; // output the start.
3972 argPtr++; // skip past the left paren.
3973 unsigned parenCount = 1;
3974
3975 while (*argPtr && parenCount) {
3976 switch (*argPtr) {
3977 case '(': parenCount++; break;
3978 case ')': parenCount--; break;
3979 default: break;
3980 }
3981 if (parenCount) argPtr++;
3982 }
3983 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3984 RParen = argPtr; // output the end
3985}
3986
3987void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3988 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3989 RewriteBlockPointerFunctionArgs(FD);
3990 return;
3991 }
3992 // Handle Variables and Typedefs.
3993 SourceLocation DeclLoc = ND->getLocation();
3994 QualType DeclT;
3995 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3996 DeclT = VD->getType();
3997 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3998 DeclT = TDD->getUnderlyingType();
3999 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4000 DeclT = FD->getType();
4001 else
4002 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4003
4004 const char *startBuf = SM->getCharacterData(DeclLoc);
4005 const char *endBuf = startBuf;
4006 // scan backward (from the decl location) for the end of the previous decl.
4007 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4008 startBuf--;
4009
4010 // *startBuf != '^' if we are dealing with a pointer to function that
4011 // may take block argument types (which will be handled below).
4012 if (*startBuf == '^') {
4013 // Replace the '^' with '*', computing a negative offset.
4014 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4015 ReplaceText(DeclLoc, 1, "*", 1);
4016 }
4017 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4018 // Replace the '^' with '*' for arguments.
4019 DeclLoc = ND->getLocation();
4020 startBuf = SM->getCharacterData(DeclLoc);
4021 const char *argListBegin, *argListEnd;
4022 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4023 while (argListBegin < argListEnd) {
4024 if (*argListBegin == '^') {
4025 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4026 ReplaceText(CaretLoc, 1, "*", 1);
4027 }
4028 argListBegin++;
4029 }
4030 }
4031 return;
4032}
4033
4034void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4035 // Add initializers for any closure decl refs.
4036 GetBlockDeclRefExprs(Exp->getBody());
4037 if (BlockDeclRefs.size()) {
4038 // Unique all "by copy" declarations.
4039 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4040 if (!BlockDeclRefs[i]->isByRef())
4041 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4042 // Unique all "by ref" declarations.
4043 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4044 if (BlockDeclRefs[i]->isByRef()) {
4045 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4046 }
4047 // Find any imported blocks...they will need special attention.
4048 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff1d56d9e2008-12-11 20:51:38 +00004049 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroffe59c8b12008-11-13 17:40:07 +00004050 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004051 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4052 }
4053 }
4054}
4055
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004056FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4057 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004058 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004059 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor1f88aa72009-02-25 16:33:18 +00004060 ID, FType, FunctionDecl::Extern, false,
4061 false);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004062}
4063
Steve Naroff80c54752008-10-29 18:15:37 +00004064Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004065 Blocks.push_back(Exp);
4066
4067 CollectBlockDeclRefInfo(Exp);
4068 std::string FuncName;
4069
4070 if (CurFunctionDef)
Chris Lattner3a8f2942008-11-24 03:33:13 +00004071 FuncName = CurFunctionDef->getNameAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004072 else if (CurMethodDef) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00004073 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004074 // Convert colons to underscores.
4075 std::string::size_type loc = 0;
4076 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4077 FuncName.replace(loc, 1, "_");
Steve Naroff80c54752008-10-29 18:15:37 +00004078 } else if (GlobalVarDecl)
Chris Lattner271d4c22008-11-24 05:29:24 +00004079 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004080
4081 std::string BlockNumber = utostr(Blocks.size()-1);
4082
4083 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4084 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4085
4086 // Get a pointer to the function type so we can cast appropriately.
4087 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4088
4089 FunctionDecl *FD;
4090 Expr *NewRep;
4091
4092 // Simulate a contructor call...
4093 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004094 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004095
4096 llvm::SmallVector<Expr*, 4> InitExprs;
4097
Steve Naroffd0419d62008-10-29 21:23:59 +00004098 // Initialize the block function.
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004099 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004100 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4101 SourceLocation());
4102 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4103 Context->VoidPtrTy, SourceLocation(),
4104 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004105 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004106
4107 if (ImportedBlockDecls.size()) {
4108 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004109 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004110 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4111 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4112 Context->VoidPtrTy, SourceLocation(),
4113 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004114 InitExprs.push_back(castExpr);
4115
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004116 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004117 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004118 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4119 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4120 Context->VoidPtrTy, SourceLocation(),
4121 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004122 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004123 }
4124 // Add initializers for any closure decl refs.
4125 if (BlockDeclRefs.size()) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004126 Expr *Exp;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004127 // Output all "by copy" declarations.
4128 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4129 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004130 if (isObjCType((*I)->getType())) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004131 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004132 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004133 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffd896f4b2008-12-11 21:05:33 +00004134 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004135 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004136 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4137 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4138 Context->VoidPtrTy, SourceLocation(),
4139 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004140 } else {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004141 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004142 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004143 }
Steve Naroffd0419d62008-10-29 21:23:59 +00004144 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004145 }
4146 // Output all "by ref" declarations.
4147 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4148 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004149 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004150 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4151 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Naroffd0419d62008-10-29 21:23:59 +00004152 Context->getPointerType(Exp->getType()),
4153 SourceLocation());
Steve Naroff362c7562008-11-14 21:36:12 +00004154 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004155 }
4156 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00004157 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4158 FType, SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004159 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004160 Context->getPointerType(NewRep->getType()),
4161 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004162 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4163 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004164 BlockDeclRefs.clear();
4165 BlockByRefDecls.clear();
4166 BlockByCopyDecls.clear();
4167 ImportedBlockDecls.clear();
4168 return NewRep;
4169}
4170
4171//===----------------------------------------------------------------------===//
4172// Function Body / Expression rewriting
4173//===----------------------------------------------------------------------===//
4174
Steve Naroff0e948412008-12-04 16:24:46 +00004175// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4176// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4177// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4178// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4179// Since the rewriter isn't capable of rewriting rewritten code, it's important
4180// we get this right.
4181void RewriteObjC::CollectPropertySetters(Stmt *S) {
4182 // Perform a bottom up traversal of all children.
4183 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4184 CI != E; ++CI)
4185 if (*CI)
4186 CollectPropertySetters(*CI);
4187
4188 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4189 if (BinOp->isAssignmentOp()) {
4190 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4191 PropSetters[PRE] = BinOp;
4192 }
4193 }
4194}
4195
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004196Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4197 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4198 isa<DoStmt>(S) || isa<ForStmt>(S))
4199 Stmts.push_back(S);
4200 else if (isa<ObjCForCollectionStmt>(S)) {
4201 Stmts.push_back(S);
4202 ObjCBcLabelNo.push_back(++BcLabelCount);
4203 }
4204
4205 SourceRange OrigStmtRange = S->getSourceRange();
4206
4207 // Perform a bottom up rewrite of all children.
4208 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4209 CI != E; ++CI)
4210 if (*CI) {
4211 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4212 if (newStmt)
4213 *CI = newStmt;
4214 }
4215
4216 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4217 // Rewrite the block body in place.
4218 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4219
4220 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff80c54752008-10-29 18:15:37 +00004221 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4222 RewrittenBlockExprs[BE] = Str;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004223
4224 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4225 //blockTranscribed->dump();
Steve Naroff80c54752008-10-29 18:15:37 +00004226 ReplaceStmt(S, blockTranscribed);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004227 return blockTranscribed;
4228 }
4229 // Handle specific things.
4230 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4231 return RewriteAtEncode(AtEncode);
4232
4233 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4234 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4235
Steve Naroff0e948412008-12-04 16:24:46 +00004236 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4237 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4238 if (BinOp) {
4239 // Because the rewriter doesn't allow us to rewrite rewritten code,
4240 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffedb4bc92008-12-09 12:56:34 +00004241 DisableReplaceStmt = true;
4242 // Save the source range. Even if we disable the replacement, the
4243 // rewritten node will have been inserted into the tree. If the synthesized
4244 // node is at the 'end', the rewriter will fail. Consider this:
4245 // self.errorHandler = handler ? handler :
4246 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4247 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff0e948412008-12-04 16:24:46 +00004248 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffedb4bc92008-12-09 12:56:34 +00004249 DisableReplaceStmt = false;
Steve Naroff102c3f22008-12-04 23:50:32 +00004250 //
4251 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4252 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4253 // to see the original expression). Consider this example:
4254 //
4255 // Foo *obj1, *obj2;
4256 //
4257 // obj1.i = [obj2 rrrr];
4258 //
4259 // 'BinOp' for the previous expression looks like:
4260 //
4261 // (BinaryOperator 0x231ccf0 'int' '='
4262 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4263 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4264 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4265 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4266 //
4267 // 'newStmt' represents the rewritten message expression. For example:
4268 //
4269 // (CallExpr 0x231d300 'id':'struct objc_object *'
4270 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4271 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4272 // (CStyleCastExpr 0x231d220 'void *'
4273 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4274 //
4275 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4276 // can be used as the setter argument. ReplaceStmt() will still 'see'
4277 // the original RHS (since we haven't altered BinOp).
4278 //
4279 // This implies the Rewrite* routines can no longer delete the original
4280 // node. As a result, we now leak the original AST nodes.
4281 //
Steve Naroffedb4bc92008-12-09 12:56:34 +00004282 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff0e948412008-12-04 16:24:46 +00004283 } else {
4284 return RewritePropertyGetter(PropRefExpr);
Steve Narofff6ce8a12008-12-03 00:56:33 +00004285 }
4286 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004287 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4288 return RewriteAtSelector(AtSelector);
4289
4290 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4291 return RewriteObjCStringLiteral(AtString);
4292
4293 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff0e948412008-12-04 16:24:46 +00004294#if 0
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004295 // Before we rewrite it, put the original message expression in a comment.
4296 SourceLocation startLoc = MessExpr->getLocStart();
4297 SourceLocation endLoc = MessExpr->getLocEnd();
4298
4299 const char *startBuf = SM->getCharacterData(startLoc);
4300 const char *endBuf = SM->getCharacterData(endLoc);
4301
4302 std::string messString;
4303 messString += "// ";
4304 messString.append(startBuf, endBuf-startBuf+1);
4305 messString += "\n";
4306
4307 // FIXME: Missing definition of
4308 // InsertText(clang::SourceLocation, char const*, unsigned int).
4309 // InsertText(startLoc, messString.c_str(), messString.size());
4310 // Tried this, but it didn't work either...
4311 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff0e948412008-12-04 16:24:46 +00004312#endif
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004313 return RewriteMessageExpr(MessExpr);
4314 }
4315
4316 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4317 return RewriteObjCTryStmt(StmtTry);
4318
4319 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4320 return RewriteObjCSynchronizedStmt(StmtTry);
4321
4322 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4323 return RewriteObjCThrowStmt(StmtThrow);
4324
4325 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4326 return RewriteObjCProtocolExpr(ProtocolExp);
4327
4328 if (ObjCForCollectionStmt *StmtForCollection =
4329 dyn_cast<ObjCForCollectionStmt>(S))
4330 return RewriteObjCForCollectionStmt(StmtForCollection,
4331 OrigStmtRange.getEnd());
4332 if (BreakStmt *StmtBreakStmt =
4333 dyn_cast<BreakStmt>(S))
4334 return RewriteBreakStmt(StmtBreakStmt);
4335 if (ContinueStmt *StmtContinueStmt =
4336 dyn_cast<ContinueStmt>(S))
4337 return RewriteContinueStmt(StmtContinueStmt);
4338
4339 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4340 // and cast exprs.
4341 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4342 // FIXME: What we're doing here is modifying the type-specifier that
4343 // precedes the first Decl. In the future the DeclGroup should have
4344 // a separate type-specifier that we can rewrite.
4345 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4346
4347 // Blocks rewrite rules.
4348 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4349 DI != DE; ++DI) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00004350 Decl *SD = *DI;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004351 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004352 if (isTopLevelBlockPointerType(ND->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004353 RewriteBlockPointerDecl(ND);
4354 else if (ND->getType()->isFunctionPointerType())
4355 CheckFunctionPointerDecl(ND->getType(), ND);
4356 }
4357 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004358 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004359 RewriteBlockPointerDecl(TD);
4360 else if (TD->getUnderlyingType()->isFunctionPointerType())
4361 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4362 }
4363 }
4364 }
4365
4366 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4367 RewriteObjCQualifiedInterfaceTypes(CE);
4368
4369 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4370 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4371 assert(!Stmts.empty() && "Statement stack is empty");
4372 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4373 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4374 && "Statement stack mismatch");
4375 Stmts.pop_back();
4376 }
4377 // Handle blocks rewriting.
4378 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4379 if (BDRE->isByRef())
4380 RewriteBlockDeclRefExpr(BDRE);
4381 }
4382 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00004383 if (CE->getCallee()->getType()->isBlockPointerType()) {
4384 Stmt *BlockCall = SynthesizeBlockCall(CE);
4385 ReplaceStmt(S, BlockCall);
4386 return BlockCall;
4387 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004388 }
Steve Naroff7f1412d2008-11-03 23:29:32 +00004389 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004390 RewriteCastExpr(CE);
4391 }
4392#if 0
4393 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004394 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004395 // Get the new text.
4396 std::string SStr;
4397 llvm::raw_string_ostream Buf(SStr);
4398 Replacement->printPretty(Buf);
4399 const std::string &Str = Buf.str();
4400
4401 printf("CAST = %s\n", &Str[0]);
4402 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4403 delete S;
4404 return Replacement;
4405 }
4406#endif
4407 // Return this stmt unmodified.
4408 return S;
4409}
4410
4411/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4412/// main file of the input.
4413void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4414 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffee8d4972008-12-17 00:20:22 +00004415 if (FD->isOverloadedOperator())
4416 return;
4417
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004418 // Since function prototypes don't have ParmDecl's, we check the function
4419 // prototype. This enables us to rewrite function declarations and
4420 // definitions using the same code.
Douglas Gregor4fa58902009-02-26 23:50:07 +00004421 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004422
Ted Kremenek30916072009-03-12 18:33:24 +00004423 if (CompoundStmt *Body = FD->getBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004424 CurFunctionDef = FD;
Steve Naroff0e948412008-12-04 16:24:46 +00004425 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004426 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004427 Body =
4428 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4429 FD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004430 CurrentBody = 0;
4431 if (PropParentMap) {
4432 delete PropParentMap;
4433 PropParentMap = 0;
4434 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004435 // This synthesizes and inserts the block "impl" struct, invoke function,
4436 // and any copy/dispose helper functions.
4437 InsertBlockLiteralsWithinFunction(FD);
4438 CurFunctionDef = 0;
4439 }
4440 return;
4441 }
4442 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Ted Kremenek30916072009-03-12 18:33:24 +00004443 if (CompoundStmt *Body = MD->getBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004444 CurMethodDef = MD;
Steve Naroff0e948412008-12-04 16:24:46 +00004445 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004446 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004447 Body =
4448 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4449 MD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004450 CurrentBody = 0;
4451 if (PropParentMap) {
4452 delete PropParentMap;
4453 PropParentMap = 0;
4454 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004455 InsertBlockLiteralsWithinMethod(MD);
4456 CurMethodDef = 0;
4457 }
4458 }
4459 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4460 ClassImplementation.push_back(CI);
4461 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4462 CategoryImplementation.push_back(CI);
4463 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4464 RewriteForwardClassDecl(CD);
4465 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4466 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffd896f4b2008-12-11 21:05:33 +00004467 if (isTopLevelBlockPointerType(VD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004468 RewriteBlockPointerDecl(VD);
Steve Naroff80c54752008-10-29 18:15:37 +00004469 else if (VD->getType()->isFunctionPointerType()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004470 CheckFunctionPointerDecl(VD->getType(), VD);
4471 if (VD->getInit()) {
Steve Naroff7f1412d2008-11-03 23:29:32 +00004472 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004473 RewriteCastExpr(CE);
4474 }
4475 }
4476 }
Steve Naroff80c54752008-10-29 18:15:37 +00004477 if (VD->getInit()) {
4478 GlobalVarDecl = VD;
Steve Naroff0e948412008-12-04 16:24:46 +00004479 CollectPropertySetters(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004480 CurrentBody = VD->getInit();
Steve Naroff80c54752008-10-29 18:15:37 +00004481 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004482 CurrentBody = 0;
4483 if (PropParentMap) {
4484 delete PropParentMap;
4485 PropParentMap = 0;
4486 }
Douglas Gregor24afd4a2008-11-17 14:58:09 +00004487 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004488 VD->getNameAsCString());
Steve Naroff80c54752008-10-29 18:15:37 +00004489 GlobalVarDecl = 0;
4490
4491 // This is needed for blocks.
Steve Naroff7f1412d2008-11-03 23:29:32 +00004492 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff80c54752008-10-29 18:15:37 +00004493 RewriteCastExpr(CE);
4494 }
4495 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004496 return;
4497 }
4498 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004499 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004500 RewriteBlockPointerDecl(TD);
4501 else if (TD->getUnderlyingType()->isFunctionPointerType())
4502 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4503 return;
4504 }
4505 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4506 if (RD->isDefinition()) {
Douglas Gregor640a04b2008-12-11 17:59:21 +00004507 for (RecordDecl::field_iterator i = RD->field_begin(),
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004508 e = RD->field_end(); i != e; ++i) {
4509 FieldDecl *FD = *i;
Steve Naroffd896f4b2008-12-11 21:05:33 +00004510 if (isTopLevelBlockPointerType(FD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004511 RewriteBlockPointerDecl(FD);
4512 }
4513 }
4514 return;
4515 }
4516 // Nothing yet.
4517}
4518
4519void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4520 // Get the top-level buffer that this corresponds to.
4521
4522 // Rewrite tabs if we care.
4523 //RewriteTabs();
4524
4525 if (Diags.hasErrorOccurred())
4526 return;
4527
4528 // Create the output file.
4529
4530 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4531 llvm::raw_ostream *OutFile;
4532 if (OutFileName == "-") {
4533 OutFile = &llvm::outs();
4534 } else if (!OutFileName.empty()) {
4535 std::string Err;
Steve Naroff08299f82009-02-03 20:39:18 +00004536 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(),
4537 // set binary mode (critical for Windoze)
4538 true,
4539 Err);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004540 OwnedStream.reset(OutFile);
4541 } else if (InFileName == "-") {
4542 OutFile = &llvm::outs();
4543 } else {
4544 llvm::sys::Path Path(InFileName);
4545 Path.eraseSuffix();
4546 Path.appendSuffix("cpp");
4547 std::string Err;
Steve Naroff08299f82009-02-03 20:39:18 +00004548 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(),
4549 // set binary mode (critical for Windoze)
4550 true,
4551 Err);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004552 OwnedStream.reset(OutFile);
4553 }
4554
4555 RewriteInclude();
4556
Chris Lattnerf4f776a2009-01-17 06:22:33 +00004557 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004558 Preamble.c_str(), Preamble.size(), false);
4559
Steve Naroff901d8fd2008-11-14 14:10:01 +00004560 if (ClassImplementation.size() || CategoryImplementation.size())
4561 RewriteImplementations();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004562
4563 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4564 // we are done.
4565 if (const RewriteBuffer *RewriteBuf =
4566 Rewrite.getRewriteBufferFor(MainFileID)) {
4567 //printf("Changed:\n");
4568 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4569 } else {
4570 fprintf(stderr, "No changes\n");
4571 }
Steve Naroff21658f62008-11-13 20:07:04 +00004572
Steve Naroff901d8fd2008-11-14 14:10:01 +00004573 if (ClassImplementation.size() || CategoryImplementation.size()) {
4574 // Rewrite Objective-c meta data*
4575 std::string ResultStr;
4576 SynthesizeMetaDataIntoBuffer(ResultStr);
4577 // Emit metadata.
4578 *OutFile << ResultStr;
4579 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004580 OutFile->flush();
4581}
4582