blob: 95b50b832e4b5e329cf207c525bfd86d8c46e792 [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"
Steve Narofffbed6802008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner569faa62007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff1c46cf12008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman6da15102008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattner673f2bd2008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000031using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000033
Steve Naroff1c46cf12008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattnerb429ae42007-10-11 00:43:27 +000038namespace {
Steve Naroff44e81222008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
Steve Naroff43964fb2008-12-05 17:03:39 +000044 unsigned TryFinallyContainsReturnDiag;
45
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000046 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000047 SourceManager *SM;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000048 TranslationUnitDecl *TUDecl;
Chris Lattnerf4f776a2009-01-17 06:22:33 +000049 FileID MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000050 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000051 SourceLocation LastIncLoc;
Steve Narofffef037c2008-03-27 22:29:16 +000052
Ted Kremenek42730c52008-01-07 19:49:32 +000053 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
54 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
55 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff04eaa192008-05-06 18:26:51 +000056 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek42730c52008-01-07 19:49:32 +000057 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
58 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000059 llvm::SmallVector<Stmt *, 32> Stmts;
60 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffe9780582007-10-23 23:50:29 +000061
Steve Naroff47e7fa22008-03-15 00:55:56 +000062 unsigned NumObjCStringLiterals;
63
Steve Naroffe9780582007-10-23 23:50:29 +000064 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000065 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000066 FunctionDecl *MsgSendStretFunctionDecl;
67 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000068 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000069 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000070 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000071 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000072 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000073 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000074 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000075
Steve Naroff0add5d22007-11-03 11:27:19 +000076 // ObjC string constant support.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000077 VarDecl *ConstantStringClassReference;
Steve Naroff0add5d22007-11-03 11:27:19 +000078 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000079
Fariborz Jahanian22277422008-01-16 00:09:11 +000080 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000081 int BcLabelCount;
82
Steve Naroff764c1ae2007-11-15 10:28:18 +000083 // Needed for super.
Steve Naroff38a9e3f2008-10-27 17:20:55 +000084 ObjCMethodDecl *CurMethodDef;
Steve Naroff764c1ae2007-11-15 10:28:18 +000085 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000086 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000087
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000088 // Needed for header files being rewritten
89 bool IsHeader;
90
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000091 std::string InFileName;
92 std::string OutFileName;
93
Steve Narofffef037c2008-03-27 22:29:16 +000094 std::string Preamble;
Steve Naroff38a9e3f2008-10-27 17:20:55 +000095
96 // Block expressions.
97 llvm::SmallVector<BlockExpr *, 32> Blocks;
98 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
99 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Narofffef037c2008-03-27 22:29:16 +0000100
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000101 // Block related declarations.
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
104 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
105
106 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
107
Steve Naroff0e948412008-12-04 16:24:46 +0000108 // This maps a property to it's assignment statement.
109 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Narofffbed6802008-12-08 16:43:47 +0000110 // This maps a property to it's synthesied message expression.
111 // This allows us to rewrite chained getters (e.g. o.a.b.c).
112 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
113
Steve Naroff102c3f22008-12-04 23:50:32 +0000114 // This maps an original source AST to it's rewritten form. This allows
115 // us to avoid rewriting the same node twice (which is very uncommon).
116 // This is needed to support some of the exotic property rewriting.
117 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff6ce8a12008-12-03 00:56:33 +0000118
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000119 FunctionDecl *CurFunctionDef;
Steve Naroff80c54752008-10-29 18:15:37 +0000120 VarDecl *GlobalVarDecl;
121
Steve Naroffedb4bc92008-12-09 12:56:34 +0000122 bool DisableReplaceStmt;
123
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000124 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +0000125 public:
Ted Kremenek79b50cb2008-05-31 20:11:04 +0000126 virtual void Initialize(ASTContext &context);
127
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000128 // Top Level Driver code.
Chris Lattnera17991f2009-03-29 16:50:03 +0000129 virtual void HandleTopLevelDecl(DeclGroupRef D) {
130 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
131 HandleTopLevelSingleDecl(*I);
132 }
133 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000134 void HandleDeclInMainFile(Decl *D);
Steve Naroff44e81222008-04-14 22:03:09 +0000135 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000136 Diagnostic &D, const LangOptions &LOpts);
Ted Kremenekcab0b0c2008-08-08 04:15:52 +0000137
138 ~RewriteObjC() {}
139
Chris Lattner2a594d02009-03-28 04:11:33 +0000140 virtual void HandleTranslationUnit(ASTContext &C);
Chris Lattnerb1548372008-01-31 19:37:57 +0000141
142 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff102c3f22008-12-04 23:50:32 +0000143 Stmt *ReplacingStmt = ReplacedNodes[Old];
144
145 if (ReplacingStmt)
146 return; // We can't rewrite the same node twice.
Chris Lattnerb1548372008-01-31 19:37:57 +0000147
Steve Naroffedb4bc92008-12-09 12:56:34 +0000148 if (DisableReplaceStmt)
149 return; // Used when rewriting the assignment of a property setter.
150
Steve Naroff102c3f22008-12-04 23:50:32 +0000151 // If replacement succeeded or warning disabled return with no warning.
152 if (!Rewrite.ReplaceStmt(Old, New)) {
153 ReplacedNodes[Old] = New;
154 return;
155 }
156 if (SilenceRewriteMacroWarning)
157 return;
Chris Lattner6948ae62008-11-18 07:04:44 +0000158 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
159 << Old->getSourceRange();
Chris Lattnerb1548372008-01-31 19:37:57 +0000160 }
Steve Naroffedb4bc92008-12-09 12:56:34 +0000161
162 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
163 // Measaure the old text.
164 int Size = Rewrite.getRangeSize(SrcRange);
165 if (Size == -1) {
166 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
167 << Old->getSourceRange();
168 return;
169 }
170 // Get the new text.
171 std::string SStr;
172 llvm::raw_string_ostream S(SStr);
173 New->printPretty(S);
174 const std::string &Str = S.str();
175
176 // If replacement succeeded or warning disabled return with no warning.
177 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
178 ReplacedNodes[Old] = New;
179 return;
180 }
181 if (SilenceRewriteMacroWarning)
182 return;
183 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
184 << Old->getSourceRange();
185 }
186
Steve Narofffef037c2008-03-27 22:29:16 +0000187 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
188 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000189 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000190 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000191 SilenceRewriteMacroWarning)
192 return;
193
194 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
195 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000196
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000197 void RemoveText(SourceLocation Loc, unsigned StrLen) {
198 // If removal succeeded or warning disabled return with no warning.
199 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
200 return;
201
202 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
203 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000204
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000205 void ReplaceText(SourceLocation Start, unsigned OrigLength,
206 const char *NewStr, unsigned NewLength) {
207 // If removal succeeded or warning disabled return with no warning.
208 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
209 SilenceRewriteMacroWarning)
210 return;
211
212 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
213 }
214
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000215 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000216 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000217 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000218 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000219 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffea6610f2008-12-02 17:36:43 +0000220 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
221 ObjCImplementationDecl *IMD,
222 ObjCCategoryImplDecl *CID);
Ted Kremenek42730c52008-01-07 19:49:32 +0000223 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000224 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000225 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
226 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
227 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
228 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
229 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff56af2002009-01-11 01:06:09 +0000230 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000231 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000232 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000233 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000234 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000235 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000236 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000237 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000238 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000239
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000240 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000241 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff0e948412008-12-04 16:24:46 +0000242 void CollectPropertySetters(Stmt *S);
243
Steve Narofffbed6802008-12-08 16:43:47 +0000244 Stmt *CurrentBody;
245 ParentMap *PropParentMap; // created lazily.
246
Chris Lattner0021f452007-10-24 16:57:36 +0000247 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000248 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff0e948412008-12-04 16:24:46 +0000249 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffedb4bc92008-12-09 12:56:34 +0000250 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
251 SourceRange SrcRange);
Steve Naroff296b74f2007-11-05 14:50:49 +0000252 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000253 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000254 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000255 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff43964fb2008-12-05 17:03:39 +0000256 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000257 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000258 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000259 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
260 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
261 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000262 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
263 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000264 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
265 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000266 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000267 Stmt *RewriteBreakStmt(BreakStmt *S);
268 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000269 void SynthCountByEnumWithState(std::string &buf);
270
Steve Naroff02a82aa2007-10-30 23:14:51 +0000271 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000272 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000273 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000274 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000275 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000276 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000277 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000278 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000279 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000280 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000281
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000282 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000283 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
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 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000287 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000288
Douglas Gregorcd19b572009-04-23 01:02:12 +0000289 template<typename MethodIterator>
290 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
291 MethodIterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000292 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000293 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000294 const char *ClassName,
295 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000296
Chris Lattner0be08822008-07-21 21:32:27 +0000297 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
298 &Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000299 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000300 const char *ClassName,
301 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000302 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000303 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000304 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
305 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000306 std::string &Result);
Steve Naroff21658f62008-11-13 20:07:04 +0000307 void RewriteImplementations();
308 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000309
310 // Block rewriting.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000311 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000312 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
313
314 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
315 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
316
Steve Naroff80c54752008-10-29 18:15:37 +0000317 // Block specific rewrite rules.
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000318 void RewriteBlockCall(CallExpr *Exp);
319 void RewriteBlockPointerDecl(NamedDecl *VD);
320 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
321 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
322
323 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
324 const char *funcName, std::string Tag);
325 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
326 const char *funcName, std::string Tag);
327 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
328 bool hasCopyDisposeHelpers);
Steve Naroff85eb17b2008-10-30 10:07:53 +0000329 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000330 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
331 const char *FunName);
332
333 void CollectBlockDeclRefInfo(BlockExpr *Exp);
334 void GetBlockCallExprs(Stmt *S);
335 void GetBlockDeclRefExprs(Stmt *S);
336
337 // We avoid calling Type::isBlockPointerType(), since it operates on the
338 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000339 bool isTopLevelBlockPointerType(QualType T) {
340 return isa<BlockPointerType>(T);
341 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000342
343 // FIXME: This predicate seems like it would be useful to add to ASTContext.
344 bool isObjCType(QualType T) {
345 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
346 return false;
347
348 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
349
350 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
351 OCT == Context->getCanonicalType(Context->getObjCClassType()))
352 return true;
353
354 if (const PointerType *PT = OCT->getAsPointerType()) {
355 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
356 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
357 return true;
358 }
359 return false;
360 }
361 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek0c97e042009-02-07 01:47:29 +0000362 void GetExtentOfArgList(const char *Name, const char *&LParen,
363 const char *&RParen);
Steve Naroff7f1412d2008-11-03 23:29:32 +0000364 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +0000365
366 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff80c54752008-10-29 18:15:37 +0000367 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000368 };
369}
370
Douglas Gregor4fa58902009-02-26 23:50:07 +0000371void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000372 NamedDecl *D) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000373 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
374 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000375 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +0000376 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000377 // All the args are checked/rewritten. Don't call twice!
378 RewriteBlockPointerDecl(D);
379 break;
380 }
381 }
382}
383
384void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
385 const PointerType *PT = funcType->getAsPointerType();
386 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor4fa58902009-02-26 23:50:07 +0000387 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000388}
389
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000390static bool IsHeaderFile(const std::string &Filename) {
391 std::string::size_type DotPos = Filename.rfind('.');
392
393 if (DotPos == std::string::npos) {
394 // no file extension
395 return false;
396 }
397
398 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
399 // C header: .h
400 // C++ header: .hh or .H;
401 return Ext == "h" || Ext == "hh" || Ext == "H";
402}
403
Steve Naroff44e81222008-04-14 22:03:09 +0000404RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000405 Diagnostic &D, const LangOptions &LOpts)
406 : Diags(D), LangOpts(LOpts) {
407 IsHeader = IsHeaderFile(inFile);
408 InFileName = inFile;
409 OutFileName = outFile;
410 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
411 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff43964fb2008-12-05 17:03:39 +0000412 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000413 "rewriter doesn't support user-specified control flow semantics "
414 "for @try/@finally (code may not execute properly)");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000415}
416
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000417ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000418 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000419 Diagnostic &Diags,
420 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000421 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000422}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000423
Steve Naroff44e81222008-04-14 22:03:09 +0000424void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000425 Context = &context;
426 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000427 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000428 MsgSendFunctionDecl = 0;
429 MsgSendSuperFunctionDecl = 0;
430 MsgSendStretFunctionDecl = 0;
431 MsgSendSuperStretFunctionDecl = 0;
432 MsgSendFpretFunctionDecl = 0;
433 GetClassFunctionDecl = 0;
434 GetMetaClassFunctionDecl = 0;
435 SelGetUidFunctionDecl = 0;
436 CFStringFunctionDecl = 0;
437 GetProtocolFunctionDecl = 0;
438 ConstantStringClassReference = 0;
439 NSStringRecord = 0;
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000440 CurMethodDef = 0;
441 CurFunctionDef = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000442 GlobalVarDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000443 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000444 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000445 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000446 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000447 NumObjCStringLiterals = 0;
Steve Naroffbad6f3b2008-12-08 20:01:41 +0000448 PropParentMap = 0;
449 CurrentBody = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000450 DisableReplaceStmt = false;
451
Chris Lattner12499682008-01-31 19:38:44 +0000452 // Get the ID and start/end of the main file.
453 MainFileID = SM->getMainFileID();
454 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
455 MainFileStart = MainBuf->getBufferStart();
456 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000457
Chris Lattnere1be6022009-04-14 23:22:57 +0000458 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Steve Naroffde0da102008-03-10 23:16:54 +0000459
Chris Lattner12499682008-01-31 19:38:44 +0000460 // declaring objc_selector outside the parameter list removes a silly
461 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000462 if (IsHeader)
Steve Naroff08299f82009-02-03 20:39:18 +0000463 Preamble = "#pragma once\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000464 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff12673622008-12-23 20:11:22 +0000465 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Narofffef037c2008-03-27 22:29:16 +0000466 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000467 if (LangOpts.Microsoft) {
468 // Add a constructor for creating temporary objects.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000469 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
470 ": ";
Steve Narofffef037c2008-03-27 22:29:16 +0000471 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000472 }
Steve Narofffef037c2008-03-27 22:29:16 +0000473 Preamble += "};\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000474 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
475 Preamble += "typedef struct objc_object Protocol;\n";
476 Preamble += "#define _REWRITER_typedef_Protocol\n";
477 Preamble += "#endif\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000478 if (LangOpts.Microsoft) {
479 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
480 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
481 } else
482 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
483 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000484 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000485 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000486 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000487 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000488 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000489 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000490 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000491 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000492 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000493 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000494 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000495 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000496 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000497 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
498 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
499 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
500 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
501 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000502 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000503 // @synchronized hooks.
Steve Naroff1b208d72008-12-08 17:30:33 +0000504 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
505 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
506 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000507 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
508 Preamble += "struct __objcFastEnumerationState {\n\t";
509 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000510 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000511 Preamble += "unsigned long *mutationsPtr;\n\t";
512 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000513 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000514 Preamble += "#define __FASTENUMERATIONSTATE\n";
515 Preamble += "#endif\n";
516 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
517 Preamble += "struct __NSConstantStringImpl {\n";
518 Preamble += " int *isa;\n";
519 Preamble += " int flags;\n";
520 Preamble += " char *str;\n";
521 Preamble += " long length;\n";
522 Preamble += "};\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000523 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
524 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
525 Preamble += "#else\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000526 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000527 Preamble += "#endif\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000528 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
529 Preamble += "#endif\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000530 // Blocks preamble.
531 Preamble += "#ifndef BLOCK_IMPL\n";
532 Preamble += "#define BLOCK_IMPL\n";
533 Preamble += "struct __block_impl {\n";
534 Preamble += " void *isa;\n";
535 Preamble += " int Flags;\n";
536 Preamble += " int Size;\n";
537 Preamble += " void *FuncPtr;\n";
538 Preamble += "};\n";
Steve Naroff44fe1e32008-12-16 15:50:30 +0000539 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
540 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
541 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
542 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
543 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000544 Preamble += "#endif\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000545 if (LangOpts.Microsoft) {
Steve Naroff1b208d72008-12-08 17:30:33 +0000546 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
547 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000548 Preamble += "#define __attribute__(X)\n";
549 }
Chris Lattner12499682008-01-31 19:38:44 +0000550}
551
552
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000553//===----------------------------------------------------------------------===//
554// Top Level Driver Code
555//===----------------------------------------------------------------------===//
556
Chris Lattnera17991f2009-03-29 16:50:03 +0000557void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000558 // Two cases: either the decl could be in the main file, or it could be in a
559 // #included file. If the former, rewrite it now. If the later, check to see
560 // if we rewrote the #include/#import.
561 SourceLocation Loc = D->getLocation();
Chris Lattner18c8dc02009-01-16 07:36:28 +0000562 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000563
564 // If this is for a builtin, ignore it.
565 if (Loc.isInvalid()) return;
566
Steve Naroffe9780582007-10-23 23:50:29 +0000567 // Look for built-in declarations that we need to refer during the rewrite.
568 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000569 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000570 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000571 // declared in <Foundation/NSString.h>
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000572 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000573 ConstantStringClassReference = FVD;
574 return;
575 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000576 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000577 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000578 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000579 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000580 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000581 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000582 } else if (ObjCForwardProtocolDecl *FP =
583 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000584 RewriteForwardProtocolDecl(FP);
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000585 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
586 // Recurse into linkage specifications
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000587 for (DeclContext::decl_iterator DI = LSD->decls_begin(*Context),
588 DIEnd = LSD->decls_end(*Context);
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000589 DI != DIEnd; ++DI)
Chris Lattnera17991f2009-03-29 16:50:03 +0000590 HandleTopLevelSingleDecl(*DI);
Steve Naroffe9780582007-10-23 23:50:29 +0000591 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000592 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000593 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000594 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000595}
596
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000597//===----------------------------------------------------------------------===//
598// Syntactic (non-AST) Rewriting Code
599//===----------------------------------------------------------------------===//
600
Steve Naroff44e81222008-04-14 22:03:09 +0000601void RewriteObjC::RewriteInclude() {
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000602 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000603 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
604 const char *MainBufStart = MainBuf.first;
605 const char *MainBufEnd = MainBuf.second;
606 size_t ImportLen = strlen("import");
607 size_t IncludeLen = strlen("include");
608
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000609 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000610 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
611 if (*BufPtr == '#') {
612 if (++BufPtr == MainBufEnd)
613 return;
614 while (*BufPtr == ' ' || *BufPtr == '\t')
615 if (++BufPtr == MainBufEnd)
616 return;
617 if (!strncmp(BufPtr, "import", ImportLen)) {
618 // replace import with include
619 SourceLocation ImportLoc =
620 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000621 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000622 BufPtr += ImportLen;
623 }
624 }
625 }
Chris Lattner74db1682007-10-16 21:07:07 +0000626}
627
Steve Naroff44e81222008-04-14 22:03:09 +0000628void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000629 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
630 const char *MainBufStart = MainBuf.first;
631 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000632
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000633 // Loop over the whole file, looking for tabs.
634 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
635 if (*BufPtr != '\t')
636 continue;
637
638 // Okay, we found a tab. This tab will turn into at least one character,
639 // but it depends on which 'virtual column' it is in. Compute that now.
640 unsigned VCol = 0;
641 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
642 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
643 ++VCol;
644
645 // Okay, now that we know the virtual column, we know how many spaces to
646 // insert. We assume 8-character tab-stops.
647 unsigned Spaces = 8-(VCol & 7);
648
649 // Get the location of the tab.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000650 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
651 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000652
653 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000654 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000655 }
Chris Lattner569faa62007-10-11 18:38:32 +0000656}
657
Steve Naroff121ed222008-12-02 15:48:25 +0000658static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
659 ObjCIvarDecl *OID) {
660 std::string S;
661 S = "((struct ";
662 S += ClassDecl->getIdentifier()->getName();
663 S += "_IMPL *)self)->";
664 S += OID->getNameAsCString();
665 return S;
666}
667
Steve Naroffea6610f2008-12-02 17:36:43 +0000668void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
669 ObjCImplementationDecl *IMD,
670 ObjCCategoryImplDecl *CID) {
Steve Naroff110be842008-12-01 20:33:01 +0000671 SourceLocation startLoc = PID->getLocStart();
672 InsertText(startLoc, "// ", 3);
Steve Naroff121ed222008-12-02 15:48:25 +0000673 const char *startBuf = SM->getCharacterData(startLoc);
674 assert((*startBuf == '@') && "bogus @synthesize location");
675 const char *semiBuf = strchr(startBuf, ';');
676 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek0c97e042009-02-07 01:47:29 +0000677 SourceLocation onePastSemiLoc =
678 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff121ed222008-12-02 15:48:25 +0000679
680 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
681 return; // FIXME: is this correct?
682
683 // Generate the 'getter' function.
Steve Naroff121ed222008-12-02 15:48:25 +0000684 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff121ed222008-12-02 15:48:25 +0000685 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff121ed222008-12-02 15:48:25 +0000686 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000687
688 if (!OID)
689 return;
690
691 std::string Getr;
692 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
693 Getr += "{ ";
694 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000695 // FIXME: deal with code generation implications for various property
696 // attributes (copy, retain, nonatomic).
697 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000698 Getr += "return " + getIvarAccessString(ClassDecl, OID);
699 Getr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000700 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffea6610f2008-12-02 17:36:43 +0000701
Steve Naroff121ed222008-12-02 15:48:25 +0000702 if (PD->isReadOnly())
703 return;
704
705 // Generate the 'setter' function.
706 std::string Setr;
707 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff121ed222008-12-02 15:48:25 +0000708 Setr += "{ ";
Steve Naroff1e7b7962008-12-02 16:05:55 +0000709 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000710 // FIXME: deal with code generation implications for various property
711 // attributes (copy, retain, nonatomic).
Steve Narofff6ce8a12008-12-03 00:56:33 +0000712 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000713 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff20f67392008-12-11 19:29:16 +0000714 Setr += PD->getNameAsCString();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000715 Setr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000716 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroff110be842008-12-01 20:33:01 +0000717}
Chris Lattner569faa62007-10-11 18:38:32 +0000718
Steve Naroff44e81222008-04-14 22:03:09 +0000719void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000720 // Get the start location and compute the semi location.
721 SourceLocation startLoc = ClassDecl->getLocation();
722 const char *startBuf = SM->getCharacterData(startLoc);
723 const char *semiPtr = strchr(startBuf, ';');
724
725 // Translate to typedef's that forward reference structs with the same name
726 // as the class. As a convenience, we include the original declaration
727 // as a comment.
728 std::string typedefString;
729 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000730 typedefString.append(startBuf, semiPtr-startBuf+1);
731 typedefString += "\n";
Chris Lattner6a028742009-02-20 18:04:31 +0000732 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
733 I != E; ++I) {
734 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff2aeae312007-11-09 12:50:28 +0000735 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000736 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000737 typedefString += "\n";
738 typedefString += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000739 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000740 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000741 typedefString += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000742 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000743 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000744 }
745
746 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000747 ReplaceText(startLoc, semiPtr-startBuf+1,
748 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000749}
750
Steve Naroff44e81222008-04-14 22:03:09 +0000751void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000752 SourceLocation LocStart = Method->getLocStart();
753 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000754
Chris Lattner2d89c562009-02-04 01:06:56 +0000755 if (SM->getInstantiationLineNumber(LocEnd) >
756 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff99f50fe2008-10-21 13:37:27 +0000757 InsertText(LocStart, "#if 0\n", 6);
758 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000759 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000760 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000761 }
762}
763
Steve Naroff56af2002009-01-11 01:06:09 +0000764void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000765{
Steve Naroff56af2002009-01-11 01:06:09 +0000766 SourceLocation Loc = prop->getLocation();
767
768 ReplaceText(Loc, 0, "// ", 3);
769
770 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000771}
772
Steve Naroff44e81222008-04-14 22:03:09 +0000773void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000774 SourceLocation LocStart = CatDecl->getLocStart();
775
776 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000777 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000778
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000779 for (ObjCCategoryDecl::instmeth_iterator
780 I = CatDecl->instmeth_begin(*Context),
781 E = CatDecl->instmeth_end(*Context);
782 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000783 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000784 for (ObjCCategoryDecl::classmeth_iterator
785 I = CatDecl->classmeth_begin(*Context),
786 E = CatDecl->classmeth_end(*Context);
787 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000788 RewriteMethodDeclaration(*I);
789
Steve Naroff667f1682007-10-30 13:30:57 +0000790 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000791 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000792}
793
Steve Naroff44e81222008-04-14 22:03:09 +0000794void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000795 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000796
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000797 SourceLocation LocStart = PDecl->getLocStart();
798
799 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000800 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000801
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000802 for (ObjCProtocolDecl::instmeth_iterator
803 I = PDecl->instmeth_begin(*Context),
804 E = PDecl->instmeth_end(*Context);
805 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000806 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000807 for (ObjCProtocolDecl::classmeth_iterator
808 I = PDecl->classmeth_begin(*Context),
809 E = PDecl->classmeth_end(*Context);
810 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000811 RewriteMethodDeclaration(*I);
812
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000813 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000814 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000815 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000816
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000817 // Must comment out @optional/@required
818 const char *startBuf = SM->getCharacterData(LocStart);
819 const char *endBuf = SM->getCharacterData(LocEnd);
820 for (const char *p = startBuf; p < endBuf; p++) {
821 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
822 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000823 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000824 ReplaceText(OptionalLoc, strlen("@optional"),
825 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000826
827 }
828 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
829 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000830 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000831 ReplaceText(OptionalLoc, strlen("@required"),
832 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000833
834 }
835 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000836}
837
Steve Naroff44e81222008-04-14 22:03:09 +0000838void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000839 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000840 if (LocStart.isInvalid())
841 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000842 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000843 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000844}
845
Steve Naroff44e81222008-04-14 22:03:09 +0000846void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000847 std::string &ResultStr) {
Steve Naroff6449c6c2008-10-30 12:09:33 +0000848 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff91044cf2008-07-16 14:40:40 +0000849 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000850 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000851 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000852 ResultStr += "id";
Steve Naroff20f67392008-12-11 19:29:16 +0000853 else if (OMD->getResultType()->isFunctionPointerType() ||
854 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000855 // needs special handling, since pointer-to-functions have special
856 // syntax (where a decaration models use).
857 QualType retType = OMD->getResultType();
Steve Naroff20f67392008-12-11 19:29:16 +0000858 QualType PointeeTy;
859 if (const PointerType* PT = retType->getAsPointerType())
860 PointeeTy = PT->getPointeeType();
861 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
862 PointeeTy = BPT->getPointeeType();
863 if ((FPRetType = PointeeTy->getAsFunctionType())) {
864 ResultStr += FPRetType->getResultType().getAsString();
865 ResultStr += "(*";
Steve Naroff91044cf2008-07-16 14:40:40 +0000866 }
867 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000868 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000869 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000870
871 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000872 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000873
Douglas Gregor5d764842009-01-09 17:18:27 +0000874 if (OMD->isInstanceMethod())
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000875 NameStr += "_I_";
876 else
877 NameStr += "_C_";
878
Chris Lattner271d4c22008-11-24 05:29:24 +0000879 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000880 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000881
Ted Kremenek42730c52008-01-07 19:49:32 +0000882 if (ObjCCategoryImplDecl *CID =
Steve Naroff438be772009-01-08 19:41:02 +0000883 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000884 NameStr += CID->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000885 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000886 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000887 // Append selector names, replacing ':' with '_'
Chris Lattner3a8f2942008-11-24 03:33:13 +0000888 {
889 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000890 int len = selString.size();
891 for (int i = 0; i < len; i++)
892 if (selString[i] == ':')
893 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000894 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000895 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000896 // Remember this name for metadata emission
897 MethodInternalNames[OMD] = NameStr;
898 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000899
900 // Rewrite arguments
901 ResultStr += "(";
902
903 // invisible arguments
Douglas Gregor5d764842009-01-09 17:18:27 +0000904 if (OMD->isInstanceMethod()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000905 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000906 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000907 if (!LangOpts.Microsoft) {
908 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
909 ResultStr += "struct ";
910 }
911 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattner271d4c22008-11-24 05:29:24 +0000912 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +0000913 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000914 }
915 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000916 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000917
918 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000919 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000920 ResultStr += " _cmd";
921
922 // Method arguments.
Chris Lattner5c6b2c62009-02-20 18:43:26 +0000923 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
924 E = OMD->param_end(); PI != E; ++PI) {
925 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000926 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000927 if (PDecl->getType()->isObjCQualifiedIdType()) {
928 ResultStr += "id ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000929 ResultStr += PDecl->getNameAsString();
Steve Naroff133dfda2008-04-18 21:13:19 +0000930 } else {
Chris Lattner271d4c22008-11-24 05:29:24 +0000931 std::string Name = PDecl->getNameAsString();
Steve Naroffd896f4b2008-12-11 21:05:33 +0000932 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff4e2ae512008-10-30 14:45:29 +0000933 // Make sure we convert "t (^)(...)" to "t (*)(...)".
934 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
935 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
936 } else
937 PDecl->getType().getAsStringInternal(Name);
Steve Naroff133dfda2008-04-18 21:13:19 +0000938 ResultStr += Name;
939 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000940 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000941 if (OMD->isVariadic())
942 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000943 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000944
Steve Naroff91044cf2008-07-16 14:40:40 +0000945 if (FPRetType) {
946 ResultStr += ")"; // close the precedence "scope" for "*".
947
948 // Now, emit the argument types (if any).
Douglas Gregor4fa58902009-02-26 23:50:07 +0000949 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000950 ResultStr += "(";
951 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
952 if (i) ResultStr += ", ";
953 std::string ParamStr = FT->getArgType(i).getAsString();
954 ResultStr += ParamStr;
955 }
956 if (FT->isVariadic()) {
957 if (FT->getNumArgs()) ResultStr += ", ";
958 ResultStr += "...";
959 }
960 ResultStr += ")";
961 } else {
962 ResultStr += "()";
963 }
964 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000965}
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000966void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000967 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
968 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000969
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000970 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000971 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000972 else
Chris Lattner6216f292008-01-31 19:42:41 +0000973 InsertText(CID->getLocStart(), "// ", 3);
Steve Naroff21658f62008-11-13 20:07:04 +0000974
Ted Kremenek42730c52008-01-07 19:49:32 +0000975 for (ObjCCategoryImplDecl::instmeth_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +0000976 I = IMD ? IMD->instmeth_begin(*Context) : CID->instmeth_begin(*Context),
977 E = IMD ? IMD->instmeth_end(*Context) : CID->instmeth_end(*Context);
978 I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000979 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000980 ObjCMethodDecl *OMD = *I;
981 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000982 SourceLocation LocStart = OMD->getLocStart();
Sebastian Redlbc9ef252009-04-26 20:35:05 +0000983 SourceLocation LocEnd = OMD->getCompoundBody(*Context)->getLocStart();
984
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000985 const char *startBuf = SM->getCharacterData(LocStart);
986 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000987 ReplaceText(LocStart, endBuf-startBuf,
988 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000989 }
990
Ted Kremenek42730c52008-01-07 19:49:32 +0000991 for (ObjCCategoryImplDecl::classmeth_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +0000992 I = IMD ? IMD->classmeth_begin(*Context) : CID->classmeth_begin(*Context),
993 E = IMD ? IMD->classmeth_end(*Context) : CID->classmeth_end(*Context);
994 I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000995 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000996 ObjCMethodDecl *OMD = *I;
997 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000998 SourceLocation LocStart = OMD->getLocStart();
Sebastian Redlbc9ef252009-04-26 20:35:05 +0000999 SourceLocation LocEnd = OMD->getCompoundBody(*Context)->getLocStart();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001000
1001 const char *startBuf = SM->getCharacterData(LocStart);
1002 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001003 ReplaceText(LocStart, endBuf-startBuf,
1004 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001005 }
Steve Naroff110be842008-12-01 20:33:01 +00001006 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +00001007 I = IMD ? IMD->propimpl_begin(*Context) : CID->propimpl_begin(*Context),
1008 E = IMD ? IMD->propimpl_end(*Context) : CID->propimpl_end(*Context);
1009 I != E; ++I) {
Steve Naroffea6610f2008-12-02 17:36:43 +00001010 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroff110be842008-12-01 20:33:01 +00001011 }
1012
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001013 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +00001014 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001015 else
Chris Lattner6216f292008-01-31 19:42:41 +00001016 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001017}
1018
Steve Naroff44e81222008-04-14 22:03:09 +00001019void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +00001020 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +00001021 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +00001022 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +00001023 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001024 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001025 ResultStr += "\n";
1026 ResultStr += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001027 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001028 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +00001029 ResultStr += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +00001030 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001031 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +00001032 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00001033 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +00001034 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001035 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +00001036
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001037 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(*Context),
1038 E = ClassDecl->prop_end(*Context); I != E; ++I)
Steve Naroff56af2002009-01-11 01:06:09 +00001039 RewriteProperty(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001040 for (ObjCInterfaceDecl::instmeth_iterator
1041 I = ClassDecl->instmeth_begin(*Context),
1042 E = ClassDecl->instmeth_end(*Context);
1043 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +00001044 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001045 for (ObjCInterfaceDecl::classmeth_iterator
1046 I = ClassDecl->classmeth_begin(*Context),
1047 E = ClassDecl->classmeth_end(*Context);
1048 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +00001049 RewriteMethodDeclaration(*I);
1050
Steve Naroff1ccf4632007-10-30 03:43:13 +00001051 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001052 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +00001053}
1054
Steve Naroffedb4bc92008-12-09 12:56:34 +00001055Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1056 SourceRange SrcRange) {
Steve Naroff0e948412008-12-04 16:24:46 +00001057 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1058 // This allows us to reuse all the fun and games in SynthMessageExpr().
1059 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1060 ObjCMessageExpr *MsgExpr;
1061 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1062 llvm::SmallVector<Expr *, 1> ExprVec;
1063 ExprVec.push_back(newStmt);
1064
Steve Narofffbed6802008-12-08 16:43:47 +00001065 Stmt *Receiver = PropRefExpr->getBase();
1066 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1067 if (PRE && PropGetters[PRE]) {
1068 // This allows us to handle chain/nested property getters.
1069 Receiver = PropGetters[PRE];
1070 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001071 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff0e948412008-12-04 16:24:46 +00001072 PDecl->getSetterName(), PDecl->getType(),
1073 PDecl->getSetterMethodDecl(),
1074 SourceLocation(), SourceLocation(),
1075 &ExprVec[0], 1);
1076 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1077
1078 // Now do the actual rewrite.
Steve Naroffedb4bc92008-12-09 12:56:34 +00001079 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroff478f7382008-12-10 14:53:27 +00001080 //delete BinOp;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001081 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1082 // to things that stay around.
1083 Context->Deallocate(MsgExpr);
Steve Naroff0e948412008-12-04 16:24:46 +00001084 return ReplacingStmt;
Steve Narofff6ce8a12008-12-03 00:56:33 +00001085}
1086
Steve Naroff0e948412008-12-04 16:24:46 +00001087Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff6ce8a12008-12-03 00:56:33 +00001088 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1089 // This allows us to reuse all the fun and games in SynthMessageExpr().
1090 ObjCMessageExpr *MsgExpr;
1091 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1092
Steve Narofffbed6802008-12-08 16:43:47 +00001093 Stmt *Receiver = PropRefExpr->getBase();
1094
1095 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1096 if (PRE && PropGetters[PRE]) {
1097 // This allows us to handle chain/nested property getters.
1098 Receiver = PropGetters[PRE];
1099 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001100 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Narofff6ce8a12008-12-03 00:56:33 +00001101 PDecl->getGetterName(), PDecl->getType(),
1102 PDecl->getGetterMethodDecl(),
1103 SourceLocation(), SourceLocation(),
1104 0, 0);
1105
Steve Naroff102c3f22008-12-04 23:50:32 +00001106 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001107
1108 if (!PropParentMap)
1109 PropParentMap = new ParentMap(CurrentBody);
1110
1111 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1112 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1113 // We stash away the ReplacingStmt since actually doing the
1114 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1115 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001116 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1117 // to things that stay around.
1118 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001119 return PropRefExpr; // return the original...
1120 } else {
1121 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001122 // delete PropRefExpr; elsewhere...
1123 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1124 // to things that stay around.
1125 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001126 return ReplacingStmt;
1127 }
Steve Narofff6ce8a12008-12-03 00:56:33 +00001128}
1129
Chris Lattner343c82b2008-05-23 20:40:52 +00001130Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1131 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001132 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001133 if (CurMethodDef) {
Steve Naroff60dfb6b2008-03-12 00:25:36 +00001134 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001135 ObjCInterfaceType *iFaceDecl =
1136 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffa9636222008-05-08 17:52:16 +00001137 // lookup which class implements the instance variable.
1138 ObjCInterfaceDecl *clsDeclared = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001139 iFaceDecl->getDecl()->lookupInstanceVariable(*Context,
1140 D->getIdentifier(),
1141 clsDeclared);
Steve Naroffa9636222008-05-08 17:52:16 +00001142 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1143
1144 // Synthesize an explicit cast to gain access to the ivar.
1145 std::string RecName = clsDeclared->getIdentifier()->getName();
1146 RecName += "_IMPL";
1147 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001148 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001149 SourceLocation(), II);
Steve Naroffa9636222008-05-08 17:52:16 +00001150 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1151 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek0c97e042009-02-07 01:47:29 +00001152 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1153 castT,SourceLocation(),
1154 SourceLocation());
Steve Naroffa9636222008-05-08 17:52:16 +00001155 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001156 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1157 IV->getBase()->getLocEnd(),
1158 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +00001159 if (IV->isFreeIvar() &&
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001160 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001161 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1162 IV->getLocation(),
1163 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +00001164 ReplaceStmt(IV, ME);
Steve Naroff102c3f22008-12-04 23:50:32 +00001165 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffa9636222008-05-08 17:52:16 +00001166 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +00001167 }
Chris Lattner343c82b2008-05-23 20:40:52 +00001168
1169 ReplaceStmt(IV->getBase(), PE);
1170 // Cannot delete IV->getBase(), since PE points to it.
1171 // Replace the old base with the cast. This is important when doing
1172 // embedded rewrites. For example, [newInv->_container addObject:0].
1173 IV->setBase(PE);
1174 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +00001175 }
Steve Naroffe6155362008-04-18 21:55:08 +00001176 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +00001177 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1178
1179 // Explicit ivar refs need to have a cast inserted.
1180 // FIXME: consider sharing some of this code with the code above.
1181 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +00001182 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001183 // lookup which class implements the instance variable.
1184 ObjCInterfaceDecl *clsDeclared = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001185 iFaceDecl->getDecl()->lookupInstanceVariable(*Context,
1186 D->getIdentifier(),
1187 clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001188 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1189
1190 // Synthesize an explicit cast to gain access to the ivar.
1191 std::string RecName = clsDeclared->getIdentifier()->getName();
1192 RecName += "_IMPL";
1193 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001194 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001195 SourceLocation(), II);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001196 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1197 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek0c97e042009-02-07 01:47:29 +00001198 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1199 castT, SourceLocation(),
1200 SourceLocation());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001201 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001202 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner3cca6612008-05-28 16:38:23 +00001203 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001204 ReplaceStmt(IV->getBase(), PE);
1205 // Cannot delete IV->getBase(), since PE points to it.
1206 // Replace the old base with the cast. This is important when doing
1207 // embedded rewrites. For example, [newInv->_container addObject:0].
1208 IV->setBase(PE);
1209 return IV;
1210 }
Steve Naroff292b7b92007-11-15 11:33:00 +00001211 }
Steve Naroffe6155362008-04-18 21:55:08 +00001212 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +00001213}
1214
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001215/// SynthCountByEnumWithState - To print:
1216/// ((unsigned int (*)
1217/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1218/// (void *)objc_msgSend)((id)l_collection,
1219/// sel_registerName(
1220/// "countByEnumeratingWithState:objects:count:"),
1221/// &enumState,
1222/// (id *)items, (unsigned int)16)
1223///
Steve Naroff44e81222008-04-14 22:03:09 +00001224void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001225 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1226 "id *, unsigned int))(void *)objc_msgSend)";
1227 buf += "\n\t\t";
1228 buf += "((id)l_collection,\n\t\t";
1229 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1230 buf += "\n\t\t";
1231 buf += "&enumState, "
1232 "(id *)items, (unsigned int)16)";
1233}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001234
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001235/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1236/// statement to exit to its outer synthesized loop.
1237///
Steve Naroff44e81222008-04-14 22:03:09 +00001238Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001239 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1240 return S;
1241 // replace break with goto __break_label
1242 std::string buf;
1243
1244 SourceLocation startLoc = S->getLocStart();
1245 buf = "goto __break_label_";
1246 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001247 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001248
1249 return 0;
1250}
1251
1252/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1253/// statement to continue with its inner synthesized loop.
1254///
Steve Naroff44e81222008-04-14 22:03:09 +00001255Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001256 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1257 return S;
1258 // replace continue with goto __continue_label
1259 std::string buf;
1260
1261 SourceLocation startLoc = S->getLocStart();
1262 buf = "goto __continue_label_";
1263 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001264 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001265
1266 return 0;
1267}
1268
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001269/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001270/// It rewrites:
1271/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001272
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001273/// Into:
1274/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001275/// type elem;
1276/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001277/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001278/// id l_collection = (id)collection;
1279/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1280/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001281/// if (limit) {
1282/// unsigned long startMutations = *enumState.mutationsPtr;
1283/// do {
1284/// unsigned long counter = 0;
1285/// do {
1286/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001287/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001288/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001289/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001290/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001291/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001292/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1293/// objects:items count:16]);
1294/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001295/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001296/// }
1297/// else
1298/// elem = nil;
1299/// }
1300///
Steve Naroff44e81222008-04-14 22:03:09 +00001301Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001302 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001303 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1304 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1305 "ObjCForCollectionStmt Statement stack mismatch");
1306 assert(!ObjCBcLabelNo.empty() &&
1307 "ObjCForCollectionStmt - Label No stack empty");
1308
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001309 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001310 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001311 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001312 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001313 std::string buf;
1314 buf = "\n{\n\t";
1315 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1316 // type elem;
Chris Lattner4a9a85e2009-03-28 06:33:19 +00001317 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001318 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001319 elementTypeAsString = ElementType.getAsString();
1320 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001321 buf += " ";
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001322 elementName = D->getNameAsCString();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001323 buf += elementName;
1324 buf += ";\n\t";
1325 }
Chris Lattner690c2872008-04-08 05:52:18 +00001326 else {
1327 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001328 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001329 elementTypeAsString
1330 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001331 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001332
1333 // struct __objcFastEnumerationState enumState = { 0 };
1334 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1335 // id items[16];
1336 buf += "id items[16];\n\t";
1337 // id l_collection = (id)
1338 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001339 // Find start location of 'collection' the hard way!
1340 const char *startCollectionBuf = startBuf;
1341 startCollectionBuf += 3; // skip 'for'
1342 startCollectionBuf = strchr(startCollectionBuf, '(');
1343 startCollectionBuf++; // skip '('
1344 // find 'in' and skip it.
1345 while (*startCollectionBuf != ' ' ||
1346 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1347 (*(startCollectionBuf+3) != ' ' &&
1348 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1349 startCollectionBuf++;
1350 startCollectionBuf += 3;
1351
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001352 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001353 ReplaceText(startLoc, startCollectionBuf - startBuf,
1354 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001355 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001356 SourceLocation rightParenLoc = S->getRParenLoc();
1357 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1358 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001359 buf = ";\n\t";
1360
1361 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1362 // objects:items count:16];
1363 // which is synthesized into:
1364 // unsigned int limit =
1365 // ((unsigned int (*)
1366 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1367 // (void *)objc_msgSend)((id)l_collection,
1368 // sel_registerName(
1369 // "countByEnumeratingWithState:objects:count:"),
1370 // (struct __objcFastEnumerationState *)&state,
1371 // (id *)items, (unsigned int)16);
1372 buf += "unsigned long limit =\n\t\t";
1373 SynthCountByEnumWithState(buf);
1374 buf += ";\n\t";
1375 /// if (limit) {
1376 /// unsigned long startMutations = *enumState.mutationsPtr;
1377 /// do {
1378 /// unsigned long counter = 0;
1379 /// do {
1380 /// if (startMutations != *enumState.mutationsPtr)
1381 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001382 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001383 buf += "if (limit) {\n\t";
1384 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1385 buf += "do {\n\t\t";
1386 buf += "unsigned long counter = 0;\n\t\t";
1387 buf += "do {\n\t\t\t";
1388 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1389 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1390 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001391 buf += " = (";
1392 buf += elementTypeAsString;
1393 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001394 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001395 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001396
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001397 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001398 /// } while (counter < limit);
1399 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1400 /// objects:items count:16]);
1401 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001402 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001403 /// }
1404 /// else
1405 /// elem = nil;
1406 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001407 ///
1408 buf = ";\n\t";
1409 buf += "__continue_label_";
1410 buf += utostr(ObjCBcLabelNo.back());
1411 buf += ": ;";
1412 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001413 buf += "} while (counter < limit);\n\t";
1414 buf += "} while (limit = ";
1415 SynthCountByEnumWithState(buf);
1416 buf += ");\n\t";
1417 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001418 buf += " = ((id)0);\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001419 buf += "__break_label_";
1420 buf += utostr(ObjCBcLabelNo.back());
1421 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001422 buf += "}\n\t";
1423 buf += "else\n\t\t";
1424 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001425 buf += " = ((id)0);\n";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001426 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001427
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001428 // Insert all these *after* the statement body.
Sebastian Redlbc9ef252009-04-26 20:35:05 +00001429 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff5f238fe2008-07-21 18:26:02 +00001430 if (isa<CompoundStmt>(S->getBody())) {
1431 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1432 InsertText(endBodyLoc, buf.c_str(), buf.size());
1433 } else {
1434 /* Need to treat single statements specially. For example:
1435 *
1436 * for (A *a in b) if (stuff()) break;
1437 * for (A *a in b) xxxyy;
1438 *
1439 * The following code simply scans ahead to the semi to find the actual end.
1440 */
1441 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1442 const char *semiBuf = strchr(stmtBuf, ';');
1443 assert(semiBuf && "Can't find ';'");
1444 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1445 InsertText(endBodyLoc, buf.c_str(), buf.size());
1446 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001447 Stmts.pop_back();
1448 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001449 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001450}
1451
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001452/// RewriteObjCSynchronizedStmt -
1453/// This routine rewrites @synchronized(expr) stmt;
1454/// into:
1455/// objc_sync_enter(expr);
1456/// @try stmt @finally { objc_sync_exit(expr); }
1457///
Steve Naroff44e81222008-04-14 22:03:09 +00001458Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001459 // Get the start location and compute the semi location.
1460 SourceLocation startLoc = S->getLocStart();
1461 const char *startBuf = SM->getCharacterData(startLoc);
1462
1463 assert((*startBuf == '@') && "bogus @synchronized location");
1464
1465 std::string buf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001466 buf = "objc_sync_enter((id)";
1467 const char *lparenBuf = startBuf;
1468 while (*lparenBuf != '(') lparenBuf++;
1469 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroff027cd0b2008-08-19 13:04:19 +00001470 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1471 // the sync expression is typically a message expression that's already
1472 // been rewritten! (which implies the SourceLocation's are invalid).
1473 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001474 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroff027cd0b2008-08-19 13:04:19 +00001475 while (*endBuf != ')') endBuf--;
1476 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001477 buf = ");\n";
1478 // declare a new scope with two variables, _stack and _rethrow.
1479 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1480 buf += "int buf[18/*32-bit i386*/];\n";
1481 buf += "char *pointers[4];} _stack;\n";
1482 buf += "id volatile _rethrow = 0;\n";
1483 buf += "objc_exception_try_enter(&_stack);\n";
1484 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001485 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001486 startLoc = S->getSynchBody()->getLocEnd();
1487 startBuf = SM->getCharacterData(startLoc);
1488
Steve Naroff027cd0b2008-08-19 13:04:19 +00001489 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001490 SourceLocation lastCurlyLoc = startLoc;
1491 buf = "}\nelse {\n";
1492 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1493 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001494 buf += " objc_sync_exit(";
Ted Kremenek0c97e042009-02-07 01:47:29 +00001495 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1496 S->getSynchExpr(),
1497 Context->getObjCIdType(),
1498 SourceLocation(),
1499 SourceLocation());
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001500 std::string syncExprBufS;
1501 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroffc1656a62008-08-21 13:03:03 +00001502 syncExpr->printPretty(syncExprBuf);
Steve Naroff17919b52008-07-16 19:47:39 +00001503 buf += syncExprBuf.str();
1504 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001505 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1506 buf += "}\n";
1507 buf += "}";
1508
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001509 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001510 return 0;
1511}
1512
Steve Naroff43964fb2008-12-05 17:03:39 +00001513void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1514 // Perform a bottom up traversal of all children.
1515 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1516 CI != E; ++CI)
1517 if (*CI)
1518 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1519
1520 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1521 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1522 Diags.Report(Context->getFullLoc(S->getLocStart()),
1523 TryFinallyContainsReturnDiag);
1524 }
1525 return;
1526}
1527
Steve Naroff44e81222008-04-14 22:03:09 +00001528Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001529 // Get the start location and compute the semi location.
1530 SourceLocation startLoc = S->getLocStart();
1531 const char *startBuf = SM->getCharacterData(startLoc);
1532
1533 assert((*startBuf == '@') && "bogus @try location");
1534
1535 std::string buf;
1536 // declare a new scope with two variables, _stack and _rethrow.
1537 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1538 buf += "int buf[18/*32-bit i386*/];\n";
1539 buf += "char *pointers[4];} _stack;\n";
1540 buf += "id volatile _rethrow = 0;\n";
1541 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001542 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001543
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001544 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001545
1546 startLoc = S->getTryBody()->getLocEnd();
1547 startBuf = SM->getCharacterData(startLoc);
1548
1549 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001550
Steve Naroffe9f69842007-11-07 04:08:17 +00001551 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001552 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1553 if (catchList) {
1554 startLoc = startLoc.getFileLocWithOffset(1);
1555 buf = " /* @catch begin */ else {\n";
1556 buf += " id _caught = objc_exception_extract(&_stack);\n";
1557 buf += " objc_exception_try_enter (&_stack);\n";
1558 buf += " if (_setjmp(_stack.buf))\n";
1559 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1560 buf += " else { /* @catch continue */";
1561
1562 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff36269d22008-09-09 19:59:12 +00001563 } else { /* no catch list */
1564 buf = "}\nelse {\n";
1565 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1566 buf += "}";
1567 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff9d0ff352008-07-16 15:31:30 +00001568 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001569 bool sawIdTypedCatch = false;
1570 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001571 while (catchList) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001572 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffe9f69842007-11-07 04:08:17 +00001573
1574 if (catchList == S->getCatchStmts())
1575 buf = "if ("; // we are generating code for the first catch clause
1576 else
1577 buf = "else if (";
1578 startLoc = catchList->getLocStart();
1579 startBuf = SM->getCharacterData(startLoc);
1580
1581 assert((*startBuf == '@') && "bogus @catch location");
1582
1583 const char *lParenLoc = strchr(startBuf, '(');
1584
Steve Naroff397c4ce2008-02-01 22:08:12 +00001585 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001586 // Now rewrite the body...
1587 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001588 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1589 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001590 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1591 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001592 assert((*bodyBuf == '{') && "bogus @catch body location");
1593
1594 buf += "1) { id _tmp = _caught;";
1595 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1596 buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001597 } else if (catchDecl) {
1598 QualType t = catchDecl->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001599 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001600 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001601 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001602 sawIdTypedCatch = true;
1603 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001604 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001605
Ted Kremenek42730c52008-01-07 19:49:32 +00001606 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001607 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001608 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00001609 buf += cls->getDecl()->getNameAsString();
Steve Naroffd3287d82007-11-07 18:43:40 +00001610 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001611 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001612 }
1613 }
1614 // Now rewrite the body...
1615 lastCatchBody = catchList->getCatchBody();
1616 SourceLocation rParenLoc = catchList->getRParenLoc();
1617 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1618 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1619 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1620 assert((*rParenBuf == ')') && "bogus @catch paren location");
1621 assert((*bodyBuf == '{') && "bogus @catch body location");
1622
1623 buf = " = _caught;";
1624 // Here we replace ") {" with "= _caught;" (which initializes and
1625 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001626 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001627 } else {
Steve Naroffe9f69842007-11-07 04:08:17 +00001628 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001629 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001630 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001631 catchList = catchList->getNextCatchStmt();
1632 }
1633 // Complete the catch list...
1634 if (lastCatchBody) {
1635 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001636 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1637 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001638
Steve Naroff31325c12008-09-11 15:29:03 +00001639 // Insert the last (implicit) else clause *before* the right curly brace.
1640 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1641 buf = "} /* last catch end */\n";
1642 buf += "else {\n";
1643 buf += " _rethrow = _caught;\n";
1644 buf += " objc_exception_try_exit(&_stack);\n";
1645 buf += "} } /* @catch end */\n";
1646 if (!S->getFinallyStmt())
1647 buf += "}\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001648 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001649
1650 // Set lastCurlyLoc
1651 lastCurlyLoc = lastCatchBody->getLocEnd();
1652 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001653 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001654 startLoc = finalStmt->getLocStart();
1655 startBuf = SM->getCharacterData(startLoc);
1656 assert((*startBuf == '@') && "bogus @finally start");
1657
1658 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001659 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001660
1661 Stmt *body = finalStmt->getFinallyBody();
1662 SourceLocation startLoc = body->getLocStart();
1663 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001664 assert(*SM->getCharacterData(startLoc) == '{' &&
1665 "bogus @finally body location");
1666 assert(*SM->getCharacterData(endLoc) == '}' &&
1667 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001668
1669 startLoc = startLoc.getFileLocWithOffset(1);
1670 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001671 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001672 endLoc = endLoc.getFileLocWithOffset(-1);
1673 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001674 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001675
1676 // Set lastCurlyLoc
1677 lastCurlyLoc = body->getLocEnd();
Steve Naroff43964fb2008-12-05 17:03:39 +00001678
1679 // Now check for any return/continue/go statements within the @try.
1680 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff31325c12008-09-11 15:29:03 +00001681 } else { /* no finally clause - make sure we synthesize an implicit one */
1682 buf = "{ /* implicit finally clause */\n";
1683 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1684 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1685 buf += "}";
1686 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001687 }
1688 // Now emit the final closing curly brace...
1689 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1690 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001691 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001692 return 0;
1693}
1694
Steve Naroff44e81222008-04-14 22:03:09 +00001695Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001696 return 0;
1697}
1698
Steve Naroff44e81222008-04-14 22:03:09 +00001699Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001700 return 0;
1701}
1702
Chris Lattnerb1548372008-01-31 19:37:57 +00001703// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001704// the throw expression is typically a message expression that's already
1705// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001706Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001707 // Get the start location and compute the semi location.
1708 SourceLocation startLoc = S->getLocStart();
1709 const char *startBuf = SM->getCharacterData(startLoc);
1710
1711 assert((*startBuf == '@') && "bogus @throw location");
1712
1713 std::string buf;
1714 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001715 if (S->getThrowExpr())
1716 buf = "objc_exception_throw(";
1717 else // add an implicit argument
1718 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001719
1720 // handle "@ throw" correctly.
1721 const char *wBuf = strchr(startBuf, 'w');
1722 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1723 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1724
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001725 const char *semiBuf = strchr(startBuf, ';');
1726 assert((*semiBuf == ';') && "@throw: can't find ';'");
1727 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1728 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001729 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001730 return 0;
1731}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001732
Steve Naroff44e81222008-04-14 22:03:09 +00001733Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001734 // Create a new string expression.
1735 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001736 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001737 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattneraa491192009-02-18 06:40:38 +00001738 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1739 StrEncoding.length(), false,StrType,
1740 SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001741 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001742
Chris Lattner4478db92007-11-30 22:53:43 +00001743 // Replace this subexpr in the parent.
Steve Naroff102c3f22008-12-04 23:50:32 +00001744 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner0021f452007-10-24 16:57:36 +00001745 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001746}
1747
Steve Naroff44e81222008-04-14 22:03:09 +00001748Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff95f6bce2008-12-22 22:16:07 +00001749 if (!SelGetUidFunctionDecl)
1750 SynthSelGetUidFunctionDecl();
Steve Naroff296b74f2007-11-05 14:50:49 +00001751 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1752 // Create a call to sel_registerName("selName").
1753 llvm::SmallVector<Expr*, 8> SelExprs;
1754 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00001755 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00001756 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00001757 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00001758 false, argType, SourceLocation()));
Steve Naroff296b74f2007-11-05 14:50:49 +00001759 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1760 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001761 ReplaceStmt(Exp, SelExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00001762 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff296b74f2007-11-05 14:50:49 +00001763 return SelExp;
1764}
1765
Steve Naroff44e81222008-04-14 22:03:09 +00001766CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001767 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001768 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001769 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001770
1771 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001772 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001773
1774 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001775 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001776 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregor70d26122008-11-12 17:17:38 +00001777 /*isLvalue=*/false);
Steve Naroffe9780582007-10-23 23:50:29 +00001778
1779 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001780
Ted Kremenek362abcd2009-02-09 20:51:47 +00001781 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1782 SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001783}
1784
Steve Naroffc8a92d12007-11-01 13:24:47 +00001785static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1786 const char *&startRef, const char *&endRef) {
1787 while (startBuf < endBuf) {
1788 if (*startBuf == '<')
1789 startRef = startBuf; // mark the start.
1790 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001791 if (startRef && *startRef == '<') {
1792 endRef = startBuf; // mark the end.
1793 return true;
1794 }
1795 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001796 }
1797 startBuf++;
1798 }
1799 return false;
1800}
1801
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001802static void scanToNextArgument(const char *&argRef) {
1803 int angle = 0;
1804 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1805 if (*argRef == '<')
1806 angle++;
1807 else if (*argRef == '>')
1808 angle--;
1809 argRef++;
1810 }
1811 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1812}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001813
Steve Naroff44e81222008-04-14 22:03:09 +00001814bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001815
Ted Kremenek42730c52008-01-07 19:49:32 +00001816 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001817 return true;
1818
Steve Naroffc8a92d12007-11-01 13:24:47 +00001819 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001820 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001821 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001822 return true; // we have "Class <Protocol> *".
1823 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001824 return false;
1825}
1826
Steve Naroffd06c88d2008-07-29 18:15:38 +00001827void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1828 QualType Type = E->getType();
1829 if (needToScanForQualifiers(Type)) {
Steve Narofff31ece92008-11-19 21:15:47 +00001830 SourceLocation Loc, EndLoc;
1831
1832 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1833 Loc = ECE->getLParenLoc();
1834 EndLoc = ECE->getRParenLoc();
1835 } else {
1836 Loc = E->getLocStart();
1837 EndLoc = E->getLocEnd();
1838 }
1839 // This will defend against trying to rewrite synthesized expressions.
1840 if (Loc.isInvalid() || EndLoc.isInvalid())
1841 return;
1842
Steve Naroffd06c88d2008-07-29 18:15:38 +00001843 const char *startBuf = SM->getCharacterData(Loc);
Steve Narofff31ece92008-11-19 21:15:47 +00001844 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroffd06c88d2008-07-29 18:15:38 +00001845 const char *startRef = 0, *endRef = 0;
1846 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1847 // Get the locations of the startRef, endRef.
1848 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1849 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1850 // Comment out the protocol references.
1851 InsertText(LessLoc, "/*", 2);
1852 InsertText(GreaterLoc, "*/", 2);
1853 }
1854 }
1855}
1856
Steve Naroff44e81222008-04-14 22:03:09 +00001857void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001858 SourceLocation Loc;
1859 QualType Type;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001860 const FunctionProtoType *proto = 0;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001861 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1862 Loc = VD->getLocation();
1863 Type = VD->getType();
1864 }
1865 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1866 Loc = FD->getLocation();
1867 // Check for ObjC 'id' and class types that have been adorned with protocol
1868 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1869 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1870 assert(funcType && "missing function type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00001871 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001872 if (!proto)
1873 return;
1874 Type = proto->getResultType();
1875 }
1876 else
1877 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001878
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001879 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001880 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001881
1882 const char *endBuf = SM->getCharacterData(Loc);
1883 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001884 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001885 startBuf--; // scan backward (from the decl location) for return type.
1886 const char *startRef = 0, *endRef = 0;
1887 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1888 // Get the locations of the startRef, endRef.
1889 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1890 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1891 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001892 InsertText(LessLoc, "/*", 2);
1893 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001894 }
1895 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001896 if (!proto)
1897 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001898 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001899 const char *startBuf = SM->getCharacterData(Loc);
1900 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001901 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1902 if (needToScanForQualifiers(proto->getArgType(i))) {
1903 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001904
Steve Naroffc8a92d12007-11-01 13:24:47 +00001905 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001906 // scan forward (from the decl location) for argument types.
1907 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001908 const char *startRef = 0, *endRef = 0;
1909 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1910 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001911 SourceLocation LessLoc =
1912 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1913 SourceLocation GreaterLoc =
1914 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001915 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001916 InsertText(LessLoc, "/*", 2);
1917 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001918 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001919 startBuf = ++endBuf;
1920 }
1921 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001922 // If the function name is derived from a macro expansion, then the
1923 // argument buffer will not follow the name. Need to speak with Chris.
1924 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001925 startBuf++; // scan forward (from the decl location) for argument types.
1926 startBuf++;
1927 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001928 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001929}
1930
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001931// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001932void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001933 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1934 llvm::SmallVector<QualType, 16> ArgTys;
1935 ArgTys.push_back(Context->getPointerType(
1936 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001937 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001938 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001939 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001940 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001941 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001942 SelGetUidIdent, getFuncType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001943 FunctionDecl::Extern, false);
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001944}
1945
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001946// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001947void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001948 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1949 llvm::SmallVector<QualType, 16> ArgTys;
1950 ArgTys.push_back(Context->getPointerType(
1951 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001952 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001953 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001954 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001955 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001956 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001957 SelGetProtoIdent, getFuncType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001958 FunctionDecl::Extern, false);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001959}
1960
Steve Naroff44e81222008-04-14 22:03:09 +00001961void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001962 // declared in <objc/objc.h>
Douglas Gregor7339c9e2009-01-09 01:47:02 +00001963 if (FD->getIdentifier() &&
1964 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001965 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001966 return;
1967 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001968 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001969}
1970
Steve Naroffbec4bf52008-03-11 17:37:02 +00001971// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001972void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001973 if (SuperContructorFunctionDecl)
1974 return;
Steve Naroff12673622008-12-23 20:11:22 +00001975 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffbec4bf52008-03-11 17:37:02 +00001976 llvm::SmallVector<QualType, 16> ArgTys;
1977 QualType argT = Context->getObjCIdType();
1978 assert(!argT.isNull() && "Can't find 'id' type");
1979 ArgTys.push_back(argT);
1980 ArgTys.push_back(argT);
1981 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1982 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001983 false, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001984 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001985 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001986 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001987 FunctionDecl::Extern, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00001988}
1989
Steve Naroff02a82aa2007-10-30 23:14:51 +00001990// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001991void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001992 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1993 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001994 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001995 assert(!argT.isNull() && "Can't find 'id' type");
1996 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001997 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001998 assert(!argT.isNull() && "Can't find 'SEL' type");
1999 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002000 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002001 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002002 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002003 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002004 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002005 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002006 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00002007}
2008
Steve Naroff764c1ae2007-11-15 10:28:18 +00002009// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002010void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002011 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2012 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002013 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002014 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002015 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002016 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2017 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2018 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002019 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002020 assert(!argT.isNull() && "Can't find 'SEL' type");
2021 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002022 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002023 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002024 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002025 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002026 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002027 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002028 FunctionDecl::Extern, false);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002029}
2030
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002031// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002032void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002033 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2034 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002035 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002036 assert(!argT.isNull() && "Can't find 'id' type");
2037 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002038 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002039 assert(!argT.isNull() && "Can't find 'SEL' type");
2040 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002041 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002042 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002043 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002044 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002045 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002046 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002047 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002048}
2049
2050// SynthMsgSendSuperStretFunctionDecl -
2051// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002052void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002053 IdentifierInfo *msgSendIdent =
2054 &Context->Idents.get("objc_msgSendSuper_stret");
2055 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002056 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002057 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002058 &Context->Idents.get("objc_super"));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002059 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2060 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2061 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002062 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002063 assert(!argT.isNull() && "Can't find 'SEL' type");
2064 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002065 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002066 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002067 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002068 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00002069 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002070 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002071 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002072}
2073
Steve Naroff31316a12008-05-08 22:02:18 +00002074// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002075void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002076 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2077 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002078 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002079 assert(!argT.isNull() && "Can't find 'id' type");
2080 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002081 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002082 assert(!argT.isNull() && "Can't find 'SEL' type");
2083 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00002084 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002085 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002086 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002087 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002088 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002089 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002090 FunctionDecl::Extern, false);
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002091}
2092
Steve Naroff02a82aa2007-10-30 23:14:51 +00002093// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002094void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00002095 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2096 llvm::SmallVector<QualType, 16> ArgTys;
2097 ArgTys.push_back(Context->getPointerType(
2098 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002099 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002100 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002101 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002102 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002103 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002104 getClassIdent, getClassType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002105 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00002106}
2107
Steve Naroff3b1caac2007-12-07 03:50:46 +00002108// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002109void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002110 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2111 llvm::SmallVector<QualType, 16> ArgTys;
2112 ArgTys.push_back(Context->getPointerType(
2113 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002114 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002115 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002116 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002117 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002118 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002119 getClassIdent, getClassType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002120 FunctionDecl::Extern, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002121}
2122
Steve Naroff44e81222008-04-14 22:03:09 +00002123Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002124 QualType strType = getConstantStringStructType();
2125
2126 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00002127
2128 std::string tmpName = InFileName;
2129 unsigned i;
2130 for (i=0; i < tmpName.length(); i++) {
2131 char c = tmpName.at(i);
2132 // replace any non alphanumeric characters with '_'.
2133 if (!isalpha(c) && (c < '0' || c > '9'))
2134 tmpName[i] = '_';
2135 }
2136 S += tmpName;
2137 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002138 S += utostr(NumObjCStringLiterals++);
2139
Steve Narofffef037c2008-03-27 22:29:16 +00002140 Preamble += "static __NSConstantStringImpl " + S;
2141 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2142 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00002143 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00002144 std::string prettyBufS;
2145 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002146 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00002147 Preamble += prettyBuf.str();
2148 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00002149 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00002150 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002151
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002152 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002153 &Context->Idents.get(S.c_str()), strType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002154 VarDecl::Static);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002155 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2156 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroff47e7fa22008-03-15 00:55:56 +00002157 Context->getPointerType(DRE->getType()),
2158 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00002159 // cast to NSConstantString *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002160 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroff7f1412d2008-11-03 23:29:32 +00002161 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00002162 ReplaceStmt(Exp, cast);
Steve Naroff102c3f22008-12-04 23:50:32 +00002163 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffabb96362007-11-08 14:30:50 +00002164 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00002165}
2166
Steve Naroff44e81222008-04-14 22:03:09 +00002167ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002168 // check if we are sending a message to 'super'
Douglas Gregor5d764842009-01-09 17:18:27 +00002169 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattnere4650482008-03-15 06:12:44 +00002170
Douglas Gregord8606632008-11-04 14:56:14 +00002171 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2172 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner4423d372008-06-21 18:04:54 +00002173 assert(PT);
2174 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2175 return IT->getDecl();
2176 }
2177 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002178}
2179
2180// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00002181QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002182 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002183 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002184 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002185 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002186 QualType FieldTypes[2];
2187
2188 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00002189 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002190 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00002191 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002192
Steve Naroff764c1ae2007-11-15 10:28:18 +00002193 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002194 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002195 SuperStructDecl->addDecl(*Context,
2196 FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002197 SourceLocation(), 0,
2198 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002199 /*Mutable=*/false));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002200 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002201
Douglas Gregor8acb7272008-12-11 16:49:14 +00002202 SuperStructDecl->completeDefinition(*Context);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002203 }
2204 return Context->getTagDeclType(SuperStructDecl);
2205}
2206
Steve Naroff44e81222008-04-14 22:03:09 +00002207QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002208 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002209 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002210 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002211 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroff47e7fa22008-03-15 00:55:56 +00002212 QualType FieldTypes[4];
2213
2214 // struct objc_object *receiver;
2215 FieldTypes[0] = Context->getObjCIdType();
2216 // int flags;
2217 FieldTypes[1] = Context->IntTy;
2218 // char *str;
2219 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2220 // long length;
2221 FieldTypes[3] = Context->LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002222
Steve Naroff47e7fa22008-03-15 00:55:56 +00002223 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002224 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002225 ConstantStringDecl->addDecl(*Context,
2226 FieldDecl::Create(*Context,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002227 ConstantStringDecl,
2228 SourceLocation(), 0,
2229 FieldTypes[i],
2230 /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002231 /*Mutable=*/true));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002232 }
2233
2234 ConstantStringDecl->completeDefinition(*Context);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002235 }
2236 return Context->getTagDeclType(ConstantStringDecl);
2237}
2238
Steve Naroff44e81222008-04-14 22:03:09 +00002239Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00002240 if (!SelGetUidFunctionDecl)
2241 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002242 if (!MsgSendFunctionDecl)
2243 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002244 if (!MsgSendSuperFunctionDecl)
2245 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002246 if (!MsgSendStretFunctionDecl)
2247 SynthMsgSendStretFunctionDecl();
2248 if (!MsgSendSuperStretFunctionDecl)
2249 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002250 if (!MsgSendFpretFunctionDecl)
2251 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002252 if (!GetClassFunctionDecl)
2253 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002254 if (!GetMetaClassFunctionDecl)
2255 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002256
Steve Naroff764c1ae2007-11-15 10:28:18 +00002257 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002258 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2259 // May need to use objc_msgSend_stret() as well.
2260 FunctionDecl *MsgSendStretFlavor = 0;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002261 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2262 QualType resultType = OMD->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00002263 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002264 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00002265 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002266 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002267 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002268
Steve Naroff71226032007-10-24 22:48:43 +00002269 // Synthesize a call to objc_msgSend().
2270 llvm::SmallVector<Expr*, 8> MsgExprs;
2271 IdentifierInfo *clsName = Exp->getClassName();
2272
2273 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2274 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00002275 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2276 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002277 if (!strcmp(clsName->getName(), "super")) {
2278 MsgSendFlavor = MsgSendSuperFunctionDecl;
2279 if (MsgSendStretFlavor)
2280 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2281 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2282
Ted Kremenek42730c52008-01-07 19:49:32 +00002283 ObjCInterfaceDecl *SuperDecl =
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002284 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002285
2286 llvm::SmallVector<Expr*, 4> InitExprs;
2287
2288 // set the receiver to self, the first argument to all methods.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002289 InitExprs.push_back(new (Context) DeclRefExpr(
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002290 CurMethodDef->getSelfDecl(),
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002291 Context->getObjCIdType(),
2292 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002293 llvm::SmallVector<Expr*, 8> ClsExprs;
2294 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002295 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002296 SuperDecl->getIdentifier()->getName(),
2297 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002298 false, argType, SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002299 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2300 &ClsExprs[0],
2301 ClsExprs.size());
2302 // To turn off a warning, type-cast to 'id'
Douglas Gregor21a04f32008-10-27 19:41:14 +00002303 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002304 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002305 Cls, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002306 SourceLocation(), SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002307 // struct objc_super
2308 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002309 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002310
Steve Naroffdee066b2008-03-11 18:14:26 +00002311 if (LangOpts.Microsoft) {
2312 SynthSuperContructorFunctionDecl();
2313 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002314 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffdee066b2008-03-11 18:14:26 +00002315 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002316 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2317 InitExprs.size(),
2318 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002319 // The code for super is a little tricky to prevent collision with
2320 // the structure definition in the header. The rewriter has it's own
2321 // internal definition (__rw_objc_super) that is uses. This is why
2322 // we need the cast below. For example:
2323 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2324 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002325 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002326 Context->getPointerType(SuperRep->getType()),
2327 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002328 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002329 SuperRep, Context->getPointerType(superType),
2330 SourceLocation(), SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002331 } else {
2332 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002333 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffdee066b2008-03-11 18:14:26 +00002334 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002335 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002336 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner71ca8c82008-10-26 23:43:26 +00002337 false);
Steve Naroff12673622008-12-23 20:11:22 +00002338 // struct objc_super *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002339 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002340 Context->getPointerType(SuperRep->getType()),
2341 SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002342 }
Steve Naroff12673622008-12-23 20:11:22 +00002343 MsgExprs.push_back(SuperRep);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002344 } else {
2345 llvm::SmallVector<Expr*, 8> ClsExprs;
2346 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002347 ClsExprs.push_back(StringLiteral::Create(*Context,
2348 clsName->getName(),
2349 clsName->getLength(),
2350 false, argType,
2351 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002352 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2353 &ClsExprs[0],
2354 ClsExprs.size());
2355 MsgExprs.push_back(Cls);
2356 }
Steve Naroff885e2122007-11-14 23:54:14 +00002357 } else { // instance message.
2358 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002359
Ted Kremenek42730c52008-01-07 19:49:32 +00002360 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002361 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002362 if (MsgSendStretFlavor)
2363 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002364 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2365
2366 llvm::SmallVector<Expr*, 4> InitExprs;
2367
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002368 InitExprs.push_back(
Ted Kremenek0c97e042009-02-07 01:47:29 +00002369 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2370 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff23528612008-07-16 22:35:27 +00002371 Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002372 SourceLocation()),
2373 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002374 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002375
2376 llvm::SmallVector<Expr*, 8> ClsExprs;
2377 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002378 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002379 SuperDecl->getIdentifier()->getName(),
2380 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002381 false, argType, SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002382 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002383 &ClsExprs[0],
2384 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002385 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002386 InitExprs.push_back(
Douglas Gregor21a04f32008-10-27 19:41:14 +00002387 // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002388 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002389 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002390 // struct objc_super
2391 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002392 Expr *SuperRep;
2393
2394 if (LangOpts.Microsoft) {
2395 SynthSuperContructorFunctionDecl();
2396 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002397 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffbec4bf52008-03-11 17:37:02 +00002398 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002399 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2400 InitExprs.size(),
2401 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002402 // The code for super is a little tricky to prevent collision with
2403 // the structure definition in the header. The rewriter has it's own
2404 // internal definition (__rw_objc_super) that is uses. This is why
2405 // we need the cast below. For example:
2406 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2407 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002408 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002409 Context->getPointerType(SuperRep->getType()),
2410 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002411 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002412 SuperRep, Context->getPointerType(superType),
2413 SourceLocation(), SourceLocation());
Steve Naroffbec4bf52008-03-11 17:37:02 +00002414 } else {
2415 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002416 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00002417 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002418 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002419 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00002420 }
Steve Naroff12673622008-12-23 20:11:22 +00002421 MsgExprs.push_back(SuperRep);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002422 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002423 // Remove all type-casts because it may contain objc-style types; e.g.
2424 // Foo<Proto> *.
Douglas Gregor035d0882008-10-28 15:36:24 +00002425 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002426 recExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002427 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002428 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002429 SourceLocation(), SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002430 MsgExprs.push_back(recExpr);
2431 }
Steve Naroff885e2122007-11-14 23:54:14 +00002432 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002433 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002434 llvm::SmallVector<Expr*, 8> SelExprs;
2435 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002436 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002437 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00002438 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002439 false, argType, SourceLocation()));
Steve Naroff71226032007-10-24 22:48:43 +00002440 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2441 &SelExprs[0], SelExprs.size());
2442 MsgExprs.push_back(SelExp);
2443
2444 // Now push any user supplied arguments.
2445 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002446 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002447 // Make all implicit casts explicit...ICE comes in handy:-)
2448 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2449 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor21a04f32008-10-27 19:41:14 +00002450 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002451 ? Context->getObjCIdType()
Douglas Gregor21a04f32008-10-27 19:41:14 +00002452 : ICE->getType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002453 userExpr = new (Context) CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002454 }
2455 // Make id<P...> cast into an 'id' cast.
Douglas Gregor035d0882008-10-28 15:36:24 +00002456 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002457 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor035d0882008-10-28 15:36:24 +00002458 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002459 userExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002460 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002461 userExpr, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002462 SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002463 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002464 }
Steve Naroff885e2122007-11-14 23:54:14 +00002465 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002466 // We've transferred the ownership to MsgExprs. Null out the argument in
2467 // the original expression, since we will delete it below.
2468 Exp->setArg(i, 0);
2469 }
Steve Naroff0744c472007-11-04 22:37:50 +00002470 // Generate the funky cast.
2471 CastExpr *cast;
2472 llvm::SmallVector<QualType, 8> ArgTypes;
2473 QualType returnType;
2474
2475 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002476 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2477 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2478 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002479 ArgTypes.push_back(Context->getObjCIdType());
2480 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002481 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002482 // Push any user argument types.
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002483 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2484 E = OMD->param_end(); PI != E; ++PI) {
2485 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002486 ? Context->getObjCIdType()
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002487 : (*PI)->getType();
Steve Naroff66c842f2008-10-29 14:49:46 +00002488 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00002489 if (isTopLevelBlockPointerType(t)) {
Steve Naroff66c842f2008-10-29 14:49:46 +00002490 const BlockPointerType *BPT = t->getAsBlockPointerType();
2491 t = Context->getPointerType(BPT->getPointeeType());
2492 }
Steve Naroff4242b972007-11-05 14:36:37 +00002493 ArgTypes.push_back(t);
2494 }
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002495 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2496 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002497 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002498 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002499 }
2500 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002501 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002502
2503 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002504 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002505 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002506
2507 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2508 // If we don't do this cast, we get the following bizarre warning/note:
2509 // xx.m:13: warning: function called through a non-compatible type
2510 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek0c97e042009-02-07 01:47:29 +00002511 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002512 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002513 SourceLocation(), SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002514
Steve Naroff0744c472007-11-04 22:37:50 +00002515 // Now do the "normal" pointer to function cast.
2516 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002517 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002518 // If we don't have a method decl, force a variadic cast.
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002519 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroff0744c472007-11-04 22:37:50 +00002520 castType = Context->getPointerType(castType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002521 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002522
2523 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002524 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroff0744c472007-11-04 22:37:50 +00002525
2526 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002527 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2528 MsgExprs.size(),
2529 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002530 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002531 if (MsgSendStretFlavor) {
2532 // We have the method which returns a struct/union. Must also generate
2533 // call to objc_msgSend_stret and hang both varieties on a conditional
2534 // expression which dictate which one to envoke depending on size of
2535 // method's return type.
2536
2537 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002538 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002539 SourceLocation());
2540 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek0c97e042009-02-07 01:47:29 +00002541 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002542 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002543 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002544 // Now do the "normal" pointer to function cast.
2545 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002546 &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002547 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002548 castType = Context->getPointerType(castType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002549 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002550
2551 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002552 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002553
2554 FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002555 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2556 MsgExprs.size(),
2557 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002558
2559 // Build sizeof(returnType)
Douglas Gregor396f1142009-03-13 21:01:28 +00002560 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
2561 returnType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002562 Context->getSizeType(),
2563 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002564 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2565 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2566 // For X86 it is more complicated and some kind of target specific routine
2567 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002568 unsigned IntSize =
2569 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek0c97e042009-02-07 01:47:29 +00002570 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002571 Context->IntTy,
2572 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002573 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002574 BinaryOperator::LE,
2575 Context->IntTy,
2576 SourceLocation());
2577 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2578 ConditionalOperator *CondExpr =
Ted Kremenek0c97e042009-02-07 01:47:29 +00002579 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2580 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002581 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002582 return ReplacingStmt;
2583}
2584
Steve Naroff44e81222008-04-14 22:03:09 +00002585Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002586 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroffe8efe892008-10-27 20:54:44 +00002587
Steve Naroff0e948412008-12-04 16:24:46 +00002588 //ReplacingStmt->dump();
Steve Naroff71226032007-10-24 22:48:43 +00002589 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002590 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002591
Steve Naroff102c3f22008-12-04 23:50:32 +00002592 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002593 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002594}
2595
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002596/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2597/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002598Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002599 if (!GetProtocolFunctionDecl)
2600 SynthGetProtocolFunctionDecl();
2601 // Create a call to objc_getProtocol("ProtocolName").
2602 llvm::SmallVector<Expr*, 8> ProtoExprs;
2603 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002604 ProtoExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002605 Exp->getProtocol()->getNameAsCString(),
2606 strlen(Exp->getProtocol()->getNameAsCString()),
Chris Lattnerc3144742009-02-18 05:49:11 +00002607 false, argType, SourceLocation()));
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002608 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2609 &ProtoExprs[0],
2610 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002611 ReplaceStmt(Exp, ProtoExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00002612 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002613 return ProtoExp;
2614
2615}
2616
Steve Naroffef82b742008-05-31 14:15:04 +00002617bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2618 const char *endBuf) {
2619 while (startBuf < endBuf) {
2620 if (*startBuf == '#') {
2621 // Skip whitespace.
2622 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2623 ;
2624 if (!strncmp(startBuf, "if", strlen("if")) ||
2625 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2626 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2627 !strncmp(startBuf, "define", strlen("define")) ||
2628 !strncmp(startBuf, "undef", strlen("undef")) ||
2629 !strncmp(startBuf, "else", strlen("else")) ||
2630 !strncmp(startBuf, "elif", strlen("elif")) ||
2631 !strncmp(startBuf, "endif", strlen("endif")) ||
2632 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2633 !strncmp(startBuf, "include", strlen("include")) ||
2634 !strncmp(startBuf, "import", strlen("import")) ||
2635 !strncmp(startBuf, "include_next", strlen("include_next")))
2636 return true;
2637 }
2638 startBuf++;
2639 }
2640 return false;
2641}
2642
Ted Kremenek42730c52008-01-07 19:49:32 +00002643/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002644/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002645void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002646 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002647 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002648 assert(CDecl->getNameAsCString() &&
Douglas Gregor24afd4a2008-11-17 14:58:09 +00002649 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002650 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002651 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002652 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002653 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002654 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002655 SourceLocation LocStart = CDecl->getLocStart();
2656 SourceLocation LocEnd = CDecl->getLocEnd();
2657
2658 const char *startBuf = SM->getCharacterData(LocStart);
2659 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002660
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002661 // If no ivars and no root or if its root, directly or indirectly,
2662 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002663 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2664 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattnere1be6022009-04-14 23:22:57 +00002665 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002666 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002667 return;
2668 }
2669
2670 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002671 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002672 Result += "\nstruct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002673 Result += CDecl->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +00002674 if (LangOpts.Microsoft)
2675 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002676
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002677 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002678 const char *cursor = strchr(startBuf, '{');
2679 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002680 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002681 // If the buffer contains preprocessor directives, we do more fine-grained
2682 // rewrites. This is intended to fix code that looks like (which occurs in
2683 // NSURL.h, for example):
2684 //
2685 // #ifdef XYZ
2686 // @interface Foo : NSObject
2687 // #else
2688 // @interface FooBar : NSObject
2689 // #endif
2690 // {
2691 // int i;
2692 // }
2693 // @end
2694 //
2695 // This clause is segregated to avoid breaking the common case.
2696 if (BufferContainsPPDirectives(startBuf, cursor)) {
2697 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2698 CDecl->getClassLoc();
2699 const char *endHeader = SM->getCharacterData(L);
Chris Lattnere1be6022009-04-14 23:22:57 +00002700 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffef82b742008-05-31 14:15:04 +00002701
Chris Lattner179fd522009-02-20 18:18:36 +00002702 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002703 // advance to the end of the referenced protocols.
2704 while (endHeader < cursor && *endHeader != '>') endHeader++;
2705 endHeader++;
2706 }
2707 // rewrite the original header
2708 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2709 } else {
2710 // rewrite the original header *without* disturbing the '{'
2711 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2712 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002713 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002714 Result = "\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002715 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002716 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002717 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002718 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002719
2720 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002721 SourceLocation OnePastCurly =
2722 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2723 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002724 }
2725 cursor++; // past '{'
2726
2727 // Now comment out any visibility specifiers.
2728 while (cursor < endBuf) {
2729 if (*cursor == '@') {
2730 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002731 // Skip whitespace.
2732 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2733 /*scan*/;
2734
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002735 // FIXME: presence of @public, etc. inside comment results in
2736 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002737 if (!strncmp(cursor, "public", strlen("public")) ||
2738 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002739 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002740 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002741 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002742 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002743 // FIXME: If there are cases where '<' is used in ivar declaration part
2744 // of user code, then scan the ivar list and use needToScanForQualifiers
2745 // for type checking.
2746 else if (*cursor == '<') {
2747 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002748 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002749 cursor = strchr(cursor, '>');
2750 cursor++;
2751 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002752 InsertText(atLoc, " */", 3);
Steve Naroff6449c6c2008-10-30 12:09:33 +00002753 } else if (*cursor == '^') { // rewrite block specifier.
2754 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2755 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002756 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002757 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002758 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002759 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002760 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002761 } else { // we don't have any instance variables - insert super struct.
Chris Lattnere1be6022009-04-14 23:22:57 +00002762 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002763 Result += " {\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002764 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002765 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002766 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002767 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002768 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002769 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002770 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002771 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002772 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002773}
2774
Ted Kremenek42730c52008-01-07 19:49:32 +00002775// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002776/// class methods.
Douglas Gregorcd19b572009-04-23 01:02:12 +00002777template<typename MethodIterator>
2778void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2779 MethodIterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002780 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002781 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002782 const char *ClassName,
2783 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002784 if (MethodBegin == MethodEnd) return;
2785
Fariborz Jahanian04455192007-10-22 21:41:37 +00002786 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002787 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002788 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002789 SEL _cmd;
2790 char *method_types;
2791 void *_imp;
2792 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002793 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002794 Result += "\nstruct _objc_method {\n";
2795 Result += "\tSEL _cmd;\n";
2796 Result += "\tchar *method_types;\n";
2797 Result += "\tvoid *_imp;\n";
2798 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002799
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002800 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002801 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002802
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002803 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002804
2805 /* struct {
2806 struct _objc_method_list *next_method;
2807 int method_count;
2808 struct _objc_method method_list[];
2809 }
2810 */
Douglas Gregorcd19b572009-04-23 01:02:12 +00002811 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc723eec2008-03-11 00:12:29 +00002812 Result += "\nstatic struct {\n";
2813 Result += "\tstruct _objc_method_list *next_method;\n";
2814 Result += "\tint method_count;\n";
2815 Result += "\tstruct _objc_method method_list[";
Douglas Gregorcd19b572009-04-23 01:02:12 +00002816 Result += utostr(NumMethods);
Steve Naroffc723eec2008-03-11 00:12:29 +00002817 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002818 Result += prefix;
2819 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2820 Result += "_METHODS_";
2821 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002822 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002823 Result += IsInstanceMethod ? "inst" : "cls";
2824 Result += "_meth\")))= ";
Douglas Gregorcd19b572009-04-23 01:02:12 +00002825 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002826
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002827 Result += "\t,{{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002828 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002829 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002830 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002831 Result += "\", \"";
2832 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002833 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002834 Result += MethodInternalNames[*MethodBegin];
2835 Result += "}\n";
2836 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2837 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002838 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002839 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002840 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002841 Result += "\", \"";
2842 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002843 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002844 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002845 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002846 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002847 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002848}
2849
Ted Kremenek42730c52008-01-07 19:49:32 +00002850/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002851void RewriteObjC::
2852RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2853 const char *prefix,
2854 const char *ClassName,
2855 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002856 static bool objc_protocol_methods = false;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002857 if (Protocols.empty()) return;
2858
2859 for (unsigned i = 0; i != Protocols.size(); i++) {
2860 ObjCProtocolDecl *PDecl = Protocols[i];
2861 // Output struct protocol_methods holder of method selector and type.
2862 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2863 /* struct protocol_methods {
2864 SEL _cmd;
2865 char *method_types;
2866 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002867 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002868 Result += "\nstruct protocol_methods {\n";
2869 Result += "\tSEL _cmd;\n";
2870 Result += "\tchar *method_types;\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002871 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002872
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002873 objc_protocol_methods = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002874 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002875 // Do not synthesize the protocol more than once.
2876 if (ObjCSynthesizedProtocols.count(PDecl))
2877 continue;
2878
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002879 if (PDecl->instmeth_begin(*Context) != PDecl->instmeth_end(*Context)) {
2880 unsigned NumMethods = std::distance(PDecl->instmeth_begin(*Context),
2881 PDecl->instmeth_end(*Context));
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002882 /* struct _objc_protocol_method_list {
2883 int protocol_method_count;
2884 struct protocol_methods protocols[];
2885 }
2886 */
2887 Result += "\nstatic struct {\n";
2888 Result += "\tint protocol_method_count;\n";
2889 Result += "\tstruct protocol_methods protocols[";
2890 Result += utostr(NumMethods);
2891 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002892 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002893 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2894 "{\n\t" + utostr(NumMethods) + "\n";
2895
2896 // Output instance methods declared in this protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002897 for (ObjCProtocolDecl::instmeth_iterator
2898 I = PDecl->instmeth_begin(*Context),
2899 E = PDecl->instmeth_end(*Context);
2900 I != E; ++I) {
2901 if (I == PDecl->instmeth_begin(*Context))
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002902 Result += "\t ,{{(SEL)\"";
2903 else
2904 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002905 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002906 std::string MethodTypeString;
2907 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2908 Result += "\", \"";
2909 Result += MethodTypeString;
2910 Result += "\"}\n";
2911 }
2912 Result += "\t }\n};\n";
2913 }
2914
2915 // Output class methods declared in this protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002916 unsigned NumMethods = std::distance(PDecl->classmeth_begin(*Context),
2917 PDecl->classmeth_end(*Context));
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002918 if (NumMethods > 0) {
2919 /* struct _objc_protocol_method_list {
2920 int protocol_method_count;
2921 struct protocol_methods protocols[];
2922 }
2923 */
2924 Result += "\nstatic struct {\n";
2925 Result += "\tint protocol_method_count;\n";
2926 Result += "\tstruct protocol_methods protocols[";
2927 Result += utostr(NumMethods);
2928 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002929 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002930 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2931 "{\n\t";
2932 Result += utostr(NumMethods);
2933 Result += "\n";
2934
2935 // Output instance methods declared in this protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002936 for (ObjCProtocolDecl::classmeth_iterator
2937 I = PDecl->classmeth_begin(*Context),
2938 E = PDecl->classmeth_end(*Context);
2939 I != E; ++I) {
2940 if (I == PDecl->classmeth_begin(*Context))
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002941 Result += "\t ,{{(SEL)\"";
2942 else
2943 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002944 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002945 std::string MethodTypeString;
2946 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2947 Result += "\", \"";
2948 Result += MethodTypeString;
2949 Result += "\"}\n";
2950 }
2951 Result += "\t }\n};\n";
2952 }
2953
2954 // Output:
2955 /* struct _objc_protocol {
2956 // Objective-C 1.0 extensions
2957 struct _objc_protocol_extension *isa;
2958 char *protocol_name;
2959 struct _objc_protocol **protocol_list;
2960 struct _objc_protocol_method_list *instance_methods;
2961 struct _objc_protocol_method_list *class_methods;
2962 };
Steve Naroff27429432008-03-12 01:06:30 +00002963 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002964 static bool objc_protocol = false;
2965 if (!objc_protocol) {
2966 Result += "\nstruct _objc_protocol {\n";
2967 Result += "\tstruct _objc_protocol_extension *isa;\n";
2968 Result += "\tchar *protocol_name;\n";
2969 Result += "\tstruct _objc_protocol **protocol_list;\n";
2970 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2971 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2972 Result += "};\n";
2973
2974 objc_protocol = true;
2975 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002976
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002977 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002978 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002979 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2980 "{\n\t0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00002981 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002982 Result += "\", 0, ";
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002983 if (PDecl->instmeth_begin(*Context) != PDecl->instmeth_end(*Context)) {
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002984 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002985 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002986 Result += ", ";
2987 }
2988 else
2989 Result += "0, ";
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002990 if (PDecl->classmeth_begin(*Context) != PDecl->classmeth_end(*Context)) {
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002991 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002992 Result += PDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002993 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002994 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002995 else
2996 Result += "0\n";
2997 Result += "};\n";
2998
2999 // Mark this protocol as having been generated.
3000 if (!ObjCSynthesizedProtocols.insert(PDecl))
3001 assert(false && "protocol already synthesized");
3002 }
3003 // Output the top lovel protocol meta-data for the class.
3004 /* struct _objc_protocol_list {
3005 struct _objc_protocol_list *next;
3006 int protocol_count;
3007 struct _objc_protocol *class_protocols[];
3008 }
3009 */
3010 Result += "\nstatic struct {\n";
3011 Result += "\tstruct _objc_protocol_list *next;\n";
3012 Result += "\tint protocol_count;\n";
3013 Result += "\tstruct _objc_protocol *class_protocols[";
3014 Result += utostr(Protocols.size());
3015 Result += "];\n} _OBJC_";
3016 Result += prefix;
3017 Result += "_PROTOCOLS_";
3018 Result += ClassName;
3019 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3020 "{\n\t0, ";
3021 Result += utostr(Protocols.size());
3022 Result += "\n";
3023
3024 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003025 Result += Protocols[0]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003026 Result += " \n";
3027
3028 for (unsigned i = 1; i != Protocols.size(); i++) {
3029 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003030 Result += Protocols[i]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003031 Result += "\n";
3032 }
3033 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003034}
3035
Ted Kremenek42730c52008-01-07 19:49:32 +00003036/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003037/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00003038void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003039 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003040 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003041 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003042 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003043 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3044 CDecl = CDecl->getNextClassCategory())
3045 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3046 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003047
Chris Lattner271d4c22008-11-24 05:29:24 +00003048 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00003049 FullCategoryName += '_';
Chris Lattner271d4c22008-11-24 05:29:24 +00003050 FullCategoryName += IDecl->getNameAsString();
Douglas Gregorcd19b572009-04-23 01:02:12 +00003051
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003052 // Build _objc_method_list for class's instance methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003053 llvm::SmallVector<ObjCMethodDecl *, 32>
3054 InstanceMethods(IDecl->instmeth_begin(*Context),
3055 IDecl->instmeth_end(*Context));
3056
3057 // If any of our property implementations have associated getters or
3058 // setters, produce metadata for them as well.
3059 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(*Context),
3060 PropEnd = IDecl->propimpl_end(*Context);
3061 Prop != PropEnd; ++Prop) {
3062 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3063 continue;
3064 if (!(*Prop)->getPropertyIvarDecl())
3065 continue;
3066 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3067 if (!PD)
3068 continue;
3069 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3070 InstanceMethods.push_back(Getter);
3071 if (PD->isReadOnly())
3072 continue;
3073 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3074 InstanceMethods.push_back(Setter);
3075 }
3076 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003077 true, "CATEGORY_", FullCategoryName.c_str(),
3078 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003079
3080 // Build _objc_method_list for class's class methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003081 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(*Context),
3082 IDecl->classmeth_end(*Context),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003083 false, "CATEGORY_", FullCategoryName.c_str(),
3084 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003085
3086 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00003087 // Null CDecl is case of a category implementation with no category interface
3088 if (CDecl)
Chris Lattner0be08822008-07-21 21:32:27 +00003089 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00003090 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003091
3092 /* struct _objc_category {
3093 char *category_name;
3094 char *class_name;
3095 struct _objc_method_list *instance_methods;
3096 struct _objc_method_list *class_methods;
3097 struct _objc_protocol_list *protocols;
3098 // Objective-C 1.0 extensions
3099 uint32_t size; // sizeof (struct _objc_category)
3100 struct _objc_property_list *instance_properties; // category's own
3101 // @property decl.
3102 };
3103 */
3104
3105 static bool objc_category = false;
3106 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003107 Result += "\nstruct _objc_category {\n";
3108 Result += "\tchar *category_name;\n";
3109 Result += "\tchar *class_name;\n";
3110 Result += "\tstruct _objc_method_list *instance_methods;\n";
3111 Result += "\tstruct _objc_method_list *class_methods;\n";
3112 Result += "\tstruct _objc_protocol_list *protocols;\n";
3113 Result += "\tunsigned int size;\n";
3114 Result += "\tstruct _objc_property_list *instance_properties;\n";
3115 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003116 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00003117 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003118 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3119 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00003120 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003121 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003122 Result += "\"\n\t, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003123 Result += ClassDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003124 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003125
Douglas Gregorcd19b572009-04-23 01:02:12 +00003126 if (IDecl->instmeth_begin(*Context) != IDecl->instmeth_end(*Context)) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003127 Result += "\t, (struct _objc_method_list *)"
3128 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3129 Result += FullCategoryName;
3130 Result += "\n";
3131 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003132 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003133 Result += "\t, 0\n";
Douglas Gregorcd19b572009-04-23 01:02:12 +00003134 if (IDecl->classmeth_begin(*Context) != IDecl->classmeth_end(*Context)) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003135 Result += "\t, (struct _objc_method_list *)"
3136 "&_OBJC_CATEGORY_CLASS_METHODS_";
3137 Result += FullCategoryName;
3138 Result += "\n";
3139 }
3140 else
3141 Result += "\t, 0\n";
3142
Chris Lattner179fd522009-02-20 18:18:36 +00003143 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003144 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3145 Result += FullCategoryName;
3146 Result += "\n";
3147 }
3148 else
3149 Result += "\t, 0\n";
3150 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003151}
3152
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003153/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3154/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00003155void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00003156 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003157 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00003158 if (ivar->isBitField()) {
3159 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3160 // place all bitfields at offset 0.
3161 Result += "0";
3162 } else {
3163 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003164 Result += IDecl->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003165 if (LangOpts.Microsoft)
3166 Result += "_IMPL";
3167 Result += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003168 Result += ivar->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003169 Result += ")";
3170 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003171}
3172
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003173//===----------------------------------------------------------------------===//
3174// Meta Data Emission
3175//===----------------------------------------------------------------------===//
3176
Steve Naroff44e81222008-04-14 22:03:09 +00003177void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003178 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003179 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003180
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003181 // Explictly declared @interface's are already synthesized.
Steve Naroff7333b492009-04-20 20:09:33 +00003182 if (CDecl->isImplicitInterfaceDecl()) {
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003183 // FIXME: Implementation of a class with no @interface (legacy) doese not
3184 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00003185 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003186 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003187
Chris Lattnerc7b06752007-12-12 07:56:42 +00003188 // Build _objc_ivar_list metadata for classes ivars if needed
Douglas Gregor087dbf32009-04-23 03:23:08 +00003189 unsigned NumIvars = !IDecl->ivar_empty(*Context)
3190 ? IDecl->ivar_size(*Context)
Chris Lattnerec4979b2008-03-16 21:08:55 +00003191 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003192 if (NumIvars > 0) {
3193 static bool objc_ivar = false;
3194 if (!objc_ivar) {
3195 /* struct _objc_ivar {
3196 char *ivar_name;
3197 char *ivar_type;
3198 int ivar_offset;
3199 };
3200 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003201 Result += "\nstruct _objc_ivar {\n";
3202 Result += "\tchar *ivar_name;\n";
3203 Result += "\tchar *ivar_type;\n";
3204 Result += "\tint ivar_offset;\n";
3205 Result += "};\n";
3206
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003207 objc_ivar = true;
3208 }
3209
Steve Naroffc723eec2008-03-11 00:12:29 +00003210 /* struct {
3211 int ivar_count;
3212 struct _objc_ivar ivar_list[nIvars];
3213 };
3214 */
3215 Result += "\nstatic struct {\n";
3216 Result += "\tint ivar_count;\n";
3217 Result += "\tstruct _objc_ivar ivar_list[";
3218 Result += utostr(NumIvars);
3219 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003220 Result += IDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003221 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003222 "{\n\t";
3223 Result += utostr(NumIvars);
3224 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003225
Ted Kremenek42730c52008-01-07 19:49:32 +00003226 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor087dbf32009-04-23 03:23:08 +00003227 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
3228 if (!IDecl->ivar_empty(*Context)) {
3229 for (ObjCImplementationDecl::ivar_iterator
3230 IV = IDecl->ivar_begin(*Context),
3231 IVEnd = IDecl->ivar_end(*Context);
3232 IV != IVEnd; ++IV)
3233 IVars.push_back(*IV);
3234 IVI = IVars.begin();
3235 IVE = IVars.end();
Chris Lattnerc7b06752007-12-12 07:56:42 +00003236 } else {
3237 IVI = CDecl->ivar_begin();
3238 IVE = CDecl->ivar_end();
3239 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003240 Result += "\t,{{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003241 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003242 Result += "\", \"";
3243 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00003244 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003245 Result += StrEncoding;
3246 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003247 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003248 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003249 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003250 Result += "\t ,{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003251 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003252 Result += "\", \"";
3253 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00003254 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003255 Result += StrEncoding;
3256 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003257 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003258 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003259 }
3260
3261 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003262 }
3263
3264 // Build _objc_method_list for class's instance methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003265 llvm::SmallVector<ObjCMethodDecl *, 32>
3266 InstanceMethods(IDecl->instmeth_begin(*Context),
3267 IDecl->instmeth_end(*Context));
3268
3269 // If any of our property implementations have associated getters or
3270 // setters, produce metadata for them as well.
3271 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(*Context),
3272 PropEnd = IDecl->propimpl_end(*Context);
3273 Prop != PropEnd; ++Prop) {
3274 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3275 continue;
3276 if (!(*Prop)->getPropertyIvarDecl())
3277 continue;
3278 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3279 if (!PD)
3280 continue;
3281 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3282 InstanceMethods.push_back(Getter);
3283 if (PD->isReadOnly())
3284 continue;
3285 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3286 InstanceMethods.push_back(Setter);
3287 }
3288 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003289 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003290
3291 // Build _objc_method_list for class's class methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003292 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(*Context),
3293 IDecl->classmeth_end(*Context),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003294 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003295
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003296 // Protocols referenced in class declaration?
Chris Lattner0be08822008-07-21 21:32:27 +00003297 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003298 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003299
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003300
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003301 // Declaration of class/meta-class metadata
3302 /* struct _objc_class {
3303 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003304 const char *super_class_name;
3305 char *name;
3306 long version;
3307 long info;
3308 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003309 struct _objc_ivar_list *ivars;
3310 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003311 struct objc_cache *cache;
3312 struct objc_protocol_list *protocols;
3313 const char *ivar_layout;
3314 struct _objc_class_ext *ext;
3315 };
3316 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003317 static bool objc_class = false;
3318 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003319 Result += "\nstruct _objc_class {\n";
3320 Result += "\tstruct _objc_class *isa;\n";
3321 Result += "\tconst char *super_class_name;\n";
3322 Result += "\tchar *name;\n";
3323 Result += "\tlong version;\n";
3324 Result += "\tlong info;\n";
3325 Result += "\tlong instance_size;\n";
3326 Result += "\tstruct _objc_ivar_list *ivars;\n";
3327 Result += "\tstruct _objc_method_list *methods;\n";
3328 Result += "\tstruct objc_cache *cache;\n";
3329 Result += "\tstruct _objc_protocol_list *protocols;\n";
3330 Result += "\tconst char *ivar_layout;\n";
3331 Result += "\tstruct _objc_class_ext *ext;\n";
3332 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003333 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003334 }
3335
3336 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003337 ObjCInterfaceDecl *RootClass = 0;
3338 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003339 while (SuperClass) {
3340 RootClass = SuperClass;
3341 SuperClass = SuperClass->getSuperClass();
3342 }
3343 SuperClass = CDecl->getSuperClass();
3344
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003345 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003346 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003347 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003348 "{\n\t(struct _objc_class *)\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003349 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003350 Result += "\"";
3351
3352 if (SuperClass) {
3353 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003354 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003355 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003356 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003357 Result += "\"";
3358 }
3359 else {
3360 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003361 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003362 Result += "\"";
3363 }
Ted Kremenek42730c52008-01-07 19:49:32 +00003364 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003365 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003366 Result += ", 0,2, sizeof(struct _objc_class), 0";
Douglas Gregorcd19b572009-04-23 01:02:12 +00003367 if (IDecl->classmeth_begin(*Context) != IDecl->classmeth_end(*Context)) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003368 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003369 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003370 Result += "\n";
3371 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003372 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003373 Result += ", 0\n";
Chris Lattner179fd522009-02-20 18:18:36 +00003374 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003375 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003376 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003377 Result += ",0,0\n";
3378 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003379 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003380 Result += "\t,0,0,0,0\n";
3381 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003382
3383 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003384 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003385 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003386 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003387 "{\n\t&_OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003388 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003389 if (SuperClass) {
3390 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003391 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003392 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003393 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003394 Result += "\"";
3395 }
3396 else {
3397 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003398 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003399 Result += "\"";
3400 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003401 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003402 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003403 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003404 Result += ",0";
3405 else {
3406 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003407 Result += ",sizeof(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003408 Result += CDecl->getNameAsString();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003409 if (LangOpts.Microsoft)
3410 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003411 Result += ")";
3412 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003413 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003414 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003415 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003416 Result += "\n\t";
3417 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003418 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003419 Result += ",0";
Douglas Gregorcd19b572009-04-23 01:02:12 +00003420 if (IDecl->instmeth_begin(*Context) != IDecl->instmeth_end(*Context)) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003421 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003422 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003423 Result += ", 0\n\t";
3424 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003425 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003426 Result += ",0,0";
Chris Lattner179fd522009-02-20 18:18:36 +00003427 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003428 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003429 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003430 Result += ", 0,0\n";
3431 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003432 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003433 Result += ",0,0,0\n";
3434 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003435}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003436
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003437/// RewriteImplementations - This routine rewrites all method implementations
3438/// and emits meta-data.
3439
Steve Naroff21658f62008-11-13 20:07:04 +00003440void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003441 int ClsDefCount = ClassImplementation.size();
3442 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003443
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003444 // Rewrite implemented methods
3445 for (int i = 0; i < ClsDefCount; i++)
3446 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003447
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003448 for (int i = 0; i < CatDefCount; i++)
3449 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Naroff21658f62008-11-13 20:07:04 +00003450}
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003451
Steve Naroff21658f62008-11-13 20:07:04 +00003452void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3453 int ClsDefCount = ClassImplementation.size();
3454 int CatDefCount = CategoryImplementation.size();
3455
Steve Naroff5bf10222008-05-07 21:23:49 +00003456 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003457 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003458 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003459 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003460 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003461
3462 // For each implemented category, write out all its meta data.
3463 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003464 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003465
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003466 // Write objc_symtab metadata
3467 /*
3468 struct _objc_symtab
3469 {
3470 long sel_ref_cnt;
3471 SEL *refs;
3472 short cls_def_cnt;
3473 short cat_def_cnt;
3474 void *defs[cls_def_cnt + cat_def_cnt];
3475 };
3476 */
3477
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003478 Result += "\nstruct _objc_symtab {\n";
3479 Result += "\tlong sel_ref_cnt;\n";
3480 Result += "\tSEL *refs;\n";
3481 Result += "\tshort cls_def_cnt;\n";
3482 Result += "\tshort cat_def_cnt;\n";
3483 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3484 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003485
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003486 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003487 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003488 Result += "\t0, 0, " + utostr(ClsDefCount)
3489 + ", " + utostr(CatDefCount) + "\n";
3490 for (int i = 0; i < ClsDefCount; i++) {
3491 Result += "\t,&_OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003492 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003493 Result += "\n";
3494 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003495
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003496 for (int i = 0; i < CatDefCount; i++) {
3497 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003498 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003499 Result += "_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003500 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003501 Result += "\n";
3502 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003503
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003504 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003505
3506 // Write objc_module metadata
3507
3508 /*
3509 struct _objc_module {
3510 long version;
3511 long size;
3512 const char *name;
3513 struct _objc_symtab *symtab;
3514 }
3515 */
3516
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003517 Result += "\nstruct _objc_module {\n";
3518 Result += "\tlong version;\n";
3519 Result += "\tlong size;\n";
3520 Result += "\tconst char *name;\n";
3521 Result += "\tstruct _objc_symtab *symtab;\n";
3522 Result += "};\n\n";
3523 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003524 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003525 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3526 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003527 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003528
3529 if (LangOpts.Microsoft) {
3530 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003531 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003532 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3533 Result += "&_OBJC_MODULES;\n";
3534 Result += "#pragma data_seg(pop)\n\n";
3535 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003536}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003537
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003538std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3539 const char *funcName,
3540 std::string Tag) {
3541 const FunctionType *AFT = CE->getFunctionType();
3542 QualType RT = AFT->getResultType();
3543 std::string StructRef = "struct " + Tag;
3544 std::string S = "static " + RT.getAsString() + " __" +
3545 funcName + "_" + "block_func_" + utostr(i);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003546
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003547 BlockDecl *BD = CE->getBlockDecl();
3548
Douglas Gregor4fa58902009-02-26 23:50:07 +00003549 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroff16478cf2009-02-02 17:19:26 +00003550 // No user-supplied arguments. Still need to pass in a pointer to the
3551 // block (to reference imported block decl refs).
3552 S += "(" + StructRef + " *__cself)";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003553 } else if (BD->param_empty()) {
3554 S += "(" + StructRef + " *__cself)";
3555 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003556 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003557 assert(FT && "SynthesizeBlockFunc: No function proto");
3558 S += '(';
3559 // first add the implicit argument.
3560 S += StructRef + " *__cself, ";
3561 std::string ParamStr;
3562 for (BlockDecl::param_iterator AI = BD->param_begin(),
3563 E = BD->param_end(); AI != E; ++AI) {
3564 if (AI != BD->param_begin()) S += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003565 ParamStr = (*AI)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003566 (*AI)->getType().getAsStringInternal(ParamStr);
3567 S += ParamStr;
3568 }
3569 if (FT->isVariadic()) {
3570 if (!BD->param_empty()) S += ", ";
3571 S += "...";
3572 }
3573 S += ')';
3574 }
3575 S += " {\n";
3576
3577 // Create local declarations to avoid rewriting all closure decl ref exprs.
3578 // First, emit a declaration for all "by ref" decls.
3579 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3580 E = BlockByRefDecls.end(); I != E; ++I) {
3581 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003582 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003583 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003584 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003585 }
3586 // Next, emit a declaration for all "by copy" declarations.
3587 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3588 E = BlockByCopyDecls.end(); I != E; ++I) {
3589 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003590 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003591 // Handle nested closure invocation. For example:
3592 //
3593 // void (^myImportedClosure)(void);
3594 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3595 //
3596 // void (^anotherClosure)(void);
3597 // anotherClosure = ^(void) {
3598 // myImportedClosure(); // import and invoke the closure
3599 // };
3600 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003601 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003602 S += "struct __block_impl *";
3603 else
3604 (*I)->getType().getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003605 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003606 }
3607 std::string RewrittenStr = RewrittenBlockExprs[CE];
3608 const char *cstr = RewrittenStr.c_str();
3609 while (*cstr++ != '{') ;
3610 S += cstr;
3611 S += "\n";
3612 return S;
3613}
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003614
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003615std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3616 const char *funcName,
3617 std::string Tag) {
3618 std::string StructRef = "struct " + Tag;
3619 std::string S = "static void __";
3620
3621 S += funcName;
3622 S += "_block_copy_" + utostr(i);
3623 S += "(" + StructRef;
3624 S += "*dst, " + StructRef;
3625 S += "*src) {";
3626 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3627 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003628 S += "_Block_object_assign((void*)&dst->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003629 S += (*I)->getNameAsString();
Steve Naroff1d56d9e2008-12-11 20:51:38 +00003630 S += ", (void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003631 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003632 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003633 }
3634 S += "\nstatic void __";
3635 S += funcName;
3636 S += "_block_dispose_" + utostr(i);
3637 S += "(" + StructRef;
3638 S += "*src) {";
3639 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3640 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003641 S += "_Block_object_dispose((void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003642 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003643 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003644 }
3645 S += "}\n";
3646 return S;
3647}
3648
3649std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3650 bool hasCopyDisposeHelpers) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003651 std::string S = "\nstruct " + Tag;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003652 std::string Constructor = " " + Tag;
3653
3654 S += " {\n struct __block_impl impl;\n";
3655
3656 if (hasCopyDisposeHelpers)
3657 S += " void *copy;\n void *dispose;\n";
3658
3659 Constructor += "(void *fp";
3660
3661 if (hasCopyDisposeHelpers)
3662 Constructor += ", void *copyHelp, void *disposeHelp";
3663
3664 if (BlockDeclRefs.size()) {
3665 // Output all "by copy" declarations.
3666 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3667 E = BlockByCopyDecls.end(); I != E; ++I) {
3668 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003669 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003670 std::string ArgName = "_" + FieldName;
3671 // Handle nested closure invocation. For example:
3672 //
3673 // void (^myImportedBlock)(void);
3674 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3675 //
3676 // void (^anotherBlock)(void);
3677 // anotherBlock = ^(void) {
3678 // myImportedBlock(); // import and invoke the closure
3679 // };
3680 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003681 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003682 S += "struct __block_impl *";
3683 Constructor += ", void *" + ArgName;
3684 } else {
3685 (*I)->getType().getAsStringInternal(FieldName);
3686 (*I)->getType().getAsStringInternal(ArgName);
3687 Constructor += ", " + ArgName;
3688 }
3689 S += FieldName + ";\n";
3690 }
3691 // Output all "by ref" declarations.
3692 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3693 E = BlockByRefDecls.end(); I != E; ++I) {
3694 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003695 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003696 std::string ArgName = "_" + FieldName;
3697 // Handle nested closure invocation. For example:
3698 //
3699 // void (^myImportedBlock)(void);
3700 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3701 //
3702 // void (^anotherBlock)(void);
3703 // anotherBlock = ^(void) {
3704 // myImportedBlock(); // import and invoke the closure
3705 // };
3706 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003707 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003708 S += "struct __block_impl *";
3709 Constructor += ", void *" + ArgName;
3710 } else {
3711 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3712 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3713 Constructor += ", " + ArgName;
3714 }
3715 S += FieldName + "; // by ref\n";
3716 }
3717 // Finish writing the constructor.
3718 // FIXME: handle NSConcreteGlobalBlock.
3719 Constructor += ", int flags=0) {\n";
3720 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3721 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3722
3723 if (hasCopyDisposeHelpers)
3724 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3725
3726 // Initialize all "by copy" arguments.
3727 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3728 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003729 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003730 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003731 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003732 Constructor += Name + " = (struct __block_impl *)_";
3733 else
3734 Constructor += Name + " = _";
3735 Constructor += Name + ";\n";
3736 }
3737 // Initialize all "by ref" arguments.
3738 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3739 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003740 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003741 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003742 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003743 Constructor += Name + " = (struct __block_impl *)_";
3744 else
3745 Constructor += Name + " = _";
3746 Constructor += Name + ";\n";
3747 }
3748 } else {
3749 // Finish writing the constructor.
3750 // FIXME: handle NSConcreteGlobalBlock.
3751 Constructor += ", int flags=0) {\n";
3752 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3753 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3754 if (hasCopyDisposeHelpers)
3755 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3756 }
3757 Constructor += " ";
3758 Constructor += "}\n";
3759 S += Constructor;
3760 S += "};\n";
3761 return S;
3762}
3763
3764void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3765 const char *FunName) {
3766 // Insert closures that were part of the function.
3767 for (unsigned i = 0; i < Blocks.size(); i++) {
3768
3769 CollectBlockDeclRefInfo(Blocks[i]);
3770
3771 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3772
3773 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3774 ImportedBlockDecls.size() > 0);
3775
3776 InsertText(FunLocStart, CI.c_str(), CI.size());
3777
3778 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3779
3780 InsertText(FunLocStart, CF.c_str(), CF.size());
3781
3782 if (ImportedBlockDecls.size()) {
3783 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3784 InsertText(FunLocStart, HF.c_str(), HF.size());
3785 }
3786
3787 BlockDeclRefs.clear();
3788 BlockByRefDecls.clear();
3789 BlockByCopyDecls.clear();
3790 BlockCallExprs.clear();
3791 ImportedBlockDecls.clear();
3792 }
3793 Blocks.clear();
3794 RewrittenBlockExprs.clear();
3795}
3796
3797void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3798 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003799 const char *FuncName = FD->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003800
3801 SynthesizeBlockLiterals(FunLocStart, FuncName);
3802}
3803
3804void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003805 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3806 //SourceLocation FunLocStart = MD->getLocStart();
3807 // FIXME: This hack works around a bug in Rewrite.InsertText().
3808 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner3a8f2942008-11-24 03:33:13 +00003809 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003810 // Convert colons to underscores.
3811 std::string::size_type loc = 0;
3812 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3813 FuncName.replace(loc, 1, "_");
3814
3815 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3816}
3817
3818void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3819 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3820 CI != E; ++CI)
3821 if (*CI) {
3822 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3823 GetBlockDeclRefExprs(CBE->getBody());
3824 else
3825 GetBlockDeclRefExprs(*CI);
3826 }
3827 // Handle specific things.
3828 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3829 // FIXME: Handle enums.
3830 if (!isa<FunctionDecl>(CDRE->getDecl()))
3831 BlockDeclRefs.push_back(CDRE);
3832 return;
3833}
3834
3835void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3836 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3837 CI != E; ++CI)
3838 if (*CI) {
3839 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3840 GetBlockCallExprs(CBE->getBody());
3841 else
3842 GetBlockCallExprs(*CI);
3843 }
3844
3845 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3846 if (CE->getCallee()->getType()->isBlockPointerType()) {
3847 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3848 }
3849 }
3850 return;
3851}
3852
Steve Naroff85eb17b2008-10-30 10:07:53 +00003853Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003854 // Navigate to relevant type information.
3855 const char *closureName = 0;
3856 const BlockPointerType *CPT = 0;
3857
3858 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003859 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003860 CPT = DRE->getType()->getAsBlockPointerType();
3861 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003862 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003863 CPT = CDRE->getType()->getAsBlockPointerType();
3864 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003865 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003866 CPT = MExpr->getType()->getAsBlockPointerType();
3867 } else {
3868 assert(1 && "RewriteBlockClass: Bad type");
3869 }
3870 assert(CPT && "RewriteBlockClass: Bad type");
3871 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3872 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00003873 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003874 // FTP will be null for closures that don't take arguments.
3875
Steve Naroff85eb17b2008-10-30 10:07:53 +00003876 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3877 SourceLocation(),
3878 &Context->Idents.get("__block_impl"));
3879 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003880
Steve Naroff85eb17b2008-10-30 10:07:53 +00003881 // Generate a funky cast.
3882 llvm::SmallVector<QualType, 8> ArgTypes;
3883
3884 // Push the block argument type.
3885 ArgTypes.push_back(PtrBlock);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003886 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003887 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff85eb17b2008-10-30 10:07:53 +00003888 E = FTP->arg_type_end(); I && (I != E); ++I) {
3889 QualType t = *I;
3890 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00003891 if (isTopLevelBlockPointerType(t)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003892 const BlockPointerType *BPT = t->getAsBlockPointerType();
3893 t = Context->getPointerType(BPT->getPointeeType());
3894 }
3895 ArgTypes.push_back(t);
3896 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003897 }
Steve Naroff85eb17b2008-10-30 10:07:53 +00003898 // Now do the pointer to function cast.
3899 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3900 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3901
3902 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003903
Ted Kremenek0c97e042009-02-07 01:47:29 +00003904 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3905 PtrBlock, SourceLocation(),
3906 SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003907 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003908 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3909 BlkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003910 //PE->dump();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003911
Douglas Gregor8acb7272008-12-11 16:49:14 +00003912 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3913 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003914 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek0c97e042009-02-07 01:47:29 +00003915 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3916 FD->getType());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003917
Ted Kremenek0c97e042009-02-07 01:47:29 +00003918 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3919 PtrToFuncCastType,
3920 SourceLocation(),
3921 SourceLocation());
3922 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003923
3924 llvm::SmallVector<Expr*, 8> BlkExprs;
3925 // Add the implicit argument.
3926 BlkExprs.push_back(BlkCast);
3927 // Add the user arguments.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003928 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3929 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003930 BlkExprs.push_back(*I);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003931 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00003932 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3933 BlkExprs.size(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00003934 Exp->getType(), SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003935 return CE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003936}
3937
3938void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003939 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3940 ReplaceStmt(Exp, BlockCall);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003941}
3942
3943void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3944 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003945 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroff16478cf2009-02-02 17:19:26 +00003946 Context->getPointerType(BDRE->getType()),
3947 SourceLocation());
3948 // Need parens to enforce precedence.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003949 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroff16478cf2009-02-02 17:19:26 +00003950 ReplaceStmt(BDRE, PE);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003951}
3952
Steve Naroff7f1412d2008-11-03 23:29:32 +00003953void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3954 SourceLocation LocStart = CE->getLParenLoc();
3955 SourceLocation LocEnd = CE->getRParenLoc();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003956
3957 // Need to avoid trying to rewrite synthesized casts.
3958 if (LocStart.isInvalid())
3959 return;
Steve Naroff1c53c022008-11-03 11:20:24 +00003960 // Need to avoid trying to rewrite casts contained in macros.
3961 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3962 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003963
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003964 const char *startBuf = SM->getCharacterData(LocStart);
3965 const char *endBuf = SM->getCharacterData(LocEnd);
3966
3967 // advance the location to startArgList.
3968 const char *argPtr = startBuf;
3969
3970 while (*argPtr++ && (argPtr < endBuf)) {
3971 switch (*argPtr) {
3972 case '^':
3973 // Replace the '^' with '*'.
3974 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3975 ReplaceText(LocStart, 1, "*", 1);
3976 break;
3977 }
3978 }
3979 return;
3980}
3981
3982void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3983 SourceLocation DeclLoc = FD->getLocation();
3984 unsigned parenCount = 0;
3985
3986 // We have 1 or more arguments that have closure pointers.
3987 const char *startBuf = SM->getCharacterData(DeclLoc);
3988 const char *startArgList = strchr(startBuf, '(');
3989
3990 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3991
3992 parenCount++;
3993 // advance the location to startArgList.
3994 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3995 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3996
3997 const char *argPtr = startArgList;
3998
3999 while (*argPtr++ && parenCount) {
4000 switch (*argPtr) {
4001 case '^':
4002 // Replace the '^' with '*'.
4003 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4004 ReplaceText(DeclLoc, 1, "*", 1);
4005 break;
4006 case '(':
4007 parenCount++;
4008 break;
4009 case ')':
4010 parenCount--;
4011 break;
4012 }
4013 }
4014 return;
4015}
4016
4017bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004018 const FunctionProtoType *FTP;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004019 const PointerType *PT = QT->getAsPointerType();
4020 if (PT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004021 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004022 } else {
4023 const BlockPointerType *BPT = QT->getAsBlockPointerType();
4024 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00004025 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004026 }
4027 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004028 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004029 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +00004030 if (isTopLevelBlockPointerType(*I))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004031 return true;
4032 }
4033 return false;
4034}
4035
Ted Kremenek0c97e042009-02-07 01:47:29 +00004036void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4037 const char *&RParen) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004038 const char *argPtr = strchr(Name, '(');
4039 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4040
4041 LParen = argPtr; // output the start.
4042 argPtr++; // skip past the left paren.
4043 unsigned parenCount = 1;
4044
4045 while (*argPtr && parenCount) {
4046 switch (*argPtr) {
4047 case '(': parenCount++; break;
4048 case ')': parenCount--; break;
4049 default: break;
4050 }
4051 if (parenCount) argPtr++;
4052 }
4053 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4054 RParen = argPtr; // output the end
4055}
4056
4057void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4058 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4059 RewriteBlockPointerFunctionArgs(FD);
4060 return;
4061 }
4062 // Handle Variables and Typedefs.
4063 SourceLocation DeclLoc = ND->getLocation();
4064 QualType DeclT;
4065 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4066 DeclT = VD->getType();
4067 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4068 DeclT = TDD->getUnderlyingType();
4069 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4070 DeclT = FD->getType();
4071 else
4072 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4073
4074 const char *startBuf = SM->getCharacterData(DeclLoc);
4075 const char *endBuf = startBuf;
4076 // scan backward (from the decl location) for the end of the previous decl.
4077 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4078 startBuf--;
4079
4080 // *startBuf != '^' if we are dealing with a pointer to function that
4081 // may take block argument types (which will be handled below).
4082 if (*startBuf == '^') {
4083 // Replace the '^' with '*', computing a negative offset.
4084 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4085 ReplaceText(DeclLoc, 1, "*", 1);
4086 }
4087 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4088 // Replace the '^' with '*' for arguments.
4089 DeclLoc = ND->getLocation();
4090 startBuf = SM->getCharacterData(DeclLoc);
4091 const char *argListBegin, *argListEnd;
4092 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4093 while (argListBegin < argListEnd) {
4094 if (*argListBegin == '^') {
4095 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4096 ReplaceText(CaretLoc, 1, "*", 1);
4097 }
4098 argListBegin++;
4099 }
4100 }
4101 return;
4102}
4103
4104void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4105 // Add initializers for any closure decl refs.
4106 GetBlockDeclRefExprs(Exp->getBody());
4107 if (BlockDeclRefs.size()) {
4108 // Unique all "by copy" declarations.
4109 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4110 if (!BlockDeclRefs[i]->isByRef())
4111 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4112 // Unique all "by ref" declarations.
4113 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4114 if (BlockDeclRefs[i]->isByRef()) {
4115 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4116 }
4117 // Find any imported blocks...they will need special attention.
4118 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff1d56d9e2008-12-11 20:51:38 +00004119 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroffe59c8b12008-11-13 17:40:07 +00004120 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004121 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4122 }
4123 }
4124}
4125
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004126FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4127 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004128 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004129 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor1f88aa72009-02-25 16:33:18 +00004130 ID, FType, FunctionDecl::Extern, false,
4131 false);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004132}
4133
Steve Naroff80c54752008-10-29 18:15:37 +00004134Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004135 Blocks.push_back(Exp);
4136
4137 CollectBlockDeclRefInfo(Exp);
4138 std::string FuncName;
4139
4140 if (CurFunctionDef)
Chris Lattner3a8f2942008-11-24 03:33:13 +00004141 FuncName = CurFunctionDef->getNameAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004142 else if (CurMethodDef) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00004143 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004144 // Convert colons to underscores.
4145 std::string::size_type loc = 0;
4146 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4147 FuncName.replace(loc, 1, "_");
Steve Naroff80c54752008-10-29 18:15:37 +00004148 } else if (GlobalVarDecl)
Chris Lattner271d4c22008-11-24 05:29:24 +00004149 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004150
4151 std::string BlockNumber = utostr(Blocks.size()-1);
4152
4153 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4154 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4155
4156 // Get a pointer to the function type so we can cast appropriately.
4157 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4158
4159 FunctionDecl *FD;
4160 Expr *NewRep;
4161
4162 // Simulate a contructor call...
4163 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004164 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004165
4166 llvm::SmallVector<Expr*, 4> InitExprs;
4167
Steve Naroffd0419d62008-10-29 21:23:59 +00004168 // Initialize the block function.
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004169 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004170 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4171 SourceLocation());
4172 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4173 Context->VoidPtrTy, SourceLocation(),
4174 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004175 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004176
4177 if (ImportedBlockDecls.size()) {
4178 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004179 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004180 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4181 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4182 Context->VoidPtrTy, SourceLocation(),
4183 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004184 InitExprs.push_back(castExpr);
4185
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004186 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004187 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004188 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4189 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4190 Context->VoidPtrTy, SourceLocation(),
4191 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004192 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004193 }
4194 // Add initializers for any closure decl refs.
4195 if (BlockDeclRefs.size()) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004196 Expr *Exp;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004197 // Output all "by copy" declarations.
4198 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4199 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004200 if (isObjCType((*I)->getType())) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004201 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004202 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004203 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffd896f4b2008-12-11 21:05:33 +00004204 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004205 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004206 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4207 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4208 Context->VoidPtrTy, SourceLocation(),
4209 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004210 } else {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004211 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004212 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004213 }
Steve Naroffd0419d62008-10-29 21:23:59 +00004214 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004215 }
4216 // Output all "by ref" declarations.
4217 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4218 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004219 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004220 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4221 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Naroffd0419d62008-10-29 21:23:59 +00004222 Context->getPointerType(Exp->getType()),
4223 SourceLocation());
Steve Naroff362c7562008-11-14 21:36:12 +00004224 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004225 }
4226 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00004227 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4228 FType, SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004229 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004230 Context->getPointerType(NewRep->getType()),
4231 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004232 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4233 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004234 BlockDeclRefs.clear();
4235 BlockByRefDecls.clear();
4236 BlockByCopyDecls.clear();
4237 ImportedBlockDecls.clear();
4238 return NewRep;
4239}
4240
4241//===----------------------------------------------------------------------===//
4242// Function Body / Expression rewriting
4243//===----------------------------------------------------------------------===//
4244
Steve Naroff0e948412008-12-04 16:24:46 +00004245// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4246// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4247// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4248// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4249// Since the rewriter isn't capable of rewriting rewritten code, it's important
4250// we get this right.
4251void RewriteObjC::CollectPropertySetters(Stmt *S) {
4252 // Perform a bottom up traversal of all children.
4253 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4254 CI != E; ++CI)
4255 if (*CI)
4256 CollectPropertySetters(*CI);
4257
4258 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4259 if (BinOp->isAssignmentOp()) {
4260 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4261 PropSetters[PRE] = BinOp;
4262 }
4263 }
4264}
4265
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004266Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4267 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4268 isa<DoStmt>(S) || isa<ForStmt>(S))
4269 Stmts.push_back(S);
4270 else if (isa<ObjCForCollectionStmt>(S)) {
4271 Stmts.push_back(S);
4272 ObjCBcLabelNo.push_back(++BcLabelCount);
4273 }
4274
4275 SourceRange OrigStmtRange = S->getSourceRange();
4276
4277 // Perform a bottom up rewrite of all children.
4278 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4279 CI != E; ++CI)
4280 if (*CI) {
4281 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4282 if (newStmt)
4283 *CI = newStmt;
4284 }
4285
4286 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4287 // Rewrite the block body in place.
4288 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4289
4290 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff80c54752008-10-29 18:15:37 +00004291 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4292 RewrittenBlockExprs[BE] = Str;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004293
4294 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4295 //blockTranscribed->dump();
Steve Naroff80c54752008-10-29 18:15:37 +00004296 ReplaceStmt(S, blockTranscribed);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004297 return blockTranscribed;
4298 }
4299 // Handle specific things.
4300 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4301 return RewriteAtEncode(AtEncode);
4302
4303 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4304 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4305
Steve Naroff0e948412008-12-04 16:24:46 +00004306 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4307 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4308 if (BinOp) {
4309 // Because the rewriter doesn't allow us to rewrite rewritten code,
4310 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffedb4bc92008-12-09 12:56:34 +00004311 DisableReplaceStmt = true;
4312 // Save the source range. Even if we disable the replacement, the
4313 // rewritten node will have been inserted into the tree. If the synthesized
4314 // node is at the 'end', the rewriter will fail. Consider this:
4315 // self.errorHandler = handler ? handler :
4316 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4317 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff0e948412008-12-04 16:24:46 +00004318 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffedb4bc92008-12-09 12:56:34 +00004319 DisableReplaceStmt = false;
Steve Naroff102c3f22008-12-04 23:50:32 +00004320 //
4321 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4322 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4323 // to see the original expression). Consider this example:
4324 //
4325 // Foo *obj1, *obj2;
4326 //
4327 // obj1.i = [obj2 rrrr];
4328 //
4329 // 'BinOp' for the previous expression looks like:
4330 //
4331 // (BinaryOperator 0x231ccf0 'int' '='
4332 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4333 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4334 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4335 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4336 //
4337 // 'newStmt' represents the rewritten message expression. For example:
4338 //
4339 // (CallExpr 0x231d300 'id':'struct objc_object *'
4340 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4341 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4342 // (CStyleCastExpr 0x231d220 'void *'
4343 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4344 //
4345 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4346 // can be used as the setter argument. ReplaceStmt() will still 'see'
4347 // the original RHS (since we haven't altered BinOp).
4348 //
4349 // This implies the Rewrite* routines can no longer delete the original
4350 // node. As a result, we now leak the original AST nodes.
4351 //
Steve Naroffedb4bc92008-12-09 12:56:34 +00004352 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff0e948412008-12-04 16:24:46 +00004353 } else {
4354 return RewritePropertyGetter(PropRefExpr);
Steve Narofff6ce8a12008-12-03 00:56:33 +00004355 }
4356 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004357 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4358 return RewriteAtSelector(AtSelector);
4359
4360 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4361 return RewriteObjCStringLiteral(AtString);
4362
4363 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff0e948412008-12-04 16:24:46 +00004364#if 0
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004365 // Before we rewrite it, put the original message expression in a comment.
4366 SourceLocation startLoc = MessExpr->getLocStart();
4367 SourceLocation endLoc = MessExpr->getLocEnd();
4368
4369 const char *startBuf = SM->getCharacterData(startLoc);
4370 const char *endBuf = SM->getCharacterData(endLoc);
4371
4372 std::string messString;
4373 messString += "// ";
4374 messString.append(startBuf, endBuf-startBuf+1);
4375 messString += "\n";
4376
4377 // FIXME: Missing definition of
4378 // InsertText(clang::SourceLocation, char const*, unsigned int).
4379 // InsertText(startLoc, messString.c_str(), messString.size());
4380 // Tried this, but it didn't work either...
4381 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff0e948412008-12-04 16:24:46 +00004382#endif
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004383 return RewriteMessageExpr(MessExpr);
4384 }
4385
4386 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4387 return RewriteObjCTryStmt(StmtTry);
4388
4389 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4390 return RewriteObjCSynchronizedStmt(StmtTry);
4391
4392 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4393 return RewriteObjCThrowStmt(StmtThrow);
4394
4395 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4396 return RewriteObjCProtocolExpr(ProtocolExp);
4397
4398 if (ObjCForCollectionStmt *StmtForCollection =
4399 dyn_cast<ObjCForCollectionStmt>(S))
4400 return RewriteObjCForCollectionStmt(StmtForCollection,
4401 OrigStmtRange.getEnd());
4402 if (BreakStmt *StmtBreakStmt =
4403 dyn_cast<BreakStmt>(S))
4404 return RewriteBreakStmt(StmtBreakStmt);
4405 if (ContinueStmt *StmtContinueStmt =
4406 dyn_cast<ContinueStmt>(S))
4407 return RewriteContinueStmt(StmtContinueStmt);
4408
4409 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4410 // and cast exprs.
4411 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4412 // FIXME: What we're doing here is modifying the type-specifier that
4413 // precedes the first Decl. In the future the DeclGroup should have
4414 // a separate type-specifier that we can rewrite.
4415 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4416
4417 // Blocks rewrite rules.
4418 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4419 DI != DE; ++DI) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00004420 Decl *SD = *DI;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004421 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004422 if (isTopLevelBlockPointerType(ND->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004423 RewriteBlockPointerDecl(ND);
4424 else if (ND->getType()->isFunctionPointerType())
4425 CheckFunctionPointerDecl(ND->getType(), ND);
4426 }
4427 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004428 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004429 RewriteBlockPointerDecl(TD);
4430 else if (TD->getUnderlyingType()->isFunctionPointerType())
4431 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4432 }
4433 }
4434 }
4435
4436 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4437 RewriteObjCQualifiedInterfaceTypes(CE);
4438
4439 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4440 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4441 assert(!Stmts.empty() && "Statement stack is empty");
4442 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4443 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4444 && "Statement stack mismatch");
4445 Stmts.pop_back();
4446 }
4447 // Handle blocks rewriting.
4448 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4449 if (BDRE->isByRef())
4450 RewriteBlockDeclRefExpr(BDRE);
4451 }
4452 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00004453 if (CE->getCallee()->getType()->isBlockPointerType()) {
4454 Stmt *BlockCall = SynthesizeBlockCall(CE);
4455 ReplaceStmt(S, BlockCall);
4456 return BlockCall;
4457 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004458 }
Steve Naroff7f1412d2008-11-03 23:29:32 +00004459 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004460 RewriteCastExpr(CE);
4461 }
4462#if 0
4463 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004464 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004465 // Get the new text.
4466 std::string SStr;
4467 llvm::raw_string_ostream Buf(SStr);
4468 Replacement->printPretty(Buf);
4469 const std::string &Str = Buf.str();
4470
4471 printf("CAST = %s\n", &Str[0]);
4472 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4473 delete S;
4474 return Replacement;
4475 }
4476#endif
4477 // Return this stmt unmodified.
4478 return S;
4479}
4480
4481/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4482/// main file of the input.
4483void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4484 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffee8d4972008-12-17 00:20:22 +00004485 if (FD->isOverloadedOperator())
4486 return;
4487
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004488 // Since function prototypes don't have ParmDecl's, we check the function
4489 // prototype. This enables us to rewrite function declarations and
4490 // definitions using the same code.
Douglas Gregor4fa58902009-02-26 23:50:07 +00004491 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004492
Sebastian Redlbc9ef252009-04-26 20:35:05 +00004493 // FIXME: If this should support Obj-C++, support CXXTryStmt
4494 if (CompoundStmt *Body = FD->getCompoundBody(*Context)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004495 CurFunctionDef = FD;
Steve Naroff0e948412008-12-04 16:24:46 +00004496 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004497 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004498 Body =
4499 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4500 FD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004501 CurrentBody = 0;
4502 if (PropParentMap) {
4503 delete PropParentMap;
4504 PropParentMap = 0;
4505 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004506 // This synthesizes and inserts the block "impl" struct, invoke function,
4507 // and any copy/dispose helper functions.
4508 InsertBlockLiteralsWithinFunction(FD);
4509 CurFunctionDef = 0;
4510 }
4511 return;
4512 }
4513 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Ted Kremenek30916072009-03-12 18:33:24 +00004514 if (CompoundStmt *Body = MD->getBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004515 CurMethodDef = MD;
Steve Naroff0e948412008-12-04 16:24:46 +00004516 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004517 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004518 Body =
4519 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4520 MD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004521 CurrentBody = 0;
4522 if (PropParentMap) {
4523 delete PropParentMap;
4524 PropParentMap = 0;
4525 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004526 InsertBlockLiteralsWithinMethod(MD);
4527 CurMethodDef = 0;
4528 }
4529 }
4530 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4531 ClassImplementation.push_back(CI);
4532 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4533 CategoryImplementation.push_back(CI);
4534 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4535 RewriteForwardClassDecl(CD);
4536 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4537 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffd896f4b2008-12-11 21:05:33 +00004538 if (isTopLevelBlockPointerType(VD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004539 RewriteBlockPointerDecl(VD);
Steve Naroff80c54752008-10-29 18:15:37 +00004540 else if (VD->getType()->isFunctionPointerType()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004541 CheckFunctionPointerDecl(VD->getType(), VD);
4542 if (VD->getInit()) {
Steve Naroff7f1412d2008-11-03 23:29:32 +00004543 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004544 RewriteCastExpr(CE);
4545 }
4546 }
4547 }
Steve Naroff80c54752008-10-29 18:15:37 +00004548 if (VD->getInit()) {
4549 GlobalVarDecl = VD;
Steve Naroff0e948412008-12-04 16:24:46 +00004550 CollectPropertySetters(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004551 CurrentBody = VD->getInit();
Steve Naroff80c54752008-10-29 18:15:37 +00004552 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004553 CurrentBody = 0;
4554 if (PropParentMap) {
4555 delete PropParentMap;
4556 PropParentMap = 0;
4557 }
Douglas Gregor24afd4a2008-11-17 14:58:09 +00004558 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004559 VD->getNameAsCString());
Steve Naroff80c54752008-10-29 18:15:37 +00004560 GlobalVarDecl = 0;
4561
4562 // This is needed for blocks.
Steve Naroff7f1412d2008-11-03 23:29:32 +00004563 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff80c54752008-10-29 18:15:37 +00004564 RewriteCastExpr(CE);
4565 }
4566 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004567 return;
4568 }
4569 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004570 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004571 RewriteBlockPointerDecl(TD);
4572 else if (TD->getUnderlyingType()->isFunctionPointerType())
4573 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4574 return;
4575 }
4576 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4577 if (RD->isDefinition()) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004578 for (RecordDecl::field_iterator i = RD->field_begin(*Context),
4579 e = RD->field_end(*Context); i != e; ++i) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004580 FieldDecl *FD = *i;
Steve Naroffd896f4b2008-12-11 21:05:33 +00004581 if (isTopLevelBlockPointerType(FD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004582 RewriteBlockPointerDecl(FD);
4583 }
4584 }
4585 return;
4586 }
4587 // Nothing yet.
4588}
4589
Chris Lattner2a594d02009-03-28 04:11:33 +00004590void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004591 // Get the top-level buffer that this corresponds to.
4592
4593 // Rewrite tabs if we care.
4594 //RewriteTabs();
4595
4596 if (Diags.hasErrorOccurred())
4597 return;
4598
4599 // Create the output file.
4600
4601 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4602 llvm::raw_ostream *OutFile;
4603 if (OutFileName == "-") {
4604 OutFile = &llvm::outs();
4605 } else if (!OutFileName.empty()) {
4606 std::string Err;
Steve Naroff08299f82009-02-03 20:39:18 +00004607 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(),
4608 // set binary mode (critical for Windoze)
4609 true,
4610 Err);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004611 OwnedStream.reset(OutFile);
4612 } else if (InFileName == "-") {
4613 OutFile = &llvm::outs();
4614 } else {
4615 llvm::sys::Path Path(InFileName);
4616 Path.eraseSuffix();
4617 Path.appendSuffix("cpp");
4618 std::string Err;
Steve Naroff08299f82009-02-03 20:39:18 +00004619 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(),
4620 // set binary mode (critical for Windoze)
4621 true,
4622 Err);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004623 OwnedStream.reset(OutFile);
4624 }
4625
4626 RewriteInclude();
4627
Chris Lattnerf4f776a2009-01-17 06:22:33 +00004628 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004629 Preamble.c_str(), Preamble.size(), false);
4630
Steve Naroff901d8fd2008-11-14 14:10:01 +00004631 if (ClassImplementation.size() || CategoryImplementation.size())
4632 RewriteImplementations();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004633
4634 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4635 // we are done.
4636 if (const RewriteBuffer *RewriteBuf =
4637 Rewrite.getRewriteBufferFor(MainFileID)) {
4638 //printf("Changed:\n");
4639 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4640 } else {
4641 fprintf(stderr, "No changes\n");
4642 }
Steve Naroff21658f62008-11-13 20:07:04 +00004643
Steve Naroff901d8fd2008-11-14 14:10:01 +00004644 if (ClassImplementation.size() || CategoryImplementation.size()) {
4645 // Rewrite Objective-c meta data*
4646 std::string ResultStr;
4647 SynthesizeMetaDataIntoBuffer(ResultStr);
4648 // Emit metadata.
4649 *OutFile << ResultStr;
4650 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004651 OutFile->flush();
4652}
4653