blob: 394e6b7c66d0c40577cde2986dd3fd189a021baf [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 Naroff450d2fc2009-04-29 16:37:50 +000061 // Remember all the @protocol(<expr>) expressions.
62 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Steve Naroffe9780582007-10-23 23:50:29 +000063
Steve Naroff47e7fa22008-03-15 00:55:56 +000064 unsigned NumObjCStringLiterals;
65
Steve Naroffe9780582007-10-23 23:50:29 +000066 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000067 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000068 FunctionDecl *MsgSendStretFunctionDecl;
69 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000070 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000071 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000072 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000073 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000074 FunctionDecl *CFStringFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000075 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000076
Steve Naroff0add5d22007-11-03 11:27:19 +000077 // ObjC string constant support.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000078 VarDecl *ConstantStringClassReference;
Steve Naroff0add5d22007-11-03 11:27:19 +000079 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000080
Fariborz Jahanian22277422008-01-16 00:09:11 +000081 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000082 int BcLabelCount;
83
Steve Naroff764c1ae2007-11-15 10:28:18 +000084 // Needed for super.
Steve Naroff38a9e3f2008-10-27 17:20:55 +000085 ObjCMethodDecl *CurMethodDef;
Steve Naroff764c1ae2007-11-15 10:28:18 +000086 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000087 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000088
Steve Naroff450d2fc2009-04-29 16:37:50 +000089 TypeDecl *ProtocolTypeDecl;
90 QualType getProtocolType();
91
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000092 // Needed for header files being rewritten
93 bool IsHeader;
94
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000095 std::string InFileName;
Eli Friedmana9c310842009-05-18 22:20:00 +000096 llvm::raw_ostream* OutFile;
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000097
Steve Narofffef037c2008-03-27 22:29:16 +000098 std::string Preamble;
Steve Naroff38a9e3f2008-10-27 17:20:55 +000099
100 // Block expressions.
101 llvm::SmallVector<BlockExpr *, 32> Blocks;
102 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
103 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Narofffef037c2008-03-27 22:29:16 +0000104
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000105 // Block related declarations.
106 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
107 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
108 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
109
110 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
111
Steve Naroff0e948412008-12-04 16:24:46 +0000112 // This maps a property to it's assignment statement.
113 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Narofffbed6802008-12-08 16:43:47 +0000114 // This maps a property to it's synthesied message expression.
115 // This allows us to rewrite chained getters (e.g. o.a.b.c).
116 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
117
Steve Naroff102c3f22008-12-04 23:50:32 +0000118 // This maps an original source AST to it's rewritten form. This allows
119 // us to avoid rewriting the same node twice (which is very uncommon).
120 // This is needed to support some of the exotic property rewriting.
121 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff6ce8a12008-12-03 00:56:33 +0000122
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000123 FunctionDecl *CurFunctionDef;
Steve Naroff80c54752008-10-29 18:15:37 +0000124 VarDecl *GlobalVarDecl;
125
Steve Naroffedb4bc92008-12-09 12:56:34 +0000126 bool DisableReplaceStmt;
127
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000128 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +0000129 public:
Ted Kremenek79b50cb2008-05-31 20:11:04 +0000130 virtual void Initialize(ASTContext &context);
131
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000132 // Top Level Driver code.
Chris Lattnera17991f2009-03-29 16:50:03 +0000133 virtual void HandleTopLevelDecl(DeclGroupRef D) {
134 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
135 HandleTopLevelSingleDecl(*I);
136 }
137 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000138 void HandleDeclInMainFile(Decl *D);
Eli Friedmana9c310842009-05-18 22:20:00 +0000139 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000140 Diagnostic &D, const LangOptions &LOpts);
Ted Kremenekcab0b0c2008-08-08 04:15:52 +0000141
142 ~RewriteObjC() {}
143
Chris Lattner2a594d02009-03-28 04:11:33 +0000144 virtual void HandleTranslationUnit(ASTContext &C);
Chris Lattnerb1548372008-01-31 19:37:57 +0000145
146 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff102c3f22008-12-04 23:50:32 +0000147 Stmt *ReplacingStmt = ReplacedNodes[Old];
148
149 if (ReplacingStmt)
150 return; // We can't rewrite the same node twice.
Chris Lattnerb1548372008-01-31 19:37:57 +0000151
Steve Naroffedb4bc92008-12-09 12:56:34 +0000152 if (DisableReplaceStmt)
153 return; // Used when rewriting the assignment of a property setter.
154
Steve Naroff102c3f22008-12-04 23:50:32 +0000155 // If replacement succeeded or warning disabled return with no warning.
156 if (!Rewrite.ReplaceStmt(Old, New)) {
157 ReplacedNodes[Old] = New;
158 return;
159 }
160 if (SilenceRewriteMacroWarning)
161 return;
Chris Lattner6948ae62008-11-18 07:04:44 +0000162 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
163 << Old->getSourceRange();
Chris Lattnerb1548372008-01-31 19:37:57 +0000164 }
Steve Naroffedb4bc92008-12-09 12:56:34 +0000165
166 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
167 // Measaure the old text.
168 int Size = Rewrite.getRangeSize(SrcRange);
169 if (Size == -1) {
170 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
171 << Old->getSourceRange();
172 return;
173 }
174 // Get the new text.
175 std::string SStr;
176 llvm::raw_string_ostream S(SStr);
177 New->printPretty(S);
178 const std::string &Str = S.str();
179
180 // If replacement succeeded or warning disabled return with no warning.
181 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
182 ReplacedNodes[Old] = New;
183 return;
184 }
185 if (SilenceRewriteMacroWarning)
186 return;
187 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
188 << Old->getSourceRange();
189 }
190
Steve Narofffef037c2008-03-27 22:29:16 +0000191 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
192 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000193 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000194 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000195 SilenceRewriteMacroWarning)
196 return;
197
198 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
199 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000200
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000201 void RemoveText(SourceLocation Loc, unsigned StrLen) {
202 // If removal succeeded or warning disabled return with no warning.
203 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
204 return;
205
206 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
207 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000208
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000209 void ReplaceText(SourceLocation Start, unsigned OrigLength,
210 const char *NewStr, unsigned NewLength) {
211 // If removal succeeded or warning disabled return with no warning.
212 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
213 SilenceRewriteMacroWarning)
214 return;
215
216 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
217 }
218
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000219 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000220 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000221 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000222 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000223 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffea6610f2008-12-02 17:36:43 +0000224 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
225 ObjCImplementationDecl *IMD,
226 ObjCCategoryImplDecl *CID);
Ted Kremenek42730c52008-01-07 19:49:32 +0000227 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000228 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000229 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
230 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
231 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
232 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
233 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff56af2002009-01-11 01:06:09 +0000234 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000235 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000236 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000237 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000238 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000239 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000240 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000241 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000242 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000243
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000244 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000245 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff0e948412008-12-04 16:24:46 +0000246 void CollectPropertySetters(Stmt *S);
247
Steve Narofffbed6802008-12-08 16:43:47 +0000248 Stmt *CurrentBody;
249 ParentMap *PropParentMap; // created lazily.
250
Chris Lattner0021f452007-10-24 16:57:36 +0000251 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000252 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff0e948412008-12-04 16:24:46 +0000253 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffedb4bc92008-12-09 12:56:34 +0000254 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
255 SourceRange SrcRange);
Steve Naroff296b74f2007-11-05 14:50:49 +0000256 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000257 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000258 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000259 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff43964fb2008-12-05 17:03:39 +0000260 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000261 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000262 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000263 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
264 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
265 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000266 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
267 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000268 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
269 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000270 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000271 Stmt *RewriteBreakStmt(BreakStmt *S);
272 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000273 void SynthCountByEnumWithState(std::string &buf);
274
Steve Naroff02a82aa2007-10-30 23:14:51 +0000275 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000276 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000277 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000278 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000279 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000280 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000281 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000282 void SynthSelGetUidFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000283 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000284
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000285 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000286 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000287 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000288
Ted Kremenek42730c52008-01-07 19:49:32 +0000289 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000290 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000291
Douglas Gregorcd19b572009-04-23 01:02:12 +0000292 template<typename MethodIterator>
293 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
294 MethodIterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000295 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000296 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000297 const char *ClassName,
298 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000299
Steve Naroff450d2fc2009-04-29 16:37:50 +0000300 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
301 const char *prefix,
302 const char *ClassName,
303 std::string &Result);
304 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
305 const char *prefix,
306 const char *ClassName,
307 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000308 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000309 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000310 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
311 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000312 std::string &Result);
Steve Naroff21658f62008-11-13 20:07:04 +0000313 void RewriteImplementations();
314 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000315
316 // Block rewriting.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000317 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000318 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
319
320 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
321 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
322
Steve Naroff80c54752008-10-29 18:15:37 +0000323 // Block specific rewrite rules.
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000324 void RewriteBlockCall(CallExpr *Exp);
325 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroff450d2fc2009-04-29 16:37:50 +0000326 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000327 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
328
329 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
330 const char *funcName, std::string Tag);
331 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
332 const char *funcName, std::string Tag);
333 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
334 bool hasCopyDisposeHelpers);
Steve Naroff85eb17b2008-10-30 10:07:53 +0000335 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000336 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
337 const char *FunName);
338
339 void CollectBlockDeclRefInfo(BlockExpr *Exp);
340 void GetBlockCallExprs(Stmt *S);
341 void GetBlockDeclRefExprs(Stmt *S);
342
343 // We avoid calling Type::isBlockPointerType(), since it operates on the
344 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000345 bool isTopLevelBlockPointerType(QualType T) {
346 return isa<BlockPointerType>(T);
347 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000348
349 // FIXME: This predicate seems like it would be useful to add to ASTContext.
350 bool isObjCType(QualType T) {
351 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
352 return false;
353
354 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
355
356 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
357 OCT == Context->getCanonicalType(Context->getObjCClassType()))
358 return true;
359
360 if (const PointerType *PT = OCT->getAsPointerType()) {
361 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
362 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
363 return true;
364 }
365 return false;
366 }
367 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek0c97e042009-02-07 01:47:29 +0000368 void GetExtentOfArgList(const char *Name, const char *&LParen,
369 const char *&RParen);
Steve Naroff7f1412d2008-11-03 23:29:32 +0000370 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +0000371
372 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff80c54752008-10-29 18:15:37 +0000373 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Steve Naroff450d2fc2009-04-29 16:37:50 +0000374
375 void QuoteDoublequotes(std::string &From, std::string &To) {
376 for(unsigned i = 0; i < From.length(); i++) {
377 if (From[i] == '"')
378 To += "\\\"";
379 else
380 To += From[i];
381 }
382 }
Chris Lattnerb429ae42007-10-11 00:43:27 +0000383 };
384}
385
Douglas Gregor4fa58902009-02-26 23:50:07 +0000386void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000387 NamedDecl *D) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000388 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
389 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000390 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +0000391 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000392 // All the args are checked/rewritten. Don't call twice!
393 RewriteBlockPointerDecl(D);
394 break;
395 }
396 }
397}
398
399void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
400 const PointerType *PT = funcType->getAsPointerType();
401 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor4fa58902009-02-26 23:50:07 +0000402 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000403}
404
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000405static bool IsHeaderFile(const std::string &Filename) {
406 std::string::size_type DotPos = Filename.rfind('.');
407
408 if (DotPos == std::string::npos) {
409 // no file extension
410 return false;
411 }
412
413 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
414 // C header: .h
415 // C++ header: .hh or .H;
416 return Ext == "h" || Ext == "hh" || Ext == "H";
417}
418
Eli Friedmana9c310842009-05-18 22:20:00 +0000419RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000420 Diagnostic &D, const LangOptions &LOpts)
Eli Friedmana9c310842009-05-18 22:20:00 +0000421 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS) {
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000422 IsHeader = IsHeaderFile(inFile);
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000423 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
424 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff43964fb2008-12-05 17:03:39 +0000425 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000426 "rewriter doesn't support user-specified control flow semantics "
427 "for @try/@finally (code may not execute properly)");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000428}
429
Eli Friedman848763f2009-05-18 22:29:17 +0000430ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
431 llvm::raw_ostream* OS,
432 Diagnostic &Diags,
433 const LangOptions &LOpts) {
Eli Friedmana9c310842009-05-18 22:20:00 +0000434 return new RewriteObjC(InFile, OS, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000435}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000436
Steve Naroff44e81222008-04-14 22:03:09 +0000437void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000438 Context = &context;
439 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000440 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000441 MsgSendFunctionDecl = 0;
442 MsgSendSuperFunctionDecl = 0;
443 MsgSendStretFunctionDecl = 0;
444 MsgSendSuperStretFunctionDecl = 0;
445 MsgSendFpretFunctionDecl = 0;
446 GetClassFunctionDecl = 0;
447 GetMetaClassFunctionDecl = 0;
448 SelGetUidFunctionDecl = 0;
449 CFStringFunctionDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000450 ConstantStringClassReference = 0;
451 NSStringRecord = 0;
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000452 CurMethodDef = 0;
453 CurFunctionDef = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000454 GlobalVarDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000455 SuperStructDecl = 0;
Steve Naroff450d2fc2009-04-29 16:37:50 +0000456 ProtocolTypeDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000457 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000458 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000459 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000460 NumObjCStringLiterals = 0;
Steve Naroffbad6f3b2008-12-08 20:01:41 +0000461 PropParentMap = 0;
462 CurrentBody = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000463 DisableReplaceStmt = false;
464
Chris Lattner12499682008-01-31 19:38:44 +0000465 // Get the ID and start/end of the main file.
466 MainFileID = SM->getMainFileID();
467 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
468 MainFileStart = MainBuf->getBufferStart();
469 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000470
Chris Lattnere1be6022009-04-14 23:22:57 +0000471 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Steve Naroffde0da102008-03-10 23:16:54 +0000472
Chris Lattner12499682008-01-31 19:38:44 +0000473 // declaring objc_selector outside the parameter list removes a silly
474 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000475 if (IsHeader)
Steve Naroff08299f82009-02-03 20:39:18 +0000476 Preamble = "#pragma once\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000477 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff12673622008-12-23 20:11:22 +0000478 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Narofffef037c2008-03-27 22:29:16 +0000479 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000480 if (LangOpts.Microsoft) {
481 // Add a constructor for creating temporary objects.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000482 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
483 ": ";
Steve Narofffef037c2008-03-27 22:29:16 +0000484 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000485 }
Steve Narofffef037c2008-03-27 22:29:16 +0000486 Preamble += "};\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000487 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
488 Preamble += "typedef struct objc_object Protocol;\n";
489 Preamble += "#define _REWRITER_typedef_Protocol\n";
490 Preamble += "#endif\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000491 if (LangOpts.Microsoft) {
492 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
493 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
494 } else
495 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
496 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000497 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000498 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000499 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000500 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000501 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000502 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000503 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000504 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000505 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000506 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000507 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000508 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000509 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000510 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
511 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
512 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
513 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
514 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000515 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000516 // @synchronized hooks.
Steve Naroff1b208d72008-12-08 17:30:33 +0000517 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
518 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
519 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000520 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
521 Preamble += "struct __objcFastEnumerationState {\n\t";
522 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000523 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000524 Preamble += "unsigned long *mutationsPtr;\n\t";
525 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000526 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000527 Preamble += "#define __FASTENUMERATIONSTATE\n";
528 Preamble += "#endif\n";
529 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
530 Preamble += "struct __NSConstantStringImpl {\n";
531 Preamble += " int *isa;\n";
532 Preamble += " int flags;\n";
533 Preamble += " char *str;\n";
534 Preamble += " long length;\n";
535 Preamble += "};\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000536 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
537 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
538 Preamble += "#else\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000539 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000540 Preamble += "#endif\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000541 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
542 Preamble += "#endif\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000543 // Blocks preamble.
544 Preamble += "#ifndef BLOCK_IMPL\n";
545 Preamble += "#define BLOCK_IMPL\n";
546 Preamble += "struct __block_impl {\n";
547 Preamble += " void *isa;\n";
548 Preamble += " int Flags;\n";
549 Preamble += " int Size;\n";
550 Preamble += " void *FuncPtr;\n";
551 Preamble += "};\n";
Steve Naroff44fe1e32008-12-16 15:50:30 +0000552 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
553 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
554 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
555 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
556 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000557 Preamble += "#endif\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000558 if (LangOpts.Microsoft) {
Steve Naroff1b208d72008-12-08 17:30:33 +0000559 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
560 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000561 Preamble += "#define __attribute__(X)\n";
562 }
Chris Lattner12499682008-01-31 19:38:44 +0000563}
564
565
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000566//===----------------------------------------------------------------------===//
567// Top Level Driver Code
568//===----------------------------------------------------------------------===//
569
Chris Lattnera17991f2009-03-29 16:50:03 +0000570void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000571 // Two cases: either the decl could be in the main file, or it could be in a
572 // #included file. If the former, rewrite it now. If the later, check to see
573 // if we rewrote the #include/#import.
574 SourceLocation Loc = D->getLocation();
Chris Lattner18c8dc02009-01-16 07:36:28 +0000575 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000576
577 // If this is for a builtin, ignore it.
578 if (Loc.isInvalid()) return;
579
Steve Naroffe9780582007-10-23 23:50:29 +0000580 // Look for built-in declarations that we need to refer during the rewrite.
581 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000582 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000583 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000584 // declared in <Foundation/NSString.h>
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000585 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000586 ConstantStringClassReference = FVD;
587 return;
588 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000589 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000590 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000591 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000592 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000593 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000594 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000595 } else if (ObjCForwardProtocolDecl *FP =
596 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000597 RewriteForwardProtocolDecl(FP);
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000598 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
599 // Recurse into linkage specifications
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000600 for (DeclContext::decl_iterator DI = LSD->decls_begin(*Context),
601 DIEnd = LSD->decls_end(*Context);
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000602 DI != DIEnd; ++DI)
Chris Lattnera17991f2009-03-29 16:50:03 +0000603 HandleTopLevelSingleDecl(*DI);
Steve Naroffe9780582007-10-23 23:50:29 +0000604 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000605 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000606 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000607 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000608}
609
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000610//===----------------------------------------------------------------------===//
611// Syntactic (non-AST) Rewriting Code
612//===----------------------------------------------------------------------===//
613
Steve Naroff44e81222008-04-14 22:03:09 +0000614void RewriteObjC::RewriteInclude() {
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000615 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000616 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
617 const char *MainBufStart = MainBuf.first;
618 const char *MainBufEnd = MainBuf.second;
619 size_t ImportLen = strlen("import");
620 size_t IncludeLen = strlen("include");
621
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000622 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000623 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
624 if (*BufPtr == '#') {
625 if (++BufPtr == MainBufEnd)
626 return;
627 while (*BufPtr == ' ' || *BufPtr == '\t')
628 if (++BufPtr == MainBufEnd)
629 return;
630 if (!strncmp(BufPtr, "import", ImportLen)) {
631 // replace import with include
632 SourceLocation ImportLoc =
633 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000634 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000635 BufPtr += ImportLen;
636 }
637 }
638 }
Chris Lattner74db1682007-10-16 21:07:07 +0000639}
640
Steve Naroff44e81222008-04-14 22:03:09 +0000641void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000642 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
643 const char *MainBufStart = MainBuf.first;
644 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000645
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000646 // Loop over the whole file, looking for tabs.
647 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
648 if (*BufPtr != '\t')
649 continue;
650
651 // Okay, we found a tab. This tab will turn into at least one character,
652 // but it depends on which 'virtual column' it is in. Compute that now.
653 unsigned VCol = 0;
654 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
655 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
656 ++VCol;
657
658 // Okay, now that we know the virtual column, we know how many spaces to
659 // insert. We assume 8-character tab-stops.
660 unsigned Spaces = 8-(VCol & 7);
661
662 // Get the location of the tab.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000663 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
664 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000665
666 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000667 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000668 }
Chris Lattner569faa62007-10-11 18:38:32 +0000669}
670
Steve Naroff121ed222008-12-02 15:48:25 +0000671static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
672 ObjCIvarDecl *OID) {
673 std::string S;
674 S = "((struct ";
675 S += ClassDecl->getIdentifier()->getName();
676 S += "_IMPL *)self)->";
677 S += OID->getNameAsCString();
678 return S;
679}
680
Steve Naroffea6610f2008-12-02 17:36:43 +0000681void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
682 ObjCImplementationDecl *IMD,
683 ObjCCategoryImplDecl *CID) {
Steve Naroff110be842008-12-01 20:33:01 +0000684 SourceLocation startLoc = PID->getLocStart();
685 InsertText(startLoc, "// ", 3);
Steve Naroff121ed222008-12-02 15:48:25 +0000686 const char *startBuf = SM->getCharacterData(startLoc);
687 assert((*startBuf == '@') && "bogus @synthesize location");
688 const char *semiBuf = strchr(startBuf, ';');
689 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek0c97e042009-02-07 01:47:29 +0000690 SourceLocation onePastSemiLoc =
691 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff121ed222008-12-02 15:48:25 +0000692
693 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
694 return; // FIXME: is this correct?
695
696 // Generate the 'getter' function.
Steve Naroff121ed222008-12-02 15:48:25 +0000697 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff121ed222008-12-02 15:48:25 +0000698 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff121ed222008-12-02 15:48:25 +0000699 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000700
701 if (!OID)
702 return;
703
704 std::string Getr;
705 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
706 Getr += "{ ";
707 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000708 // FIXME: deal with code generation implications for various property
709 // attributes (copy, retain, nonatomic).
710 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000711 Getr += "return " + getIvarAccessString(ClassDecl, OID);
712 Getr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000713 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff121ed222008-12-02 15:48:25 +0000714 if (PD->isReadOnly())
715 return;
716
717 // Generate the 'setter' function.
718 std::string Setr;
719 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff121ed222008-12-02 15:48:25 +0000720 Setr += "{ ";
Steve Naroff1e7b7962008-12-02 16:05:55 +0000721 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000722 // FIXME: deal with code generation implications for various property
723 // attributes (copy, retain, nonatomic).
Steve Narofff6ce8a12008-12-03 00:56:33 +0000724 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000725 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff20f67392008-12-11 19:29:16 +0000726 Setr += PD->getNameAsCString();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000727 Setr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000728 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroff110be842008-12-01 20:33:01 +0000729}
Chris Lattner569faa62007-10-11 18:38:32 +0000730
Steve Naroff44e81222008-04-14 22:03:09 +0000731void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000732 // Get the start location and compute the semi location.
733 SourceLocation startLoc = ClassDecl->getLocation();
734 const char *startBuf = SM->getCharacterData(startLoc);
735 const char *semiPtr = strchr(startBuf, ';');
736
737 // Translate to typedef's that forward reference structs with the same name
738 // as the class. As a convenience, we include the original declaration
739 // as a comment.
740 std::string typedefString;
741 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000742 typedefString.append(startBuf, semiPtr-startBuf+1);
743 typedefString += "\n";
Chris Lattner6a028742009-02-20 18:04:31 +0000744 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
745 I != E; ++I) {
746 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff2aeae312007-11-09 12:50:28 +0000747 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000748 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000749 typedefString += "\n";
750 typedefString += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000751 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000752 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000753 typedefString += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000754 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000755 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000756 }
757
758 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000759 ReplaceText(startLoc, semiPtr-startBuf+1,
760 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000761}
762
Steve Naroff44e81222008-04-14 22:03:09 +0000763void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000764 SourceLocation LocStart = Method->getLocStart();
765 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000766
Chris Lattner2d89c562009-02-04 01:06:56 +0000767 if (SM->getInstantiationLineNumber(LocEnd) >
768 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff99f50fe2008-10-21 13:37:27 +0000769 InsertText(LocStart, "#if 0\n", 6);
770 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000771 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000772 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000773 }
774}
775
Steve Naroff56af2002009-01-11 01:06:09 +0000776void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000777{
Steve Naroff56af2002009-01-11 01:06:09 +0000778 SourceLocation Loc = prop->getLocation();
779
780 ReplaceText(Loc, 0, "// ", 3);
781
782 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000783}
784
Steve Naroff44e81222008-04-14 22:03:09 +0000785void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000786 SourceLocation LocStart = CatDecl->getLocStart();
787
788 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000789 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000790
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000791 for (ObjCCategoryDecl::instmeth_iterator
792 I = CatDecl->instmeth_begin(*Context),
793 E = CatDecl->instmeth_end(*Context);
794 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000795 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000796 for (ObjCCategoryDecl::classmeth_iterator
797 I = CatDecl->classmeth_begin(*Context),
798 E = CatDecl->classmeth_end(*Context);
799 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000800 RewriteMethodDeclaration(*I);
801
Steve Naroff667f1682007-10-30 13:30:57 +0000802 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000803 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000804}
805
Steve Naroff44e81222008-04-14 22:03:09 +0000806void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000807 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000808
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000809 SourceLocation LocStart = PDecl->getLocStart();
810
811 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000812 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000813
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000814 for (ObjCProtocolDecl::instmeth_iterator
815 I = PDecl->instmeth_begin(*Context),
816 E = PDecl->instmeth_end(*Context);
817 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000818 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000819 for (ObjCProtocolDecl::classmeth_iterator
820 I = PDecl->classmeth_begin(*Context),
821 E = PDecl->classmeth_end(*Context);
822 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000823 RewriteMethodDeclaration(*I);
824
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000825 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000826 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000827 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000828
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000829 // Must comment out @optional/@required
830 const char *startBuf = SM->getCharacterData(LocStart);
831 const char *endBuf = SM->getCharacterData(LocEnd);
832 for (const char *p = startBuf; p < endBuf; p++) {
833 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
834 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000835 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000836 ReplaceText(OptionalLoc, strlen("@optional"),
837 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000838
839 }
840 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
841 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000842 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000843 ReplaceText(OptionalLoc, strlen("@required"),
844 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000845
846 }
847 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000848}
849
Steve Naroff44e81222008-04-14 22:03:09 +0000850void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000851 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000852 if (LocStart.isInvalid())
853 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000854 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000855 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000856}
857
Steve Naroff44e81222008-04-14 22:03:09 +0000858void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000859 std::string &ResultStr) {
Steve Naroff6449c6c2008-10-30 12:09:33 +0000860 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff91044cf2008-07-16 14:40:40 +0000861 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000862 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000863 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000864 ResultStr += "id";
Steve Naroff20f67392008-12-11 19:29:16 +0000865 else if (OMD->getResultType()->isFunctionPointerType() ||
866 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000867 // needs special handling, since pointer-to-functions have special
868 // syntax (where a decaration models use).
869 QualType retType = OMD->getResultType();
Steve Naroff20f67392008-12-11 19:29:16 +0000870 QualType PointeeTy;
871 if (const PointerType* PT = retType->getAsPointerType())
872 PointeeTy = PT->getPointeeType();
873 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
874 PointeeTy = BPT->getPointeeType();
875 if ((FPRetType = PointeeTy->getAsFunctionType())) {
876 ResultStr += FPRetType->getResultType().getAsString();
877 ResultStr += "(*";
Steve Naroff91044cf2008-07-16 14:40:40 +0000878 }
879 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000880 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000881 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000882
883 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000884 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000885
Douglas Gregor5d764842009-01-09 17:18:27 +0000886 if (OMD->isInstanceMethod())
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000887 NameStr += "_I_";
888 else
889 NameStr += "_C_";
890
Chris Lattner271d4c22008-11-24 05:29:24 +0000891 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000892 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000893
Ted Kremenek42730c52008-01-07 19:49:32 +0000894 if (ObjCCategoryImplDecl *CID =
Steve Naroff438be772009-01-08 19:41:02 +0000895 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000896 NameStr += CID->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000897 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000898 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000899 // Append selector names, replacing ':' with '_'
Chris Lattner3a8f2942008-11-24 03:33:13 +0000900 {
901 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000902 int len = selString.size();
903 for (int i = 0; i < len; i++)
904 if (selString[i] == ':')
905 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000906 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000907 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000908 // Remember this name for metadata emission
909 MethodInternalNames[OMD] = NameStr;
910 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000911
912 // Rewrite arguments
913 ResultStr += "(";
914
915 // invisible arguments
Douglas Gregor5d764842009-01-09 17:18:27 +0000916 if (OMD->isInstanceMethod()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000917 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000918 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000919 if (!LangOpts.Microsoft) {
920 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
921 ResultStr += "struct ";
922 }
923 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattner271d4c22008-11-24 05:29:24 +0000924 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +0000925 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000926 }
927 else
Steve Naroff450d2fc2009-04-29 16:37:50 +0000928 ResultStr += Context->getObjCClassType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000929
930 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000931 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000932 ResultStr += " _cmd";
933
934 // Method arguments.
Chris Lattner5c6b2c62009-02-20 18:43:26 +0000935 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
936 E = OMD->param_end(); PI != E; ++PI) {
937 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000938 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000939 if (PDecl->getType()->isObjCQualifiedIdType()) {
940 ResultStr += "id ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000941 ResultStr += PDecl->getNameAsString();
Steve Naroff133dfda2008-04-18 21:13:19 +0000942 } else {
Chris Lattner271d4c22008-11-24 05:29:24 +0000943 std::string Name = PDecl->getNameAsString();
Steve Naroffd896f4b2008-12-11 21:05:33 +0000944 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff4e2ae512008-10-30 14:45:29 +0000945 // Make sure we convert "t (^)(...)" to "t (*)(...)".
946 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
947 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
948 } else
949 PDecl->getType().getAsStringInternal(Name);
Steve Naroff133dfda2008-04-18 21:13:19 +0000950 ResultStr += Name;
951 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000952 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000953 if (OMD->isVariadic())
954 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000955 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000956
Steve Naroff91044cf2008-07-16 14:40:40 +0000957 if (FPRetType) {
958 ResultStr += ")"; // close the precedence "scope" for "*".
959
960 // Now, emit the argument types (if any).
Douglas Gregor4fa58902009-02-26 23:50:07 +0000961 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000962 ResultStr += "(";
963 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
964 if (i) ResultStr += ", ";
965 std::string ParamStr = FT->getArgType(i).getAsString();
966 ResultStr += ParamStr;
967 }
968 if (FT->isVariadic()) {
969 if (FT->getNumArgs()) ResultStr += ", ";
970 ResultStr += "...";
971 }
972 ResultStr += ")";
973 } else {
974 ResultStr += "()";
975 }
976 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000977}
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000978void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000979 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
980 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000981
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000982 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000983 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000984 else
Chris Lattner6216f292008-01-31 19:42:41 +0000985 InsertText(CID->getLocStart(), "// ", 3);
Steve Naroff21658f62008-11-13 20:07:04 +0000986
Ted Kremenek42730c52008-01-07 19:49:32 +0000987 for (ObjCCategoryImplDecl::instmeth_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +0000988 I = IMD ? IMD->instmeth_begin(*Context) : CID->instmeth_begin(*Context),
989 E = IMD ? IMD->instmeth_end(*Context) : CID->instmeth_end(*Context);
990 I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000991 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000992 ObjCMethodDecl *OMD = *I;
993 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000994 SourceLocation LocStart = OMD->getLocStart();
Sebastian Redlbc9ef252009-04-26 20:35:05 +0000995 SourceLocation LocEnd = OMD->getCompoundBody(*Context)->getLocStart();
996
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000997 const char *startBuf = SM->getCharacterData(LocStart);
998 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000999 ReplaceText(LocStart, endBuf-startBuf,
1000 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001001 }
1002
Ted Kremenek42730c52008-01-07 19:49:32 +00001003 for (ObjCCategoryImplDecl::classmeth_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +00001004 I = IMD ? IMD->classmeth_begin(*Context) : CID->classmeth_begin(*Context),
1005 E = IMD ? IMD->classmeth_end(*Context) : CID->classmeth_end(*Context);
1006 I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001007 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +00001008 ObjCMethodDecl *OMD = *I;
1009 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001010 SourceLocation LocStart = OMD->getLocStart();
Sebastian Redlbc9ef252009-04-26 20:35:05 +00001011 SourceLocation LocEnd = OMD->getCompoundBody(*Context)->getLocStart();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001012
1013 const char *startBuf = SM->getCharacterData(LocStart);
1014 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001015 ReplaceText(LocStart, endBuf-startBuf,
1016 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001017 }
Steve Naroff110be842008-12-01 20:33:01 +00001018 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +00001019 I = IMD ? IMD->propimpl_begin(*Context) : CID->propimpl_begin(*Context),
1020 E = IMD ? IMD->propimpl_end(*Context) : CID->propimpl_end(*Context);
1021 I != E; ++I) {
Steve Naroffea6610f2008-12-02 17:36:43 +00001022 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroff110be842008-12-01 20:33:01 +00001023 }
1024
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001025 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +00001026 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001027 else
Chris Lattner6216f292008-01-31 19:42:41 +00001028 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001029}
1030
Steve Naroff44e81222008-04-14 22:03:09 +00001031void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +00001032 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +00001033 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +00001034 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +00001035 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001036 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001037 ResultStr += "\n";
1038 ResultStr += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001039 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001040 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +00001041 ResultStr += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +00001042 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001043 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +00001044 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00001045 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +00001046 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001047 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +00001048
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001049 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(*Context),
1050 E = ClassDecl->prop_end(*Context); I != E; ++I)
Steve Naroff56af2002009-01-11 01:06:09 +00001051 RewriteProperty(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001052 for (ObjCInterfaceDecl::instmeth_iterator
1053 I = ClassDecl->instmeth_begin(*Context),
1054 E = ClassDecl->instmeth_end(*Context);
1055 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +00001056 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001057 for (ObjCInterfaceDecl::classmeth_iterator
1058 I = ClassDecl->classmeth_begin(*Context),
1059 E = ClassDecl->classmeth_end(*Context);
1060 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +00001061 RewriteMethodDeclaration(*I);
1062
Steve Naroff1ccf4632007-10-30 03:43:13 +00001063 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001064 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +00001065}
1066
Steve Naroffedb4bc92008-12-09 12:56:34 +00001067Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1068 SourceRange SrcRange) {
Steve Naroff0e948412008-12-04 16:24:46 +00001069 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1070 // This allows us to reuse all the fun and games in SynthMessageExpr().
1071 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1072 ObjCMessageExpr *MsgExpr;
1073 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1074 llvm::SmallVector<Expr *, 1> ExprVec;
1075 ExprVec.push_back(newStmt);
1076
Steve Narofffbed6802008-12-08 16:43:47 +00001077 Stmt *Receiver = PropRefExpr->getBase();
1078 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1079 if (PRE && PropGetters[PRE]) {
1080 // This allows us to handle chain/nested property getters.
1081 Receiver = PropGetters[PRE];
1082 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001083 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff0e948412008-12-04 16:24:46 +00001084 PDecl->getSetterName(), PDecl->getType(),
1085 PDecl->getSetterMethodDecl(),
1086 SourceLocation(), SourceLocation(),
1087 &ExprVec[0], 1);
1088 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1089
1090 // Now do the actual rewrite.
Steve Naroffedb4bc92008-12-09 12:56:34 +00001091 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroff478f7382008-12-10 14:53:27 +00001092 //delete BinOp;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001093 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1094 // to things that stay around.
1095 Context->Deallocate(MsgExpr);
Steve Naroff0e948412008-12-04 16:24:46 +00001096 return ReplacingStmt;
Steve Narofff6ce8a12008-12-03 00:56:33 +00001097}
1098
Steve Naroff0e948412008-12-04 16:24:46 +00001099Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff6ce8a12008-12-03 00:56:33 +00001100 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1101 // This allows us to reuse all the fun and games in SynthMessageExpr().
1102 ObjCMessageExpr *MsgExpr;
1103 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1104
Steve Narofffbed6802008-12-08 16:43:47 +00001105 Stmt *Receiver = PropRefExpr->getBase();
1106
1107 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1108 if (PRE && PropGetters[PRE]) {
1109 // This allows us to handle chain/nested property getters.
1110 Receiver = PropGetters[PRE];
1111 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001112 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Narofff6ce8a12008-12-03 00:56:33 +00001113 PDecl->getGetterName(), PDecl->getType(),
1114 PDecl->getGetterMethodDecl(),
1115 SourceLocation(), SourceLocation(),
1116 0, 0);
1117
Steve Naroff102c3f22008-12-04 23:50:32 +00001118 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001119
1120 if (!PropParentMap)
1121 PropParentMap = new ParentMap(CurrentBody);
1122
1123 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1124 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1125 // We stash away the ReplacingStmt since actually doing the
1126 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1127 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001128 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1129 // to things that stay around.
1130 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001131 return PropRefExpr; // return the original...
1132 } else {
1133 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001134 // delete PropRefExpr; elsewhere...
1135 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1136 // to things that stay around.
1137 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001138 return ReplacingStmt;
1139 }
Steve Narofff6ce8a12008-12-03 00:56:33 +00001140}
1141
Chris Lattner343c82b2008-05-23 20:40:52 +00001142Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1143 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001144 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001145 if (CurMethodDef) {
Steve Naroff60dfb6b2008-03-12 00:25:36 +00001146 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001147 ObjCInterfaceType *iFaceDecl =
1148 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffa9636222008-05-08 17:52:16 +00001149 // lookup which class implements the instance variable.
1150 ObjCInterfaceDecl *clsDeclared = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001151 iFaceDecl->getDecl()->lookupInstanceVariable(*Context,
1152 D->getIdentifier(),
1153 clsDeclared);
Steve Naroffa9636222008-05-08 17:52:16 +00001154 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1155
1156 // Synthesize an explicit cast to gain access to the ivar.
1157 std::string RecName = clsDeclared->getIdentifier()->getName();
1158 RecName += "_IMPL";
1159 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001160 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001161 SourceLocation(), II);
Steve Naroffa9636222008-05-08 17:52:16 +00001162 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1163 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek0c97e042009-02-07 01:47:29 +00001164 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1165 castT,SourceLocation(),
1166 SourceLocation());
Steve Naroffa9636222008-05-08 17:52:16 +00001167 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001168 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1169 IV->getBase()->getLocEnd(),
1170 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +00001171 if (IV->isFreeIvar() &&
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001172 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001173 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1174 IV->getLocation(),
1175 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +00001176 ReplaceStmt(IV, ME);
Steve Naroff102c3f22008-12-04 23:50:32 +00001177 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffa9636222008-05-08 17:52:16 +00001178 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +00001179 }
Chris Lattner343c82b2008-05-23 20:40:52 +00001180
1181 ReplaceStmt(IV->getBase(), PE);
1182 // Cannot delete IV->getBase(), since PE points to it.
1183 // Replace the old base with the cast. This is important when doing
1184 // embedded rewrites. For example, [newInv->_container addObject:0].
1185 IV->setBase(PE);
1186 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +00001187 }
Steve Naroffe6155362008-04-18 21:55:08 +00001188 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +00001189 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1190
1191 // Explicit ivar refs need to have a cast inserted.
1192 // FIXME: consider sharing some of this code with the code above.
1193 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +00001194 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001195 // lookup which class implements the instance variable.
1196 ObjCInterfaceDecl *clsDeclared = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001197 iFaceDecl->getDecl()->lookupInstanceVariable(*Context,
1198 D->getIdentifier(),
1199 clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001200 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1201
1202 // Synthesize an explicit cast to gain access to the ivar.
1203 std::string RecName = clsDeclared->getIdentifier()->getName();
1204 RecName += "_IMPL";
1205 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001206 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001207 SourceLocation(), II);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001208 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1209 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek0c97e042009-02-07 01:47:29 +00001210 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1211 castT, SourceLocation(),
1212 SourceLocation());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001213 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001214 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner3cca6612008-05-28 16:38:23 +00001215 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001216 ReplaceStmt(IV->getBase(), PE);
1217 // Cannot delete IV->getBase(), since PE points to it.
1218 // Replace the old base with the cast. This is important when doing
1219 // embedded rewrites. For example, [newInv->_container addObject:0].
1220 IV->setBase(PE);
1221 return IV;
1222 }
Steve Naroff292b7b92007-11-15 11:33:00 +00001223 }
Steve Naroffe6155362008-04-18 21:55:08 +00001224 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +00001225}
1226
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001227/// SynthCountByEnumWithState - To print:
1228/// ((unsigned int (*)
1229/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1230/// (void *)objc_msgSend)((id)l_collection,
1231/// sel_registerName(
1232/// "countByEnumeratingWithState:objects:count:"),
1233/// &enumState,
1234/// (id *)items, (unsigned int)16)
1235///
Steve Naroff44e81222008-04-14 22:03:09 +00001236void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001237 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1238 "id *, unsigned int))(void *)objc_msgSend)";
1239 buf += "\n\t\t";
1240 buf += "((id)l_collection,\n\t\t";
1241 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1242 buf += "\n\t\t";
1243 buf += "&enumState, "
1244 "(id *)items, (unsigned int)16)";
1245}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001246
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001247/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1248/// statement to exit to its outer synthesized loop.
1249///
Steve Naroff44e81222008-04-14 22:03:09 +00001250Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001251 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1252 return S;
1253 // replace break with goto __break_label
1254 std::string buf;
1255
1256 SourceLocation startLoc = S->getLocStart();
1257 buf = "goto __break_label_";
1258 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001259 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001260
1261 return 0;
1262}
1263
1264/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1265/// statement to continue with its inner synthesized loop.
1266///
Steve Naroff44e81222008-04-14 22:03:09 +00001267Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001268 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1269 return S;
1270 // replace continue with goto __continue_label
1271 std::string buf;
1272
1273 SourceLocation startLoc = S->getLocStart();
1274 buf = "goto __continue_label_";
1275 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001276 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001277
1278 return 0;
1279}
1280
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001281/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001282/// It rewrites:
1283/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001284
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001285/// Into:
1286/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001287/// type elem;
1288/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001289/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001290/// id l_collection = (id)collection;
1291/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1292/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001293/// if (limit) {
1294/// unsigned long startMutations = *enumState.mutationsPtr;
1295/// do {
1296/// unsigned long counter = 0;
1297/// do {
1298/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001299/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001300/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001301/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001302/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001303/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001304/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1305/// objects:items count:16]);
1306/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001307/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001308/// }
1309/// else
1310/// elem = nil;
1311/// }
1312///
Steve Naroff44e81222008-04-14 22:03:09 +00001313Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001314 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001315 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1316 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1317 "ObjCForCollectionStmt Statement stack mismatch");
1318 assert(!ObjCBcLabelNo.empty() &&
1319 "ObjCForCollectionStmt - Label No stack empty");
1320
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001321 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001322 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001323 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001324 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001325 std::string buf;
1326 buf = "\n{\n\t";
1327 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1328 // type elem;
Chris Lattner4a9a85e2009-03-28 06:33:19 +00001329 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001330 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001331 elementTypeAsString = ElementType.getAsString();
1332 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001333 buf += " ";
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001334 elementName = D->getNameAsCString();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001335 buf += elementName;
1336 buf += ";\n\t";
1337 }
Chris Lattner690c2872008-04-08 05:52:18 +00001338 else {
1339 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001340 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001341 elementTypeAsString
1342 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001343 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001344
1345 // struct __objcFastEnumerationState enumState = { 0 };
1346 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1347 // id items[16];
1348 buf += "id items[16];\n\t";
1349 // id l_collection = (id)
1350 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001351 // Find start location of 'collection' the hard way!
1352 const char *startCollectionBuf = startBuf;
1353 startCollectionBuf += 3; // skip 'for'
1354 startCollectionBuf = strchr(startCollectionBuf, '(');
1355 startCollectionBuf++; // skip '('
1356 // find 'in' and skip it.
1357 while (*startCollectionBuf != ' ' ||
1358 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1359 (*(startCollectionBuf+3) != ' ' &&
1360 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1361 startCollectionBuf++;
1362 startCollectionBuf += 3;
1363
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001364 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001365 ReplaceText(startLoc, startCollectionBuf - startBuf,
1366 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001367 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001368 SourceLocation rightParenLoc = S->getRParenLoc();
1369 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1370 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001371 buf = ";\n\t";
1372
1373 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1374 // objects:items count:16];
1375 // which is synthesized into:
1376 // unsigned int limit =
1377 // ((unsigned int (*)
1378 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1379 // (void *)objc_msgSend)((id)l_collection,
1380 // sel_registerName(
1381 // "countByEnumeratingWithState:objects:count:"),
1382 // (struct __objcFastEnumerationState *)&state,
1383 // (id *)items, (unsigned int)16);
1384 buf += "unsigned long limit =\n\t\t";
1385 SynthCountByEnumWithState(buf);
1386 buf += ";\n\t";
1387 /// if (limit) {
1388 /// unsigned long startMutations = *enumState.mutationsPtr;
1389 /// do {
1390 /// unsigned long counter = 0;
1391 /// do {
1392 /// if (startMutations != *enumState.mutationsPtr)
1393 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001394 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001395 buf += "if (limit) {\n\t";
1396 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1397 buf += "do {\n\t\t";
1398 buf += "unsigned long counter = 0;\n\t\t";
1399 buf += "do {\n\t\t\t";
1400 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1401 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1402 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001403 buf += " = (";
1404 buf += elementTypeAsString;
1405 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001406 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001407 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001408
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001409 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001410 /// } while (counter < limit);
1411 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1412 /// objects:items count:16]);
1413 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001414 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001415 /// }
1416 /// else
1417 /// elem = nil;
1418 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001419 ///
1420 buf = ";\n\t";
1421 buf += "__continue_label_";
1422 buf += utostr(ObjCBcLabelNo.back());
1423 buf += ": ;";
1424 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001425 buf += "} while (counter < limit);\n\t";
1426 buf += "} while (limit = ";
1427 SynthCountByEnumWithState(buf);
1428 buf += ");\n\t";
1429 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001430 buf += " = ((id)0);\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001431 buf += "__break_label_";
1432 buf += utostr(ObjCBcLabelNo.back());
1433 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001434 buf += "}\n\t";
1435 buf += "else\n\t\t";
1436 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001437 buf += " = ((id)0);\n";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001438 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001439
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001440 // Insert all these *after* the statement body.
Sebastian Redlbc9ef252009-04-26 20:35:05 +00001441 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff5f238fe2008-07-21 18:26:02 +00001442 if (isa<CompoundStmt>(S->getBody())) {
1443 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1444 InsertText(endBodyLoc, buf.c_str(), buf.size());
1445 } else {
1446 /* Need to treat single statements specially. For example:
1447 *
1448 * for (A *a in b) if (stuff()) break;
1449 * for (A *a in b) xxxyy;
1450 *
1451 * The following code simply scans ahead to the semi to find the actual end.
1452 */
1453 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1454 const char *semiBuf = strchr(stmtBuf, ';');
1455 assert(semiBuf && "Can't find ';'");
1456 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1457 InsertText(endBodyLoc, buf.c_str(), buf.size());
1458 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001459 Stmts.pop_back();
1460 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001461 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001462}
1463
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001464/// RewriteObjCSynchronizedStmt -
1465/// This routine rewrites @synchronized(expr) stmt;
1466/// into:
1467/// objc_sync_enter(expr);
1468/// @try stmt @finally { objc_sync_exit(expr); }
1469///
Steve Naroff44e81222008-04-14 22:03:09 +00001470Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001471 // Get the start location and compute the semi location.
1472 SourceLocation startLoc = S->getLocStart();
1473 const char *startBuf = SM->getCharacterData(startLoc);
1474
1475 assert((*startBuf == '@') && "bogus @synchronized location");
1476
1477 std::string buf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001478 buf = "objc_sync_enter((id)";
1479 const char *lparenBuf = startBuf;
1480 while (*lparenBuf != '(') lparenBuf++;
1481 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroff027cd0b2008-08-19 13:04:19 +00001482 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1483 // the sync expression is typically a message expression that's already
1484 // been rewritten! (which implies the SourceLocation's are invalid).
1485 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001486 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroff027cd0b2008-08-19 13:04:19 +00001487 while (*endBuf != ')') endBuf--;
1488 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001489 buf = ");\n";
1490 // declare a new scope with two variables, _stack and _rethrow.
1491 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1492 buf += "int buf[18/*32-bit i386*/];\n";
1493 buf += "char *pointers[4];} _stack;\n";
1494 buf += "id volatile _rethrow = 0;\n";
1495 buf += "objc_exception_try_enter(&_stack);\n";
1496 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001497 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001498 startLoc = S->getSynchBody()->getLocEnd();
1499 startBuf = SM->getCharacterData(startLoc);
1500
Steve Naroff027cd0b2008-08-19 13:04:19 +00001501 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001502 SourceLocation lastCurlyLoc = startLoc;
1503 buf = "}\nelse {\n";
1504 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff450d2fc2009-04-29 16:37:50 +00001505 buf += "}\n";
1506 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001507 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001508 buf += " objc_sync_exit(";
Ted Kremenek0c97e042009-02-07 01:47:29 +00001509 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1510 S->getSynchExpr(),
1511 Context->getObjCIdType(),
1512 SourceLocation(),
1513 SourceLocation());
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001514 std::string syncExprBufS;
1515 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroffc1656a62008-08-21 13:03:03 +00001516 syncExpr->printPretty(syncExprBuf);
Steve Naroff17919b52008-07-16 19:47:39 +00001517 buf += syncExprBuf.str();
1518 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001519 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1520 buf += "}\n";
1521 buf += "}";
1522
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001523 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001524 return 0;
1525}
1526
Steve Naroff43964fb2008-12-05 17:03:39 +00001527void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1528 // Perform a bottom up traversal of all children.
1529 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1530 CI != E; ++CI)
1531 if (*CI)
1532 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1533
1534 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1535 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1536 Diags.Report(Context->getFullLoc(S->getLocStart()),
1537 TryFinallyContainsReturnDiag);
1538 }
1539 return;
1540}
1541
Steve Naroff44e81222008-04-14 22:03:09 +00001542Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001543 // Get the start location and compute the semi location.
1544 SourceLocation startLoc = S->getLocStart();
1545 const char *startBuf = SM->getCharacterData(startLoc);
1546
1547 assert((*startBuf == '@') && "bogus @try location");
1548
1549 std::string buf;
1550 // declare a new scope with two variables, _stack and _rethrow.
1551 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1552 buf += "int buf[18/*32-bit i386*/];\n";
1553 buf += "char *pointers[4];} _stack;\n";
1554 buf += "id volatile _rethrow = 0;\n";
1555 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001556 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001557
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001558 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001559
1560 startLoc = S->getTryBody()->getLocEnd();
1561 startBuf = SM->getCharacterData(startLoc);
1562
1563 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001564
Steve Naroffe9f69842007-11-07 04:08:17 +00001565 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001566 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1567 if (catchList) {
1568 startLoc = startLoc.getFileLocWithOffset(1);
1569 buf = " /* @catch begin */ else {\n";
1570 buf += " id _caught = objc_exception_extract(&_stack);\n";
1571 buf += " objc_exception_try_enter (&_stack);\n";
1572 buf += " if (_setjmp(_stack.buf))\n";
1573 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1574 buf += " else { /* @catch continue */";
1575
1576 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff36269d22008-09-09 19:59:12 +00001577 } else { /* no catch list */
1578 buf = "}\nelse {\n";
1579 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1580 buf += "}";
1581 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff9d0ff352008-07-16 15:31:30 +00001582 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001583 bool sawIdTypedCatch = false;
1584 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001585 while (catchList) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001586 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffe9f69842007-11-07 04:08:17 +00001587
1588 if (catchList == S->getCatchStmts())
1589 buf = "if ("; // we are generating code for the first catch clause
1590 else
1591 buf = "else if (";
1592 startLoc = catchList->getLocStart();
1593 startBuf = SM->getCharacterData(startLoc);
1594
1595 assert((*startBuf == '@') && "bogus @catch location");
1596
1597 const char *lParenLoc = strchr(startBuf, '(');
1598
Steve Naroff397c4ce2008-02-01 22:08:12 +00001599 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001600 // Now rewrite the body...
1601 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001602 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1603 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001604 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1605 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001606 assert((*bodyBuf == '{') && "bogus @catch body location");
1607
1608 buf += "1) { id _tmp = _caught;";
1609 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1610 buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001611 } else if (catchDecl) {
1612 QualType t = catchDecl->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001613 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001614 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001615 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001616 sawIdTypedCatch = true;
1617 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001618 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001619
Ted Kremenek42730c52008-01-07 19:49:32 +00001620 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001621 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001622 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00001623 buf += cls->getDecl()->getNameAsString();
Steve Naroffd3287d82007-11-07 18:43:40 +00001624 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001625 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001626 }
1627 }
1628 // Now rewrite the body...
1629 lastCatchBody = catchList->getCatchBody();
1630 SourceLocation rParenLoc = catchList->getRParenLoc();
1631 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1632 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1633 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1634 assert((*rParenBuf == ')') && "bogus @catch paren location");
1635 assert((*bodyBuf == '{') && "bogus @catch body location");
1636
1637 buf = " = _caught;";
1638 // Here we replace ") {" with "= _caught;" (which initializes and
1639 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001640 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001641 } else {
Steve Naroffe9f69842007-11-07 04:08:17 +00001642 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001643 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001644 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001645 catchList = catchList->getNextCatchStmt();
1646 }
1647 // Complete the catch list...
1648 if (lastCatchBody) {
1649 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001650 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1651 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001652
Steve Naroff31325c12008-09-11 15:29:03 +00001653 // Insert the last (implicit) else clause *before* the right curly brace.
1654 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1655 buf = "} /* last catch end */\n";
1656 buf += "else {\n";
1657 buf += " _rethrow = _caught;\n";
1658 buf += " objc_exception_try_exit(&_stack);\n";
1659 buf += "} } /* @catch end */\n";
1660 if (!S->getFinallyStmt())
1661 buf += "}\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001662 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001663
1664 // Set lastCurlyLoc
1665 lastCurlyLoc = lastCatchBody->getLocEnd();
1666 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001667 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001668 startLoc = finalStmt->getLocStart();
1669 startBuf = SM->getCharacterData(startLoc);
1670 assert((*startBuf == '@') && "bogus @finally start");
1671
1672 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001673 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001674
1675 Stmt *body = finalStmt->getFinallyBody();
1676 SourceLocation startLoc = body->getLocStart();
1677 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001678 assert(*SM->getCharacterData(startLoc) == '{' &&
1679 "bogus @finally body location");
1680 assert(*SM->getCharacterData(endLoc) == '}' &&
1681 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001682
1683 startLoc = startLoc.getFileLocWithOffset(1);
1684 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001685 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001686 endLoc = endLoc.getFileLocWithOffset(-1);
1687 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001688 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001689
1690 // Set lastCurlyLoc
1691 lastCurlyLoc = body->getLocEnd();
Steve Naroff43964fb2008-12-05 17:03:39 +00001692
1693 // Now check for any return/continue/go statements within the @try.
1694 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff31325c12008-09-11 15:29:03 +00001695 } else { /* no finally clause - make sure we synthesize an implicit one */
1696 buf = "{ /* implicit finally clause */\n";
1697 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1698 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1699 buf += "}";
1700 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001701 }
1702 // Now emit the final closing curly brace...
1703 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1704 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001705 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001706 return 0;
1707}
1708
Steve Naroff44e81222008-04-14 22:03:09 +00001709Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001710 return 0;
1711}
1712
Steve Naroff44e81222008-04-14 22:03:09 +00001713Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001714 return 0;
1715}
1716
Chris Lattnerb1548372008-01-31 19:37:57 +00001717// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001718// the throw expression is typically a message expression that's already
1719// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001720Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001721 // Get the start location and compute the semi location.
1722 SourceLocation startLoc = S->getLocStart();
1723 const char *startBuf = SM->getCharacterData(startLoc);
1724
1725 assert((*startBuf == '@') && "bogus @throw location");
1726
1727 std::string buf;
1728 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001729 if (S->getThrowExpr())
1730 buf = "objc_exception_throw(";
1731 else // add an implicit argument
1732 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001733
1734 // handle "@ throw" correctly.
1735 const char *wBuf = strchr(startBuf, 'w');
1736 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1737 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1738
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001739 const char *semiBuf = strchr(startBuf, ';');
1740 assert((*semiBuf == ';') && "@throw: can't find ';'");
1741 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1742 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001743 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001744 return 0;
1745}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001746
Steve Naroff44e81222008-04-14 22:03:09 +00001747Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001748 // Create a new string expression.
1749 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001750 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001751 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattneraa491192009-02-18 06:40:38 +00001752 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1753 StrEncoding.length(), false,StrType,
1754 SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001755 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001756
Chris Lattner4478db92007-11-30 22:53:43 +00001757 // Replace this subexpr in the parent.
Steve Naroff102c3f22008-12-04 23:50:32 +00001758 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner0021f452007-10-24 16:57:36 +00001759 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001760}
1761
Steve Naroff44e81222008-04-14 22:03:09 +00001762Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff95f6bce2008-12-22 22:16:07 +00001763 if (!SelGetUidFunctionDecl)
1764 SynthSelGetUidFunctionDecl();
Steve Naroff296b74f2007-11-05 14:50:49 +00001765 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1766 // Create a call to sel_registerName("selName").
1767 llvm::SmallVector<Expr*, 8> SelExprs;
1768 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00001769 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00001770 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00001771 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00001772 false, argType, SourceLocation()));
Steve Naroff296b74f2007-11-05 14:50:49 +00001773 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1774 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001775 ReplaceStmt(Exp, SelExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00001776 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff296b74f2007-11-05 14:50:49 +00001777 return SelExp;
1778}
1779
Steve Naroff44e81222008-04-14 22:03:09 +00001780CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001781 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001782 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001783 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001784
1785 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001786 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001787
1788 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001789 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001790 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregor70d26122008-11-12 17:17:38 +00001791 /*isLvalue=*/false);
Steve Naroffe9780582007-10-23 23:50:29 +00001792
1793 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001794
Ted Kremenek362abcd2009-02-09 20:51:47 +00001795 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1796 SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001797}
1798
Steve Naroffc8a92d12007-11-01 13:24:47 +00001799static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1800 const char *&startRef, const char *&endRef) {
1801 while (startBuf < endBuf) {
1802 if (*startBuf == '<')
1803 startRef = startBuf; // mark the start.
1804 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001805 if (startRef && *startRef == '<') {
1806 endRef = startBuf; // mark the end.
1807 return true;
1808 }
1809 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001810 }
1811 startBuf++;
1812 }
1813 return false;
1814}
1815
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001816static void scanToNextArgument(const char *&argRef) {
1817 int angle = 0;
1818 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1819 if (*argRef == '<')
1820 angle++;
1821 else if (*argRef == '>')
1822 angle--;
1823 argRef++;
1824 }
1825 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1826}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001827
Steve Naroff44e81222008-04-14 22:03:09 +00001828bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001829
Ted Kremenek42730c52008-01-07 19:49:32 +00001830 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001831 return true;
1832
Steve Naroffc8a92d12007-11-01 13:24:47 +00001833 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001834 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001835 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001836 return true; // we have "Class <Protocol> *".
1837 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001838 return false;
1839}
1840
Steve Naroffd06c88d2008-07-29 18:15:38 +00001841void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1842 QualType Type = E->getType();
1843 if (needToScanForQualifiers(Type)) {
Steve Narofff31ece92008-11-19 21:15:47 +00001844 SourceLocation Loc, EndLoc;
1845
1846 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1847 Loc = ECE->getLParenLoc();
1848 EndLoc = ECE->getRParenLoc();
1849 } else {
1850 Loc = E->getLocStart();
1851 EndLoc = E->getLocEnd();
1852 }
1853 // This will defend against trying to rewrite synthesized expressions.
1854 if (Loc.isInvalid() || EndLoc.isInvalid())
1855 return;
1856
Steve Naroffd06c88d2008-07-29 18:15:38 +00001857 const char *startBuf = SM->getCharacterData(Loc);
Steve Narofff31ece92008-11-19 21:15:47 +00001858 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroffd06c88d2008-07-29 18:15:38 +00001859 const char *startRef = 0, *endRef = 0;
1860 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1861 // Get the locations of the startRef, endRef.
1862 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1863 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1864 // Comment out the protocol references.
1865 InsertText(LessLoc, "/*", 2);
1866 InsertText(GreaterLoc, "*/", 2);
1867 }
1868 }
1869}
1870
Steve Naroff44e81222008-04-14 22:03:09 +00001871void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001872 SourceLocation Loc;
1873 QualType Type;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001874 const FunctionProtoType *proto = 0;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001875 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1876 Loc = VD->getLocation();
1877 Type = VD->getType();
1878 }
1879 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1880 Loc = FD->getLocation();
1881 // Check for ObjC 'id' and class types that have been adorned with protocol
1882 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1883 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1884 assert(funcType && "missing function type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00001885 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001886 if (!proto)
1887 return;
1888 Type = proto->getResultType();
1889 }
1890 else
1891 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001892
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001893 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001894 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001895
1896 const char *endBuf = SM->getCharacterData(Loc);
1897 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001898 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001899 startBuf--; // scan backward (from the decl location) for return type.
1900 const char *startRef = 0, *endRef = 0;
1901 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1902 // Get the locations of the startRef, endRef.
1903 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1904 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1905 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001906 InsertText(LessLoc, "/*", 2);
1907 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001908 }
1909 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001910 if (!proto)
1911 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001912 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001913 const char *startBuf = SM->getCharacterData(Loc);
1914 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001915 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1916 if (needToScanForQualifiers(proto->getArgType(i))) {
1917 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001918
Steve Naroffc8a92d12007-11-01 13:24:47 +00001919 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001920 // scan forward (from the decl location) for argument types.
1921 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001922 const char *startRef = 0, *endRef = 0;
1923 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1924 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001925 SourceLocation LessLoc =
1926 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1927 SourceLocation GreaterLoc =
1928 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001929 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001930 InsertText(LessLoc, "/*", 2);
1931 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001932 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001933 startBuf = ++endBuf;
1934 }
1935 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001936 // If the function name is derived from a macro expansion, then the
1937 // argument buffer will not follow the name. Need to speak with Chris.
1938 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001939 startBuf++; // scan forward (from the decl location) for argument types.
1940 startBuf++;
1941 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001942 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001943}
1944
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001945// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001946void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001947 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1948 llvm::SmallVector<QualType, 16> ArgTys;
1949 ArgTys.push_back(Context->getPointerType(
1950 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001951 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001952 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001953 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001954 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001955 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001956 SelGetUidIdent, getFuncType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001957 FunctionDecl::Extern, false);
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001958}
1959
Steve Naroff44e81222008-04-14 22:03:09 +00001960void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001961 // declared in <objc/objc.h>
Douglas Gregor7339c9e2009-01-09 01:47:02 +00001962 if (FD->getIdentifier() &&
1963 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001964 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001965 return;
1966 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001967 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001968}
1969
Steve Naroffbec4bf52008-03-11 17:37:02 +00001970// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001971void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001972 if (SuperContructorFunctionDecl)
1973 return;
Steve Naroff12673622008-12-23 20:11:22 +00001974 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffbec4bf52008-03-11 17:37:02 +00001975 llvm::SmallVector<QualType, 16> ArgTys;
1976 QualType argT = Context->getObjCIdType();
1977 assert(!argT.isNull() && "Can't find 'id' type");
1978 ArgTys.push_back(argT);
1979 ArgTys.push_back(argT);
1980 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1981 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001982 false, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001983 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001984 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001985 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001986 FunctionDecl::Extern, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00001987}
1988
Steve Naroff02a82aa2007-10-30 23:14:51 +00001989// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001990void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001991 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1992 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001993 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001994 assert(!argT.isNull() && "Can't find 'id' type");
1995 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001996 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001997 assert(!argT.isNull() && "Can't find 'SEL' type");
1998 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001999 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002000 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002001 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002002 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002003 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002004 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002005 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00002006}
2007
Steve Naroff764c1ae2007-11-15 10:28:18 +00002008// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002009void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002010 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2011 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002012 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002013 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002014 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002015 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2016 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2017 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002018 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002019 assert(!argT.isNull() && "Can't find 'SEL' type");
2020 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002021 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002022 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002023 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002024 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002025 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002026 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002027 FunctionDecl::Extern, false);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002028}
2029
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002030// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002031void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002032 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2033 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002034 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002035 assert(!argT.isNull() && "Can't find 'id' type");
2036 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002037 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002038 assert(!argT.isNull() && "Can't find 'SEL' type");
2039 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002040 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002041 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002042 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002043 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002044 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002045 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002046 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002047}
2048
2049// SynthMsgSendSuperStretFunctionDecl -
2050// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002051void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002052 IdentifierInfo *msgSendIdent =
2053 &Context->Idents.get("objc_msgSendSuper_stret");
2054 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002055 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002056 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002057 &Context->Idents.get("objc_super"));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002058 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2059 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2060 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002061 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002062 assert(!argT.isNull() && "Can't find 'SEL' type");
2063 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002064 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002065 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002066 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002067 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00002068 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002069 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002070 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002071}
2072
Steve Naroff31316a12008-05-08 22:02:18 +00002073// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002074void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002075 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2076 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002077 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002078 assert(!argT.isNull() && "Can't find 'id' type");
2079 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002080 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002081 assert(!argT.isNull() && "Can't find 'SEL' type");
2082 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00002083 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002084 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002085 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002086 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002087 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002088 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002089 FunctionDecl::Extern, false);
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002090}
2091
Steve Naroff02a82aa2007-10-30 23:14:51 +00002092// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002093void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00002094 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2095 llvm::SmallVector<QualType, 16> ArgTys;
2096 ArgTys.push_back(Context->getPointerType(
2097 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002098 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002099 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002100 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002101 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002102 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002103 getClassIdent, getClassType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002104 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00002105}
2106
Steve Naroff3b1caac2007-12-07 03:50:46 +00002107// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002108void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002109 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2110 llvm::SmallVector<QualType, 16> ArgTys;
2111 ArgTys.push_back(Context->getPointerType(
2112 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002113 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002114 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002115 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002116 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002117 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002118 getClassIdent, getClassType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002119 FunctionDecl::Extern, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002120}
2121
Steve Naroff44e81222008-04-14 22:03:09 +00002122Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002123 QualType strType = getConstantStringStructType();
2124
2125 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00002126
2127 std::string tmpName = InFileName;
2128 unsigned i;
2129 for (i=0; i < tmpName.length(); i++) {
2130 char c = tmpName.at(i);
2131 // replace any non alphanumeric characters with '_'.
2132 if (!isalpha(c) && (c < '0' || c > '9'))
2133 tmpName[i] = '_';
2134 }
2135 S += tmpName;
2136 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002137 S += utostr(NumObjCStringLiterals++);
2138
Steve Narofffef037c2008-03-27 22:29:16 +00002139 Preamble += "static __NSConstantStringImpl " + S;
2140 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2141 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00002142 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00002143 std::string prettyBufS;
2144 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002145 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00002146 Preamble += prettyBuf.str();
2147 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00002148 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00002149 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002150
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002151 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002152 &Context->Idents.get(S.c_str()), strType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002153 VarDecl::Static);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002154 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2155 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroff47e7fa22008-03-15 00:55:56 +00002156 Context->getPointerType(DRE->getType()),
2157 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00002158 // cast to NSConstantString *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002159 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroff7f1412d2008-11-03 23:29:32 +00002160 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00002161 ReplaceStmt(Exp, cast);
Steve Naroff102c3f22008-12-04 23:50:32 +00002162 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffabb96362007-11-08 14:30:50 +00002163 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00002164}
2165
Steve Naroff44e81222008-04-14 22:03:09 +00002166ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002167 // check if we are sending a message to 'super'
Douglas Gregor5d764842009-01-09 17:18:27 +00002168 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattnere4650482008-03-15 06:12:44 +00002169
Douglas Gregord8606632008-11-04 14:56:14 +00002170 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2171 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner4423d372008-06-21 18:04:54 +00002172 assert(PT);
2173 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2174 return IT->getDecl();
2175 }
2176 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002177}
2178
2179// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00002180QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002181 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002182 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002183 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002184 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002185 QualType FieldTypes[2];
2186
2187 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00002188 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002189 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00002190 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002191
Steve Naroff764c1ae2007-11-15 10:28:18 +00002192 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002193 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002194 SuperStructDecl->addDecl(*Context,
2195 FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002196 SourceLocation(), 0,
2197 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002198 /*Mutable=*/false));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002199 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002200
Douglas Gregor8acb7272008-12-11 16:49:14 +00002201 SuperStructDecl->completeDefinition(*Context);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002202 }
2203 return Context->getTagDeclType(SuperStructDecl);
2204}
2205
Steve Naroff44e81222008-04-14 22:03:09 +00002206QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002207 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002208 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002209 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002210 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroff47e7fa22008-03-15 00:55:56 +00002211 QualType FieldTypes[4];
2212
2213 // struct objc_object *receiver;
2214 FieldTypes[0] = Context->getObjCIdType();
2215 // int flags;
2216 FieldTypes[1] = Context->IntTy;
2217 // char *str;
2218 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2219 // long length;
2220 FieldTypes[3] = Context->LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002221
Steve Naroff47e7fa22008-03-15 00:55:56 +00002222 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002223 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002224 ConstantStringDecl->addDecl(*Context,
2225 FieldDecl::Create(*Context,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002226 ConstantStringDecl,
2227 SourceLocation(), 0,
2228 FieldTypes[i],
2229 /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002230 /*Mutable=*/true));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002231 }
2232
2233 ConstantStringDecl->completeDefinition(*Context);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002234 }
2235 return Context->getTagDeclType(ConstantStringDecl);
2236}
2237
Steve Naroff44e81222008-04-14 22:03:09 +00002238Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00002239 if (!SelGetUidFunctionDecl)
2240 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002241 if (!MsgSendFunctionDecl)
2242 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002243 if (!MsgSendSuperFunctionDecl)
2244 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002245 if (!MsgSendStretFunctionDecl)
2246 SynthMsgSendStretFunctionDecl();
2247 if (!MsgSendSuperStretFunctionDecl)
2248 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002249 if (!MsgSendFpretFunctionDecl)
2250 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002251 if (!GetClassFunctionDecl)
2252 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002253 if (!GetMetaClassFunctionDecl)
2254 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002255
Steve Naroff764c1ae2007-11-15 10:28:18 +00002256 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002257 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2258 // May need to use objc_msgSend_stret() as well.
2259 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff450d2fc2009-04-29 16:37:50 +00002260 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2261 QualType resultType = mDecl->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00002262 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002263 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00002264 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002265 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002266 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002267
Steve Naroff71226032007-10-24 22:48:43 +00002268 // Synthesize a call to objc_msgSend().
2269 llvm::SmallVector<Expr*, 8> MsgExprs;
2270 IdentifierInfo *clsName = Exp->getClassName();
2271
2272 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2273 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00002274 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2275 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002276 if (!strcmp(clsName->getName(), "super")) {
2277 MsgSendFlavor = MsgSendSuperFunctionDecl;
2278 if (MsgSendStretFlavor)
2279 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2280 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2281
Ted Kremenek42730c52008-01-07 19:49:32 +00002282 ObjCInterfaceDecl *SuperDecl =
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002283 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002284
2285 llvm::SmallVector<Expr*, 4> InitExprs;
2286
2287 // set the receiver to self, the first argument to all methods.
Steve Naroff450d2fc2009-04-29 16:37:50 +00002288 InitExprs.push_back(
2289 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2290 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2291 Context->getObjCIdType(),
2292 SourceLocation()),
2293 Context->getObjCIdType(),
2294 SourceLocation(), SourceLocation())); // set the 'receiver'.
2295
Steve Naroff3b1caac2007-12-07 03:50:46 +00002296 llvm::SmallVector<Expr*, 8> ClsExprs;
2297 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002298 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002299 SuperDecl->getIdentifier()->getName(),
2300 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002301 false, argType, SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002302 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2303 &ClsExprs[0],
2304 ClsExprs.size());
2305 // To turn off a warning, type-cast to 'id'
Douglas Gregor21a04f32008-10-27 19:41:14 +00002306 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002307 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002308 Cls, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002309 SourceLocation(), SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002310 // struct objc_super
2311 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002312 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002313
Steve Naroffdee066b2008-03-11 18:14:26 +00002314 if (LangOpts.Microsoft) {
2315 SynthSuperContructorFunctionDecl();
2316 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002317 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffdee066b2008-03-11 18:14:26 +00002318 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002319 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2320 InitExprs.size(),
2321 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002322 // The code for super is a little tricky to prevent collision with
2323 // the structure definition in the header. The rewriter has it's own
2324 // internal definition (__rw_objc_super) that is uses. This is why
2325 // we need the cast below. For example:
2326 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2327 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002328 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002329 Context->getPointerType(SuperRep->getType()),
2330 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002331 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002332 SuperRep, Context->getPointerType(superType),
2333 SourceLocation(), SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002334 } else {
2335 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002336 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffdee066b2008-03-11 18:14:26 +00002337 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002338 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002339 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner71ca8c82008-10-26 23:43:26 +00002340 false);
Steve Naroff12673622008-12-23 20:11:22 +00002341 // struct objc_super *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002342 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002343 Context->getPointerType(SuperRep->getType()),
2344 SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002345 }
Steve Naroff12673622008-12-23 20:11:22 +00002346 MsgExprs.push_back(SuperRep);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002347 } else {
2348 llvm::SmallVector<Expr*, 8> ClsExprs;
2349 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002350 ClsExprs.push_back(StringLiteral::Create(*Context,
2351 clsName->getName(),
2352 clsName->getLength(),
2353 false, argType,
2354 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002355 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2356 &ClsExprs[0],
2357 ClsExprs.size());
2358 MsgExprs.push_back(Cls);
2359 }
Steve Naroff885e2122007-11-14 23:54:14 +00002360 } else { // instance message.
2361 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002362
Ted Kremenek42730c52008-01-07 19:49:32 +00002363 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002364 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002365 if (MsgSendStretFlavor)
2366 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002367 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2368
2369 llvm::SmallVector<Expr*, 4> InitExprs;
2370
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002371 InitExprs.push_back(
Ted Kremenek0c97e042009-02-07 01:47:29 +00002372 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2373 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff23528612008-07-16 22:35:27 +00002374 Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002375 SourceLocation()),
2376 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002377 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002378
2379 llvm::SmallVector<Expr*, 8> ClsExprs;
2380 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002381 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002382 SuperDecl->getIdentifier()->getName(),
2383 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002384 false, argType, SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002385 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002386 &ClsExprs[0],
2387 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002388 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002389 InitExprs.push_back(
Douglas Gregor21a04f32008-10-27 19:41:14 +00002390 // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002391 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002392 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002393 // struct objc_super
2394 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002395 Expr *SuperRep;
2396
2397 if (LangOpts.Microsoft) {
2398 SynthSuperContructorFunctionDecl();
2399 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002400 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffbec4bf52008-03-11 17:37:02 +00002401 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002402 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2403 InitExprs.size(),
2404 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002405 // The code for super is a little tricky to prevent collision with
2406 // the structure definition in the header. The rewriter has it's own
2407 // internal definition (__rw_objc_super) that is uses. This is why
2408 // we need the cast below. For example:
2409 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2410 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002411 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002412 Context->getPointerType(SuperRep->getType()),
2413 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002414 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002415 SuperRep, Context->getPointerType(superType),
2416 SourceLocation(), SourceLocation());
Steve Naroffbec4bf52008-03-11 17:37:02 +00002417 } else {
2418 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002419 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00002420 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002421 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002422 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00002423 }
Steve Naroff12673622008-12-23 20:11:22 +00002424 MsgExprs.push_back(SuperRep);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002425 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002426 // Remove all type-casts because it may contain objc-style types; e.g.
2427 // Foo<Proto> *.
Douglas Gregor035d0882008-10-28 15:36:24 +00002428 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002429 recExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002430 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002431 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002432 SourceLocation(), SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002433 MsgExprs.push_back(recExpr);
2434 }
Steve Naroff885e2122007-11-14 23:54:14 +00002435 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002436 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002437 llvm::SmallVector<Expr*, 8> SelExprs;
2438 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002439 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002440 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00002441 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002442 false, argType, SourceLocation()));
Steve Naroff71226032007-10-24 22:48:43 +00002443 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2444 &SelExprs[0], SelExprs.size());
2445 MsgExprs.push_back(SelExp);
2446
2447 // Now push any user supplied arguments.
2448 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002449 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002450 // Make all implicit casts explicit...ICE comes in handy:-)
2451 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2452 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor21a04f32008-10-27 19:41:14 +00002453 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002454 ? Context->getObjCIdType()
Douglas Gregor21a04f32008-10-27 19:41:14 +00002455 : ICE->getType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002456 userExpr = new (Context) CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002457 }
2458 // Make id<P...> cast into an 'id' cast.
Douglas Gregor035d0882008-10-28 15:36:24 +00002459 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002460 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor035d0882008-10-28 15:36:24 +00002461 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002462 userExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002463 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002464 userExpr, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002465 SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002466 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002467 }
Steve Naroff885e2122007-11-14 23:54:14 +00002468 MsgExprs.push_back(userExpr);
Steve Naroff450d2fc2009-04-29 16:37:50 +00002469 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2470 // out the argument in the original expression (since we aren't deleting
2471 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2472 //Exp->setArg(i, 0);
Steve Naroff71226032007-10-24 22:48:43 +00002473 }
Steve Naroff0744c472007-11-04 22:37:50 +00002474 // Generate the funky cast.
2475 CastExpr *cast;
2476 llvm::SmallVector<QualType, 8> ArgTypes;
2477 QualType returnType;
2478
2479 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002480 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2481 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2482 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002483 ArgTypes.push_back(Context->getObjCIdType());
2484 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002485 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002486 // Push any user argument types.
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002487 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2488 E = OMD->param_end(); PI != E; ++PI) {
2489 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002490 ? Context->getObjCIdType()
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002491 : (*PI)->getType();
Steve Naroff66c842f2008-10-29 14:49:46 +00002492 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00002493 if (isTopLevelBlockPointerType(t)) {
Steve Naroff66c842f2008-10-29 14:49:46 +00002494 const BlockPointerType *BPT = t->getAsBlockPointerType();
2495 t = Context->getPointerType(BPT->getPointeeType());
2496 }
Steve Naroff4242b972007-11-05 14:36:37 +00002497 ArgTypes.push_back(t);
2498 }
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002499 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2500 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002501 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002502 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002503 }
2504 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002505 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002506
2507 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002508 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002509 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002510
2511 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2512 // If we don't do this cast, we get the following bizarre warning/note:
2513 // xx.m:13: warning: function called through a non-compatible type
2514 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek0c97e042009-02-07 01:47:29 +00002515 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002516 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002517 SourceLocation(), SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002518
Steve Naroff0744c472007-11-04 22:37:50 +00002519 // Now do the "normal" pointer to function cast.
2520 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002521 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002522 // If we don't have a method decl, force a variadic cast.
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002523 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroff0744c472007-11-04 22:37:50 +00002524 castType = Context->getPointerType(castType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002525 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002526
2527 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002528 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroff0744c472007-11-04 22:37:50 +00002529
2530 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002531 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2532 MsgExprs.size(),
2533 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002534 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002535 if (MsgSendStretFlavor) {
2536 // We have the method which returns a struct/union. Must also generate
2537 // call to objc_msgSend_stret and hang both varieties on a conditional
2538 // expression which dictate which one to envoke depending on size of
2539 // method's return type.
2540
2541 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002542 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002543 SourceLocation());
2544 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek0c97e042009-02-07 01:47:29 +00002545 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002546 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002547 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002548 // Now do the "normal" pointer to function cast.
2549 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002550 &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002551 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002552 castType = Context->getPointerType(castType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002553 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002554
2555 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002556 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002557
2558 FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002559 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2560 MsgExprs.size(),
2561 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002562
2563 // Build sizeof(returnType)
Douglas Gregor396f1142009-03-13 21:01:28 +00002564 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
2565 returnType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002566 Context->getSizeType(),
2567 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002568 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2569 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2570 // For X86 it is more complicated and some kind of target specific routine
2571 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002572 unsigned IntSize =
2573 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek0c97e042009-02-07 01:47:29 +00002574 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002575 Context->IntTy,
2576 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002577 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002578 BinaryOperator::LE,
2579 Context->IntTy,
2580 SourceLocation());
2581 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2582 ConditionalOperator *CondExpr =
Ted Kremenek0c97e042009-02-07 01:47:29 +00002583 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2584 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002585 }
Steve Naroff450d2fc2009-04-29 16:37:50 +00002586 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002587 return ReplacingStmt;
2588}
2589
Steve Naroff44e81222008-04-14 22:03:09 +00002590Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002591 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroffe8efe892008-10-27 20:54:44 +00002592
Steve Naroff71226032007-10-24 22:48:43 +00002593 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002594 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002595
Steve Naroff102c3f22008-12-04 23:50:32 +00002596 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002597 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002598}
2599
Steve Naroff450d2fc2009-04-29 16:37:50 +00002600// typedef struct objc_object Protocol;
2601QualType RewriteObjC::getProtocolType() {
2602 if (!ProtocolTypeDecl) {
2603 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2604 SourceLocation(),
2605 &Context->Idents.get("Protocol"),
2606 Context->getObjCIdType());
2607 }
2608 return Context->getTypeDeclType(ProtocolTypeDecl);
2609}
2610
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002611/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff450d2fc2009-04-29 16:37:50 +00002612/// a synthesized/forward data reference (to the protocol's metadata).
2613/// The forward references (and metadata) are generated in
2614/// RewriteObjC::HandleTranslationUnit().
Steve Naroff44e81222008-04-14 22:03:09 +00002615Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff450d2fc2009-04-29 16:37:50 +00002616 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2617 IdentifierInfo *ID = &Context->Idents.get(Name);
2618 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2619 ID, QualType()/*UNUSED*/, VarDecl::Extern);
2620 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2621 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2622 Context->getPointerType(DRE->getType()),
2623 SourceLocation());
2624 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(), DerefExpr,
2625 DerefExpr->getType(),
2626 SourceLocation(), SourceLocation());
2627 ReplaceStmt(Exp, castExpr);
2628 ProtocolExprDecls.insert(Exp->getProtocol());
2629 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
2630 return castExpr;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002631
2632}
2633
Steve Naroffef82b742008-05-31 14:15:04 +00002634bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2635 const char *endBuf) {
2636 while (startBuf < endBuf) {
2637 if (*startBuf == '#') {
2638 // Skip whitespace.
2639 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2640 ;
2641 if (!strncmp(startBuf, "if", strlen("if")) ||
2642 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2643 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2644 !strncmp(startBuf, "define", strlen("define")) ||
2645 !strncmp(startBuf, "undef", strlen("undef")) ||
2646 !strncmp(startBuf, "else", strlen("else")) ||
2647 !strncmp(startBuf, "elif", strlen("elif")) ||
2648 !strncmp(startBuf, "endif", strlen("endif")) ||
2649 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2650 !strncmp(startBuf, "include", strlen("include")) ||
2651 !strncmp(startBuf, "import", strlen("import")) ||
2652 !strncmp(startBuf, "include_next", strlen("include_next")))
2653 return true;
2654 }
2655 startBuf++;
2656 }
2657 return false;
2658}
2659
Ted Kremenek42730c52008-01-07 19:49:32 +00002660/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002661/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002662void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002663 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002664 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002665 assert(CDecl->getNameAsCString() &&
Douglas Gregor24afd4a2008-11-17 14:58:09 +00002666 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002667 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002668 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002669 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002670 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002671 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002672 SourceLocation LocStart = CDecl->getLocStart();
2673 SourceLocation LocEnd = CDecl->getLocEnd();
2674
2675 const char *startBuf = SM->getCharacterData(LocStart);
2676 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002677
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002678 // If no ivars and no root or if its root, directly or indirectly,
2679 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002680 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2681 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattnere1be6022009-04-14 23:22:57 +00002682 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002683 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002684 return;
2685 }
2686
2687 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002688 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002689 Result += "\nstruct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002690 Result += CDecl->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +00002691 if (LangOpts.Microsoft)
2692 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002693
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002694 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002695 const char *cursor = strchr(startBuf, '{');
2696 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002697 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002698 // If the buffer contains preprocessor directives, we do more fine-grained
2699 // rewrites. This is intended to fix code that looks like (which occurs in
2700 // NSURL.h, for example):
2701 //
2702 // #ifdef XYZ
2703 // @interface Foo : NSObject
2704 // #else
2705 // @interface FooBar : NSObject
2706 // #endif
2707 // {
2708 // int i;
2709 // }
2710 // @end
2711 //
2712 // This clause is segregated to avoid breaking the common case.
2713 if (BufferContainsPPDirectives(startBuf, cursor)) {
2714 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2715 CDecl->getClassLoc();
2716 const char *endHeader = SM->getCharacterData(L);
Chris Lattnere1be6022009-04-14 23:22:57 +00002717 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffef82b742008-05-31 14:15:04 +00002718
Chris Lattner179fd522009-02-20 18:18:36 +00002719 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002720 // advance to the end of the referenced protocols.
2721 while (endHeader < cursor && *endHeader != '>') endHeader++;
2722 endHeader++;
2723 }
2724 // rewrite the original header
2725 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2726 } else {
2727 // rewrite the original header *without* disturbing the '{'
2728 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2729 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002730 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002731 Result = "\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002732 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002733 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002734 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002735 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002736
2737 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002738 SourceLocation OnePastCurly =
2739 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2740 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002741 }
2742 cursor++; // past '{'
2743
2744 // Now comment out any visibility specifiers.
2745 while (cursor < endBuf) {
2746 if (*cursor == '@') {
2747 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002748 // Skip whitespace.
2749 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2750 /*scan*/;
2751
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002752 // FIXME: presence of @public, etc. inside comment results in
2753 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002754 if (!strncmp(cursor, "public", strlen("public")) ||
2755 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002756 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002757 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002758 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002759 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002760 // FIXME: If there are cases where '<' is used in ivar declaration part
2761 // of user code, then scan the ivar list and use needToScanForQualifiers
2762 // for type checking.
2763 else if (*cursor == '<') {
2764 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002765 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002766 cursor = strchr(cursor, '>');
2767 cursor++;
2768 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002769 InsertText(atLoc, " */", 3);
Steve Naroff6449c6c2008-10-30 12:09:33 +00002770 } else if (*cursor == '^') { // rewrite block specifier.
2771 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2772 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002773 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002774 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002775 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002776 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002777 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002778 } else { // we don't have any instance variables - insert super struct.
Chris Lattnere1be6022009-04-14 23:22:57 +00002779 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002780 Result += " {\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002781 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002782 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002783 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002784 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002785 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002786 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002787 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002788 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002789 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002790}
2791
Ted Kremenek42730c52008-01-07 19:49:32 +00002792// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002793/// class methods.
Douglas Gregorcd19b572009-04-23 01:02:12 +00002794template<typename MethodIterator>
2795void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2796 MethodIterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002797 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002798 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002799 const char *ClassName,
2800 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002801 if (MethodBegin == MethodEnd) return;
2802
Fariborz Jahanian04455192007-10-22 21:41:37 +00002803 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002804 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002805 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002806 SEL _cmd;
2807 char *method_types;
2808 void *_imp;
2809 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002810 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002811 Result += "\nstruct _objc_method {\n";
2812 Result += "\tSEL _cmd;\n";
2813 Result += "\tchar *method_types;\n";
2814 Result += "\tvoid *_imp;\n";
2815 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002816
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002817 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002818 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002819
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002820 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002821
2822 /* struct {
2823 struct _objc_method_list *next_method;
2824 int method_count;
2825 struct _objc_method method_list[];
2826 }
2827 */
Douglas Gregorcd19b572009-04-23 01:02:12 +00002828 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc723eec2008-03-11 00:12:29 +00002829 Result += "\nstatic struct {\n";
2830 Result += "\tstruct _objc_method_list *next_method;\n";
2831 Result += "\tint method_count;\n";
2832 Result += "\tstruct _objc_method method_list[";
Douglas Gregorcd19b572009-04-23 01:02:12 +00002833 Result += utostr(NumMethods);
Steve Naroffc723eec2008-03-11 00:12:29 +00002834 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002835 Result += prefix;
2836 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2837 Result += "_METHODS_";
2838 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002839 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002840 Result += IsInstanceMethod ? "inst" : "cls";
2841 Result += "_meth\")))= ";
Douglas Gregorcd19b572009-04-23 01:02:12 +00002842 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002843
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002844 Result += "\t,{{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002845 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002846 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002847 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002848 Result += "\", \"";
2849 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002850 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002851 Result += MethodInternalNames[*MethodBegin];
2852 Result += "}\n";
2853 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2854 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002855 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002856 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002857 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002858 Result += "\", \"";
2859 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002860 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002861 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002862 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002863 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002864 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002865}
2866
Steve Naroff450d2fc2009-04-29 16:37:50 +00002867/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002868void RewriteObjC::
Steve Naroff450d2fc2009-04-29 16:37:50 +00002869RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2870 const char *ClassName, std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002871 static bool objc_protocol_methods = false;
Steve Naroff450d2fc2009-04-29 16:37:50 +00002872
2873 // Output struct protocol_methods holder of method selector and type.
2874 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2875 /* struct protocol_methods {
2876 SEL _cmd;
2877 char *method_types;
2878 }
2879 */
2880 Result += "\nstruct _protocol_methods {\n";
2881 Result += "\tstruct objc_selector *_cmd;\n";
2882 Result += "\tchar *method_types;\n";
2883 Result += "};\n";
2884
2885 objc_protocol_methods = true;
2886 }
2887 // Do not synthesize the protocol more than once.
2888 if (ObjCSynthesizedProtocols.count(PDecl))
2889 return;
2890
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002891 if (PDecl->instmeth_begin(*Context) != PDecl->instmeth_end(*Context)) {
2892 unsigned NumMethods = std::distance(PDecl->instmeth_begin(*Context),
2893 PDecl->instmeth_end(*Context));
Steve Naroff450d2fc2009-04-29 16:37:50 +00002894 /* struct _objc_protocol_method_list {
2895 int protocol_method_count;
2896 struct protocol_methods protocols[];
2897 }
Steve Naroff27429432008-03-12 01:06:30 +00002898 */
Steve Naroff450d2fc2009-04-29 16:37:50 +00002899 Result += "\nstatic struct {\n";
2900 Result += "\tint protocol_method_count;\n";
2901 Result += "\tstruct _protocol_methods protocol_methods[";
2902 Result += utostr(NumMethods);
2903 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2904 Result += PDecl->getNameAsString();
2905 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2906 "{\n\t" + utostr(NumMethods) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002907
Steve Naroff450d2fc2009-04-29 16:37:50 +00002908 // Output instance methods declared in this protocol.
2909 for (ObjCProtocolDecl::instmeth_iterator
2910 I = PDecl->instmeth_begin(*Context),
2911 E = PDecl->instmeth_end(*Context);
2912 I != E; ++I) {
2913 if (I == PDecl->instmeth_begin(*Context))
2914 Result += "\t ,{{(struct objc_selector *)\"";
2915 else
2916 Result += "\t ,{(struct objc_selector *)\"";
2917 Result += (*I)->getSelector().getAsString().c_str();
2918 std::string MethodTypeString;
2919 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2920 Result += "\", \"";
2921 Result += MethodTypeString;
2922 Result += "\"}\n";
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002923 }
Steve Naroff450d2fc2009-04-29 16:37:50 +00002924 Result += "\t }\n};\n";
2925 }
2926
2927 // Output class methods declared in this protocol.
2928 unsigned NumMethods = std::distance(PDecl->classmeth_begin(*Context),
2929 PDecl->classmeth_end(*Context));
2930 if (NumMethods > 0) {
2931 /* struct _objc_protocol_method_list {
2932 int protocol_method_count;
2933 struct protocol_methods protocols[];
2934 }
2935 */
2936 Result += "\nstatic struct {\n";
2937 Result += "\tint protocol_method_count;\n";
2938 Result += "\tstruct _protocol_methods protocol_methods[";
2939 Result += utostr(NumMethods);
2940 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2941 Result += PDecl->getNameAsString();
2942 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2943 "{\n\t";
2944 Result += utostr(NumMethods);
2945 Result += "\n";
2946
2947 // Output instance methods declared in this protocol.
2948 for (ObjCProtocolDecl::classmeth_iterator
2949 I = PDecl->classmeth_begin(*Context),
2950 E = PDecl->classmeth_end(*Context);
2951 I != E; ++I) {
2952 if (I == PDecl->classmeth_begin(*Context))
2953 Result += "\t ,{{(struct objc_selector *)\"";
2954 else
2955 Result += "\t ,{(struct objc_selector *)\"";
2956 Result += (*I)->getSelector().getAsString().c_str();
2957 std::string MethodTypeString;
2958 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2959 Result += "\", \"";
2960 Result += MethodTypeString;
2961 Result += "\"}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002962 }
Steve Naroff450d2fc2009-04-29 16:37:50 +00002963 Result += "\t }\n};\n";
2964 }
2965
2966 // Output:
2967 /* struct _objc_protocol {
2968 // Objective-C 1.0 extensions
2969 struct _objc_protocol_extension *isa;
2970 char *protocol_name;
2971 struct _objc_protocol **protocol_list;
2972 struct _objc_protocol_method_list *instance_methods;
2973 struct _objc_protocol_method_list *class_methods;
2974 };
2975 */
2976 static bool objc_protocol = false;
2977 if (!objc_protocol) {
2978 Result += "\nstruct _objc_protocol {\n";
2979 Result += "\tstruct _objc_protocol_extension *isa;\n";
2980 Result += "\tchar *protocol_name;\n";
2981 Result += "\tstruct _objc_protocol **protocol_list;\n";
2982 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2983 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002984 Result += "};\n";
2985
Steve Naroff450d2fc2009-04-29 16:37:50 +00002986 objc_protocol = true;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002987 }
Steve Naroff450d2fc2009-04-29 16:37:50 +00002988
2989 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2990 Result += PDecl->getNameAsString();
2991 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2992 "{\n\t0, \"";
2993 Result += PDecl->getNameAsString();
2994 Result += "\", 0, ";
2995 if (PDecl->instmeth_begin(*Context) != PDecl->instmeth_end(*Context)) {
2996 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2997 Result += PDecl->getNameAsString();
2998 Result += ", ";
2999 }
3000 else
3001 Result += "0, ";
3002 if (PDecl->classmeth_begin(*Context) != PDecl->classmeth_end(*Context)) {
3003 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3004 Result += PDecl->getNameAsString();
3005 Result += "\n";
3006 }
3007 else
3008 Result += "0\n";
3009 Result += "};\n";
3010
3011 // Mark this protocol as having been generated.
3012 if (!ObjCSynthesizedProtocols.insert(PDecl))
3013 assert(false && "protocol already synthesized");
3014
3015}
3016
3017void RewriteObjC::
3018RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3019 const char *prefix, const char *ClassName,
3020 std::string &Result) {
3021 if (Protocols.empty()) return;
3022
3023 for (unsigned i = 0; i != Protocols.size(); i++)
3024 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3025
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003026 // Output the top lovel protocol meta-data for the class.
3027 /* struct _objc_protocol_list {
3028 struct _objc_protocol_list *next;
3029 int protocol_count;
3030 struct _objc_protocol *class_protocols[];
3031 }
3032 */
3033 Result += "\nstatic struct {\n";
3034 Result += "\tstruct _objc_protocol_list *next;\n";
3035 Result += "\tint protocol_count;\n";
3036 Result += "\tstruct _objc_protocol *class_protocols[";
3037 Result += utostr(Protocols.size());
3038 Result += "];\n} _OBJC_";
3039 Result += prefix;
3040 Result += "_PROTOCOLS_";
3041 Result += ClassName;
3042 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3043 "{\n\t0, ";
3044 Result += utostr(Protocols.size());
3045 Result += "\n";
3046
3047 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003048 Result += Protocols[0]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003049 Result += " \n";
3050
3051 for (unsigned i = 1; i != Protocols.size(); i++) {
3052 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003053 Result += Protocols[i]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003054 Result += "\n";
3055 }
3056 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003057}
3058
Steve Naroff450d2fc2009-04-29 16:37:50 +00003059
Ted Kremenek42730c52008-01-07 19:49:32 +00003060/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003061/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00003062void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003063 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003064 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003065 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003066 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003067 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3068 CDecl = CDecl->getNextClassCategory())
3069 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3070 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003071
Chris Lattner271d4c22008-11-24 05:29:24 +00003072 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00003073 FullCategoryName += '_';
Chris Lattner271d4c22008-11-24 05:29:24 +00003074 FullCategoryName += IDecl->getNameAsString();
Steve Naroff450d2fc2009-04-29 16:37:50 +00003075
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003076 // Build _objc_method_list for class's instance methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003077 llvm::SmallVector<ObjCMethodDecl *, 32>
3078 InstanceMethods(IDecl->instmeth_begin(*Context),
3079 IDecl->instmeth_end(*Context));
3080
3081 // If any of our property implementations have associated getters or
3082 // setters, produce metadata for them as well.
3083 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(*Context),
3084 PropEnd = IDecl->propimpl_end(*Context);
3085 Prop != PropEnd; ++Prop) {
3086 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3087 continue;
3088 if (!(*Prop)->getPropertyIvarDecl())
3089 continue;
3090 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3091 if (!PD)
3092 continue;
3093 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3094 InstanceMethods.push_back(Getter);
3095 if (PD->isReadOnly())
3096 continue;
3097 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3098 InstanceMethods.push_back(Setter);
3099 }
3100 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003101 true, "CATEGORY_", FullCategoryName.c_str(),
3102 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003103
3104 // Build _objc_method_list for class's class methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003105 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(*Context),
3106 IDecl->classmeth_end(*Context),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003107 false, "CATEGORY_", FullCategoryName.c_str(),
3108 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003109
3110 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00003111 // Null CDecl is case of a category implementation with no category interface
3112 if (CDecl)
Steve Naroff450d2fc2009-04-29 16:37:50 +00003113 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3114 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003115 /* struct _objc_category {
3116 char *category_name;
3117 char *class_name;
3118 struct _objc_method_list *instance_methods;
3119 struct _objc_method_list *class_methods;
3120 struct _objc_protocol_list *protocols;
3121 // Objective-C 1.0 extensions
3122 uint32_t size; // sizeof (struct _objc_category)
3123 struct _objc_property_list *instance_properties; // category's own
3124 // @property decl.
3125 };
3126 */
3127
3128 static bool objc_category = false;
3129 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003130 Result += "\nstruct _objc_category {\n";
3131 Result += "\tchar *category_name;\n";
3132 Result += "\tchar *class_name;\n";
3133 Result += "\tstruct _objc_method_list *instance_methods;\n";
3134 Result += "\tstruct _objc_method_list *class_methods;\n";
3135 Result += "\tstruct _objc_protocol_list *protocols;\n";
3136 Result += "\tunsigned int size;\n";
3137 Result += "\tstruct _objc_property_list *instance_properties;\n";
3138 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003139 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00003140 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003141 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3142 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00003143 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003144 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003145 Result += "\"\n\t, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003146 Result += ClassDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003147 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003148
Douglas Gregorcd19b572009-04-23 01:02:12 +00003149 if (IDecl->instmeth_begin(*Context) != IDecl->instmeth_end(*Context)) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003150 Result += "\t, (struct _objc_method_list *)"
3151 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3152 Result += FullCategoryName;
3153 Result += "\n";
3154 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003155 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003156 Result += "\t, 0\n";
Douglas Gregorcd19b572009-04-23 01:02:12 +00003157 if (IDecl->classmeth_begin(*Context) != IDecl->classmeth_end(*Context)) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003158 Result += "\t, (struct _objc_method_list *)"
3159 "&_OBJC_CATEGORY_CLASS_METHODS_";
3160 Result += FullCategoryName;
3161 Result += "\n";
3162 }
3163 else
3164 Result += "\t, 0\n";
3165
Chris Lattner179fd522009-02-20 18:18:36 +00003166 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003167 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3168 Result += FullCategoryName;
3169 Result += "\n";
3170 }
3171 else
3172 Result += "\t, 0\n";
3173 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003174}
3175
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003176/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3177/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00003178void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00003179 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003180 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00003181 if (ivar->isBitField()) {
3182 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3183 // place all bitfields at offset 0.
3184 Result += "0";
3185 } else {
3186 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003187 Result += IDecl->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003188 if (LangOpts.Microsoft)
3189 Result += "_IMPL";
3190 Result += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003191 Result += ivar->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003192 Result += ")";
3193 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003194}
3195
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003196//===----------------------------------------------------------------------===//
3197// Meta Data Emission
3198//===----------------------------------------------------------------------===//
3199
Steve Naroff44e81222008-04-14 22:03:09 +00003200void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003201 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003202 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003203
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003204 // Explictly declared @interface's are already synthesized.
Steve Naroff7333b492009-04-20 20:09:33 +00003205 if (CDecl->isImplicitInterfaceDecl()) {
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003206 // FIXME: Implementation of a class with no @interface (legacy) doese not
3207 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00003208 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003209 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003210
Chris Lattnerc7b06752007-12-12 07:56:42 +00003211 // Build _objc_ivar_list metadata for classes ivars if needed
Douglas Gregor087dbf32009-04-23 03:23:08 +00003212 unsigned NumIvars = !IDecl->ivar_empty(*Context)
3213 ? IDecl->ivar_size(*Context)
Chris Lattnerec4979b2008-03-16 21:08:55 +00003214 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003215 if (NumIvars > 0) {
3216 static bool objc_ivar = false;
3217 if (!objc_ivar) {
3218 /* struct _objc_ivar {
3219 char *ivar_name;
3220 char *ivar_type;
3221 int ivar_offset;
3222 };
3223 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003224 Result += "\nstruct _objc_ivar {\n";
3225 Result += "\tchar *ivar_name;\n";
3226 Result += "\tchar *ivar_type;\n";
3227 Result += "\tint ivar_offset;\n";
3228 Result += "};\n";
3229
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003230 objc_ivar = true;
3231 }
3232
Steve Naroffc723eec2008-03-11 00:12:29 +00003233 /* struct {
3234 int ivar_count;
3235 struct _objc_ivar ivar_list[nIvars];
3236 };
3237 */
3238 Result += "\nstatic struct {\n";
3239 Result += "\tint ivar_count;\n";
3240 Result += "\tstruct _objc_ivar ivar_list[";
3241 Result += utostr(NumIvars);
3242 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003243 Result += IDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003244 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003245 "{\n\t";
3246 Result += utostr(NumIvars);
3247 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003248
Ted Kremenek42730c52008-01-07 19:49:32 +00003249 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor087dbf32009-04-23 03:23:08 +00003250 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
3251 if (!IDecl->ivar_empty(*Context)) {
3252 for (ObjCImplementationDecl::ivar_iterator
3253 IV = IDecl->ivar_begin(*Context),
3254 IVEnd = IDecl->ivar_end(*Context);
3255 IV != IVEnd; ++IV)
3256 IVars.push_back(*IV);
3257 IVI = IVars.begin();
3258 IVE = IVars.end();
Chris Lattnerc7b06752007-12-12 07:56:42 +00003259 } else {
3260 IVI = CDecl->ivar_begin();
3261 IVE = CDecl->ivar_end();
3262 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003263 Result += "\t,{{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003264 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003265 Result += "\", \"";
Steve Naroff450d2fc2009-04-29 16:37:50 +00003266 std::string TmpString, StrEncoding;
3267 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3268 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003269 Result += StrEncoding;
3270 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003271 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003272 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003273 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003274 Result += "\t ,{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003275 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003276 Result += "\", \"";
Steve Naroff450d2fc2009-04-29 16:37:50 +00003277 std::string TmpString, StrEncoding;
3278 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3279 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003280 Result += StrEncoding;
3281 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003282 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003283 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003284 }
3285
3286 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003287 }
3288
3289 // Build _objc_method_list for class's instance methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003290 llvm::SmallVector<ObjCMethodDecl *, 32>
3291 InstanceMethods(IDecl->instmeth_begin(*Context),
3292 IDecl->instmeth_end(*Context));
3293
3294 // If any of our property implementations have associated getters or
3295 // setters, produce metadata for them as well.
3296 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(*Context),
3297 PropEnd = IDecl->propimpl_end(*Context);
3298 Prop != PropEnd; ++Prop) {
3299 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3300 continue;
3301 if (!(*Prop)->getPropertyIvarDecl())
3302 continue;
3303 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3304 if (!PD)
3305 continue;
3306 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3307 InstanceMethods.push_back(Getter);
3308 if (PD->isReadOnly())
3309 continue;
3310 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3311 InstanceMethods.push_back(Setter);
3312 }
3313 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003314 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003315
3316 // Build _objc_method_list for class's class methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003317 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(*Context),
3318 IDecl->classmeth_end(*Context),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003319 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003320
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003321 // Protocols referenced in class declaration?
Steve Naroff450d2fc2009-04-29 16:37:50 +00003322 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3323 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003324
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003325 // Declaration of class/meta-class metadata
3326 /* struct _objc_class {
3327 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003328 const char *super_class_name;
3329 char *name;
3330 long version;
3331 long info;
3332 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003333 struct _objc_ivar_list *ivars;
3334 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003335 struct objc_cache *cache;
3336 struct objc_protocol_list *protocols;
3337 const char *ivar_layout;
3338 struct _objc_class_ext *ext;
3339 };
3340 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003341 static bool objc_class = false;
3342 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003343 Result += "\nstruct _objc_class {\n";
3344 Result += "\tstruct _objc_class *isa;\n";
3345 Result += "\tconst char *super_class_name;\n";
3346 Result += "\tchar *name;\n";
3347 Result += "\tlong version;\n";
3348 Result += "\tlong info;\n";
3349 Result += "\tlong instance_size;\n";
3350 Result += "\tstruct _objc_ivar_list *ivars;\n";
3351 Result += "\tstruct _objc_method_list *methods;\n";
3352 Result += "\tstruct objc_cache *cache;\n";
3353 Result += "\tstruct _objc_protocol_list *protocols;\n";
3354 Result += "\tconst char *ivar_layout;\n";
3355 Result += "\tstruct _objc_class_ext *ext;\n";
3356 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003357 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003358 }
3359
3360 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003361 ObjCInterfaceDecl *RootClass = 0;
3362 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003363 while (SuperClass) {
3364 RootClass = SuperClass;
3365 SuperClass = SuperClass->getSuperClass();
3366 }
3367 SuperClass = CDecl->getSuperClass();
3368
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003369 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003370 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003371 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003372 "{\n\t(struct _objc_class *)\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003373 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003374 Result += "\"";
3375
3376 if (SuperClass) {
3377 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003378 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003379 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003380 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003381 Result += "\"";
3382 }
3383 else {
3384 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003385 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003386 Result += "\"";
3387 }
Ted Kremenek42730c52008-01-07 19:49:32 +00003388 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003389 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003390 Result += ", 0,2, sizeof(struct _objc_class), 0";
Douglas Gregorcd19b572009-04-23 01:02:12 +00003391 if (IDecl->classmeth_begin(*Context) != IDecl->classmeth_end(*Context)) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003392 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003393 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003394 Result += "\n";
3395 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003396 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003397 Result += ", 0\n";
Chris Lattner179fd522009-02-20 18:18:36 +00003398 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003399 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003400 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003401 Result += ",0,0\n";
3402 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003403 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003404 Result += "\t,0,0,0,0\n";
3405 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003406
3407 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003408 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003409 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003410 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003411 "{\n\t&_OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003412 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003413 if (SuperClass) {
3414 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003415 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003416 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003417 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003418 Result += "\"";
3419 }
3420 else {
3421 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003422 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003423 Result += "\"";
3424 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003425 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003426 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003427 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003428 Result += ",0";
3429 else {
3430 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003431 Result += ",sizeof(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003432 Result += CDecl->getNameAsString();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003433 if (LangOpts.Microsoft)
3434 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003435 Result += ")";
3436 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003437 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003438 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003439 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003440 Result += "\n\t";
3441 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003442 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003443 Result += ",0";
Douglas Gregorcd19b572009-04-23 01:02:12 +00003444 if (IDecl->instmeth_begin(*Context) != IDecl->instmeth_end(*Context)) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003445 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003446 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003447 Result += ", 0\n\t";
3448 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003449 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003450 Result += ",0,0";
Chris Lattner179fd522009-02-20 18:18:36 +00003451 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003452 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003453 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003454 Result += ", 0,0\n";
3455 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003456 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003457 Result += ",0,0,0\n";
3458 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003459}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003460
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003461/// RewriteImplementations - This routine rewrites all method implementations
3462/// and emits meta-data.
3463
Steve Naroff21658f62008-11-13 20:07:04 +00003464void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003465 int ClsDefCount = ClassImplementation.size();
3466 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003467
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003468 // Rewrite implemented methods
3469 for (int i = 0; i < ClsDefCount; i++)
3470 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003471
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003472 for (int i = 0; i < CatDefCount; i++)
3473 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Naroff21658f62008-11-13 20:07:04 +00003474}
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003475
Steve Naroff21658f62008-11-13 20:07:04 +00003476void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3477 int ClsDefCount = ClassImplementation.size();
3478 int CatDefCount = CategoryImplementation.size();
3479
Steve Naroff5bf10222008-05-07 21:23:49 +00003480 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003481 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003482 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003483 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003484 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003485
3486 // For each implemented category, write out all its meta data.
3487 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003488 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff450d2fc2009-04-29 16:37:50 +00003489
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003490 // Write objc_symtab metadata
3491 /*
3492 struct _objc_symtab
3493 {
3494 long sel_ref_cnt;
3495 SEL *refs;
3496 short cls_def_cnt;
3497 short cat_def_cnt;
3498 void *defs[cls_def_cnt + cat_def_cnt];
3499 };
3500 */
3501
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003502 Result += "\nstruct _objc_symtab {\n";
3503 Result += "\tlong sel_ref_cnt;\n";
3504 Result += "\tSEL *refs;\n";
3505 Result += "\tshort cls_def_cnt;\n";
3506 Result += "\tshort cat_def_cnt;\n";
3507 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3508 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003509
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003510 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003511 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003512 Result += "\t0, 0, " + utostr(ClsDefCount)
3513 + ", " + utostr(CatDefCount) + "\n";
3514 for (int i = 0; i < ClsDefCount; i++) {
3515 Result += "\t,&_OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003516 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003517 Result += "\n";
3518 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003519
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003520 for (int i = 0; i < CatDefCount; i++) {
3521 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003522 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003523 Result += "_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003524 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003525 Result += "\n";
3526 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003527
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003528 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003529
3530 // Write objc_module metadata
3531
3532 /*
3533 struct _objc_module {
3534 long version;
3535 long size;
3536 const char *name;
3537 struct _objc_symtab *symtab;
3538 }
3539 */
3540
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003541 Result += "\nstruct _objc_module {\n";
3542 Result += "\tlong version;\n";
3543 Result += "\tlong size;\n";
3544 Result += "\tconst char *name;\n";
3545 Result += "\tstruct _objc_symtab *symtab;\n";
3546 Result += "};\n\n";
3547 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003548 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003549 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3550 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003551 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003552
3553 if (LangOpts.Microsoft) {
Steve Naroff450d2fc2009-04-29 16:37:50 +00003554 if (ProtocolExprDecls.size()) {
3555 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3556 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
3557 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
3558 E = ProtocolExprDecls.end(); I != E; ++I) {
3559 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3560 Result += (*I)->getNameAsString();
3561 Result += " = &_OBJC_PROTOCOL_";
3562 Result += (*I)->getNameAsString();
3563 Result += ";\n";
3564 }
3565 Result += "#pragma data_seg(pop)\n\n";
3566 }
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003567 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003568 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003569 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3570 Result += "&_OBJC_MODULES;\n";
3571 Result += "#pragma data_seg(pop)\n\n";
3572 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003573}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003574
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003575std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3576 const char *funcName,
3577 std::string Tag) {
3578 const FunctionType *AFT = CE->getFunctionType();
3579 QualType RT = AFT->getResultType();
3580 std::string StructRef = "struct " + Tag;
3581 std::string S = "static " + RT.getAsString() + " __" +
3582 funcName + "_" + "block_func_" + utostr(i);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003583
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003584 BlockDecl *BD = CE->getBlockDecl();
3585
Douglas Gregor4fa58902009-02-26 23:50:07 +00003586 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroff16478cf2009-02-02 17:19:26 +00003587 // No user-supplied arguments. Still need to pass in a pointer to the
3588 // block (to reference imported block decl refs).
3589 S += "(" + StructRef + " *__cself)";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003590 } else if (BD->param_empty()) {
3591 S += "(" + StructRef + " *__cself)";
3592 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003593 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003594 assert(FT && "SynthesizeBlockFunc: No function proto");
3595 S += '(';
3596 // first add the implicit argument.
3597 S += StructRef + " *__cself, ";
3598 std::string ParamStr;
3599 for (BlockDecl::param_iterator AI = BD->param_begin(),
3600 E = BD->param_end(); AI != E; ++AI) {
3601 if (AI != BD->param_begin()) S += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003602 ParamStr = (*AI)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003603 (*AI)->getType().getAsStringInternal(ParamStr);
3604 S += ParamStr;
3605 }
3606 if (FT->isVariadic()) {
3607 if (!BD->param_empty()) S += ", ";
3608 S += "...";
3609 }
3610 S += ')';
3611 }
3612 S += " {\n";
3613
3614 // Create local declarations to avoid rewriting all closure decl ref exprs.
3615 // First, emit a declaration for all "by ref" decls.
3616 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3617 E = BlockByRefDecls.end(); I != E; ++I) {
3618 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003619 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003620 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003621 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003622 }
3623 // Next, emit a declaration for all "by copy" declarations.
3624 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3625 E = BlockByCopyDecls.end(); I != E; ++I) {
3626 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003627 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003628 // Handle nested closure invocation. For example:
3629 //
3630 // void (^myImportedClosure)(void);
3631 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3632 //
3633 // void (^anotherClosure)(void);
3634 // anotherClosure = ^(void) {
3635 // myImportedClosure(); // import and invoke the closure
3636 // };
3637 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003638 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003639 S += "struct __block_impl *";
3640 else
3641 (*I)->getType().getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003642 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003643 }
3644 std::string RewrittenStr = RewrittenBlockExprs[CE];
3645 const char *cstr = RewrittenStr.c_str();
3646 while (*cstr++ != '{') ;
3647 S += cstr;
3648 S += "\n";
3649 return S;
3650}
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003651
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003652std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3653 const char *funcName,
3654 std::string Tag) {
3655 std::string StructRef = "struct " + Tag;
3656 std::string S = "static void __";
3657
3658 S += funcName;
3659 S += "_block_copy_" + utostr(i);
3660 S += "(" + StructRef;
3661 S += "*dst, " + StructRef;
3662 S += "*src) {";
3663 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3664 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003665 S += "_Block_object_assign((void*)&dst->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003666 S += (*I)->getNameAsString();
Steve Naroff1d56d9e2008-12-11 20:51:38 +00003667 S += ", (void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003668 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003669 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003670 }
3671 S += "\nstatic void __";
3672 S += funcName;
3673 S += "_block_dispose_" + utostr(i);
3674 S += "(" + StructRef;
3675 S += "*src) {";
3676 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3677 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003678 S += "_Block_object_dispose((void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003679 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003680 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003681 }
3682 S += "}\n";
3683 return S;
3684}
3685
3686std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3687 bool hasCopyDisposeHelpers) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003688 std::string S = "\nstruct " + Tag;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003689 std::string Constructor = " " + Tag;
3690
3691 S += " {\n struct __block_impl impl;\n";
3692
3693 if (hasCopyDisposeHelpers)
3694 S += " void *copy;\n void *dispose;\n";
3695
3696 Constructor += "(void *fp";
3697
3698 if (hasCopyDisposeHelpers)
3699 Constructor += ", void *copyHelp, void *disposeHelp";
3700
3701 if (BlockDeclRefs.size()) {
3702 // Output all "by copy" declarations.
3703 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3704 E = BlockByCopyDecls.end(); I != E; ++I) {
3705 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003706 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003707 std::string ArgName = "_" + FieldName;
3708 // Handle nested closure invocation. For example:
3709 //
3710 // void (^myImportedBlock)(void);
3711 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3712 //
3713 // void (^anotherBlock)(void);
3714 // anotherBlock = ^(void) {
3715 // myImportedBlock(); // import and invoke the closure
3716 // };
3717 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003718 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003719 S += "struct __block_impl *";
3720 Constructor += ", void *" + ArgName;
3721 } else {
3722 (*I)->getType().getAsStringInternal(FieldName);
3723 (*I)->getType().getAsStringInternal(ArgName);
3724 Constructor += ", " + ArgName;
3725 }
3726 S += FieldName + ";\n";
3727 }
3728 // Output all "by ref" declarations.
3729 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3730 E = BlockByRefDecls.end(); I != E; ++I) {
3731 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003732 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003733 std::string ArgName = "_" + FieldName;
3734 // Handle nested closure invocation. For example:
3735 //
3736 // void (^myImportedBlock)(void);
3737 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3738 //
3739 // void (^anotherBlock)(void);
3740 // anotherBlock = ^(void) {
3741 // myImportedBlock(); // import and invoke the closure
3742 // };
3743 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003744 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003745 S += "struct __block_impl *";
3746 Constructor += ", void *" + ArgName;
3747 } else {
3748 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3749 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3750 Constructor += ", " + ArgName;
3751 }
3752 S += FieldName + "; // by ref\n";
3753 }
3754 // Finish writing the constructor.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003755 Constructor += ", int flags=0) {\n";
Steve Naroff450d2fc2009-04-29 16:37:50 +00003756 if (GlobalVarDecl)
3757 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3758 else
3759 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3760 Constructor += " impl.Size = sizeof(";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003761 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3762
3763 if (hasCopyDisposeHelpers)
3764 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3765
3766 // Initialize all "by copy" arguments.
3767 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3768 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003769 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003770 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003771 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003772 Constructor += Name + " = (struct __block_impl *)_";
3773 else
3774 Constructor += Name + " = _";
3775 Constructor += Name + ";\n";
3776 }
3777 // Initialize all "by ref" arguments.
3778 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3779 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003780 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003781 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003782 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003783 Constructor += Name + " = (struct __block_impl *)_";
3784 else
3785 Constructor += Name + " = _";
3786 Constructor += Name + ";\n";
3787 }
3788 } else {
3789 // Finish writing the constructor.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003790 Constructor += ", int flags=0) {\n";
Steve Naroff450d2fc2009-04-29 16:37:50 +00003791 if (GlobalVarDecl)
3792 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3793 else
3794 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3795 Constructor += " impl.Size = sizeof(";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003796 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3797 if (hasCopyDisposeHelpers)
3798 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3799 }
3800 Constructor += " ";
3801 Constructor += "}\n";
3802 S += Constructor;
3803 S += "};\n";
3804 return S;
3805}
3806
3807void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3808 const char *FunName) {
3809 // Insert closures that were part of the function.
3810 for (unsigned i = 0; i < Blocks.size(); i++) {
3811
3812 CollectBlockDeclRefInfo(Blocks[i]);
3813
3814 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3815
3816 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3817 ImportedBlockDecls.size() > 0);
3818
3819 InsertText(FunLocStart, CI.c_str(), CI.size());
3820
3821 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3822
3823 InsertText(FunLocStart, CF.c_str(), CF.size());
3824
3825 if (ImportedBlockDecls.size()) {
3826 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3827 InsertText(FunLocStart, HF.c_str(), HF.size());
3828 }
3829
3830 BlockDeclRefs.clear();
3831 BlockByRefDecls.clear();
3832 BlockByCopyDecls.clear();
3833 BlockCallExprs.clear();
3834 ImportedBlockDecls.clear();
3835 }
3836 Blocks.clear();
3837 RewrittenBlockExprs.clear();
3838}
3839
3840void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3841 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003842 const char *FuncName = FD->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003843
3844 SynthesizeBlockLiterals(FunLocStart, FuncName);
3845}
3846
3847void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003848 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3849 //SourceLocation FunLocStart = MD->getLocStart();
3850 // FIXME: This hack works around a bug in Rewrite.InsertText().
3851 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner3a8f2942008-11-24 03:33:13 +00003852 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003853 // Convert colons to underscores.
3854 std::string::size_type loc = 0;
3855 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3856 FuncName.replace(loc, 1, "_");
3857
3858 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3859}
3860
3861void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3862 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3863 CI != E; ++CI)
3864 if (*CI) {
3865 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3866 GetBlockDeclRefExprs(CBE->getBody());
3867 else
3868 GetBlockDeclRefExprs(*CI);
3869 }
3870 // Handle specific things.
3871 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3872 // FIXME: Handle enums.
3873 if (!isa<FunctionDecl>(CDRE->getDecl()))
3874 BlockDeclRefs.push_back(CDRE);
3875 return;
3876}
3877
3878void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3879 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3880 CI != E; ++CI)
3881 if (*CI) {
3882 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3883 GetBlockCallExprs(CBE->getBody());
3884 else
3885 GetBlockCallExprs(*CI);
3886 }
3887
3888 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3889 if (CE->getCallee()->getType()->isBlockPointerType()) {
3890 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3891 }
3892 }
3893 return;
3894}
3895
Steve Naroff85eb17b2008-10-30 10:07:53 +00003896Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003897 // Navigate to relevant type information.
3898 const char *closureName = 0;
3899 const BlockPointerType *CPT = 0;
3900
3901 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003902 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003903 CPT = DRE->getType()->getAsBlockPointerType();
3904 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003905 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003906 CPT = CDRE->getType()->getAsBlockPointerType();
3907 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003908 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003909 CPT = MExpr->getType()->getAsBlockPointerType();
3910 } else {
3911 assert(1 && "RewriteBlockClass: Bad type");
3912 }
3913 assert(CPT && "RewriteBlockClass: Bad type");
3914 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3915 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00003916 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003917 // FTP will be null for closures that don't take arguments.
3918
Steve Naroff85eb17b2008-10-30 10:07:53 +00003919 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3920 SourceLocation(),
3921 &Context->Idents.get("__block_impl"));
3922 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003923
Steve Naroff85eb17b2008-10-30 10:07:53 +00003924 // Generate a funky cast.
3925 llvm::SmallVector<QualType, 8> ArgTypes;
3926
3927 // Push the block argument type.
3928 ArgTypes.push_back(PtrBlock);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003929 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003930 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff85eb17b2008-10-30 10:07:53 +00003931 E = FTP->arg_type_end(); I && (I != E); ++I) {
3932 QualType t = *I;
3933 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00003934 if (isTopLevelBlockPointerType(t)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003935 const BlockPointerType *BPT = t->getAsBlockPointerType();
3936 t = Context->getPointerType(BPT->getPointeeType());
3937 }
3938 ArgTypes.push_back(t);
3939 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003940 }
Steve Naroff85eb17b2008-10-30 10:07:53 +00003941 // Now do the pointer to function cast.
3942 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3943 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3944
3945 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003946
Ted Kremenek0c97e042009-02-07 01:47:29 +00003947 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3948 PtrBlock, SourceLocation(),
3949 SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003950 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003951 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3952 BlkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003953 //PE->dump();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003954
Douglas Gregor8acb7272008-12-11 16:49:14 +00003955 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3956 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003957 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek0c97e042009-02-07 01:47:29 +00003958 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3959 FD->getType());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003960
Ted Kremenek0c97e042009-02-07 01:47:29 +00003961 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3962 PtrToFuncCastType,
3963 SourceLocation(),
3964 SourceLocation());
3965 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003966
3967 llvm::SmallVector<Expr*, 8> BlkExprs;
3968 // Add the implicit argument.
3969 BlkExprs.push_back(BlkCast);
3970 // Add the user arguments.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003971 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3972 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003973 BlkExprs.push_back(*I);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003974 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00003975 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3976 BlkExprs.size(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00003977 Exp->getType(), SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003978 return CE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003979}
3980
3981void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003982 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3983 ReplaceStmt(Exp, BlockCall);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003984}
3985
Steve Naroff450d2fc2009-04-29 16:37:50 +00003986// We need to return the rewritten expression to handle cases where the
3987// BlockDeclRefExpr is embedded in another expression being rewritten.
3988// For example:
3989//
3990// int main() {
3991// __block Foo *f;
3992// __block int i;
3993//
3994// void (^myblock)() = ^() {
3995// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3996// i = 77;
3997// };
3998//}
3999Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004000 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004001 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroff16478cf2009-02-02 17:19:26 +00004002 Context->getPointerType(BDRE->getType()),
4003 SourceLocation());
4004 // Need parens to enforce precedence.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004005 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroff16478cf2009-02-02 17:19:26 +00004006 ReplaceStmt(BDRE, PE);
Steve Naroff450d2fc2009-04-29 16:37:50 +00004007 return PE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004008}
4009
Steve Naroff7f1412d2008-11-03 23:29:32 +00004010void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4011 SourceLocation LocStart = CE->getLParenLoc();
4012 SourceLocation LocEnd = CE->getRParenLoc();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004013
4014 // Need to avoid trying to rewrite synthesized casts.
4015 if (LocStart.isInvalid())
4016 return;
Steve Naroff1c53c022008-11-03 11:20:24 +00004017 // Need to avoid trying to rewrite casts contained in macros.
4018 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4019 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004020
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004021 const char *startBuf = SM->getCharacterData(LocStart);
4022 const char *endBuf = SM->getCharacterData(LocEnd);
4023
4024 // advance the location to startArgList.
4025 const char *argPtr = startBuf;
4026
4027 while (*argPtr++ && (argPtr < endBuf)) {
4028 switch (*argPtr) {
4029 case '^':
4030 // Replace the '^' with '*'.
4031 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4032 ReplaceText(LocStart, 1, "*", 1);
4033 break;
4034 }
4035 }
4036 return;
4037}
4038
4039void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4040 SourceLocation DeclLoc = FD->getLocation();
4041 unsigned parenCount = 0;
4042
4043 // We have 1 or more arguments that have closure pointers.
4044 const char *startBuf = SM->getCharacterData(DeclLoc);
4045 const char *startArgList = strchr(startBuf, '(');
4046
4047 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4048
4049 parenCount++;
4050 // advance the location to startArgList.
4051 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4052 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4053
4054 const char *argPtr = startArgList;
4055
4056 while (*argPtr++ && parenCount) {
4057 switch (*argPtr) {
4058 case '^':
4059 // Replace the '^' with '*'.
4060 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4061 ReplaceText(DeclLoc, 1, "*", 1);
4062 break;
4063 case '(':
4064 parenCount++;
4065 break;
4066 case ')':
4067 parenCount--;
4068 break;
4069 }
4070 }
4071 return;
4072}
4073
4074bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004075 const FunctionProtoType *FTP;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004076 const PointerType *PT = QT->getAsPointerType();
4077 if (PT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004078 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004079 } else {
4080 const BlockPointerType *BPT = QT->getAsBlockPointerType();
4081 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00004082 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004083 }
4084 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004085 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004086 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +00004087 if (isTopLevelBlockPointerType(*I))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004088 return true;
4089 }
4090 return false;
4091}
4092
Ted Kremenek0c97e042009-02-07 01:47:29 +00004093void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4094 const char *&RParen) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004095 const char *argPtr = strchr(Name, '(');
4096 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4097
4098 LParen = argPtr; // output the start.
4099 argPtr++; // skip past the left paren.
4100 unsigned parenCount = 1;
4101
4102 while (*argPtr && parenCount) {
4103 switch (*argPtr) {
4104 case '(': parenCount++; break;
4105 case ')': parenCount--; break;
4106 default: break;
4107 }
4108 if (parenCount) argPtr++;
4109 }
4110 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4111 RParen = argPtr; // output the end
4112}
4113
4114void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4115 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4116 RewriteBlockPointerFunctionArgs(FD);
4117 return;
4118 }
4119 // Handle Variables and Typedefs.
4120 SourceLocation DeclLoc = ND->getLocation();
4121 QualType DeclT;
4122 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4123 DeclT = VD->getType();
4124 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4125 DeclT = TDD->getUnderlyingType();
4126 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4127 DeclT = FD->getType();
4128 else
4129 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4130
4131 const char *startBuf = SM->getCharacterData(DeclLoc);
4132 const char *endBuf = startBuf;
4133 // scan backward (from the decl location) for the end of the previous decl.
4134 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4135 startBuf--;
4136
4137 // *startBuf != '^' if we are dealing with a pointer to function that
4138 // may take block argument types (which will be handled below).
4139 if (*startBuf == '^') {
4140 // Replace the '^' with '*', computing a negative offset.
4141 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4142 ReplaceText(DeclLoc, 1, "*", 1);
4143 }
4144 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4145 // Replace the '^' with '*' for arguments.
4146 DeclLoc = ND->getLocation();
4147 startBuf = SM->getCharacterData(DeclLoc);
4148 const char *argListBegin, *argListEnd;
4149 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4150 while (argListBegin < argListEnd) {
4151 if (*argListBegin == '^') {
4152 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4153 ReplaceText(CaretLoc, 1, "*", 1);
4154 }
4155 argListBegin++;
4156 }
4157 }
4158 return;
4159}
4160
4161void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4162 // Add initializers for any closure decl refs.
4163 GetBlockDeclRefExprs(Exp->getBody());
4164 if (BlockDeclRefs.size()) {
4165 // Unique all "by copy" declarations.
4166 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4167 if (!BlockDeclRefs[i]->isByRef())
4168 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4169 // Unique all "by ref" declarations.
4170 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4171 if (BlockDeclRefs[i]->isByRef()) {
4172 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4173 }
4174 // Find any imported blocks...they will need special attention.
4175 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff1d56d9e2008-12-11 20:51:38 +00004176 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroffe59c8b12008-11-13 17:40:07 +00004177 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004178 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4179 }
4180 }
4181}
4182
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004183FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4184 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004185 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004186 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor1f88aa72009-02-25 16:33:18 +00004187 ID, FType, FunctionDecl::Extern, false,
4188 false);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004189}
4190
Steve Naroff80c54752008-10-29 18:15:37 +00004191Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004192 Blocks.push_back(Exp);
4193
4194 CollectBlockDeclRefInfo(Exp);
4195 std::string FuncName;
4196
4197 if (CurFunctionDef)
Chris Lattner3a8f2942008-11-24 03:33:13 +00004198 FuncName = CurFunctionDef->getNameAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004199 else if (CurMethodDef) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00004200 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004201 // Convert colons to underscores.
4202 std::string::size_type loc = 0;
4203 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4204 FuncName.replace(loc, 1, "_");
Steve Naroff80c54752008-10-29 18:15:37 +00004205 } else if (GlobalVarDecl)
Chris Lattner271d4c22008-11-24 05:29:24 +00004206 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004207
4208 std::string BlockNumber = utostr(Blocks.size()-1);
4209
4210 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4211 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4212
4213 // Get a pointer to the function type so we can cast appropriately.
4214 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4215
4216 FunctionDecl *FD;
4217 Expr *NewRep;
4218
4219 // Simulate a contructor call...
4220 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004221 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004222
4223 llvm::SmallVector<Expr*, 4> InitExprs;
4224
Steve Naroffd0419d62008-10-29 21:23:59 +00004225 // Initialize the block function.
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004226 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004227 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4228 SourceLocation());
4229 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4230 Context->VoidPtrTy, SourceLocation(),
4231 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004232 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004233
4234 if (ImportedBlockDecls.size()) {
4235 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004236 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004237 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4238 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4239 Context->VoidPtrTy, SourceLocation(),
4240 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004241 InitExprs.push_back(castExpr);
4242
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004243 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004244 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004245 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4246 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4247 Context->VoidPtrTy, SourceLocation(),
4248 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004249 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004250 }
4251 // Add initializers for any closure decl refs.
4252 if (BlockDeclRefs.size()) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004253 Expr *Exp;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004254 // Output all "by copy" declarations.
4255 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4256 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004257 if (isObjCType((*I)->getType())) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004258 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004259 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004260 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffd896f4b2008-12-11 21:05:33 +00004261 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004262 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004263 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4264 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4265 Context->VoidPtrTy, SourceLocation(),
4266 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004267 } else {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004268 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004269 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004270 }
Steve Naroffd0419d62008-10-29 21:23:59 +00004271 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004272 }
4273 // Output all "by ref" declarations.
4274 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4275 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004276 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004277 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4278 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Naroffd0419d62008-10-29 21:23:59 +00004279 Context->getPointerType(Exp->getType()),
4280 SourceLocation());
Steve Naroff362c7562008-11-14 21:36:12 +00004281 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004282 }
4283 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00004284 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4285 FType, SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004286 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004287 Context->getPointerType(NewRep->getType()),
4288 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004289 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4290 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004291 BlockDeclRefs.clear();
4292 BlockByRefDecls.clear();
4293 BlockByCopyDecls.clear();
4294 ImportedBlockDecls.clear();
4295 return NewRep;
4296}
4297
4298//===----------------------------------------------------------------------===//
4299// Function Body / Expression rewriting
4300//===----------------------------------------------------------------------===//
4301
Steve Naroff0e948412008-12-04 16:24:46 +00004302// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4303// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4304// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4305// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4306// Since the rewriter isn't capable of rewriting rewritten code, it's important
4307// we get this right.
4308void RewriteObjC::CollectPropertySetters(Stmt *S) {
4309 // Perform a bottom up traversal of all children.
4310 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4311 CI != E; ++CI)
4312 if (*CI)
4313 CollectPropertySetters(*CI);
4314
4315 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4316 if (BinOp->isAssignmentOp()) {
4317 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4318 PropSetters[PRE] = BinOp;
4319 }
4320 }
4321}
4322
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004323Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4324 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4325 isa<DoStmt>(S) || isa<ForStmt>(S))
4326 Stmts.push_back(S);
4327 else if (isa<ObjCForCollectionStmt>(S)) {
4328 Stmts.push_back(S);
4329 ObjCBcLabelNo.push_back(++BcLabelCount);
4330 }
4331
4332 SourceRange OrigStmtRange = S->getSourceRange();
4333
4334 // Perform a bottom up rewrite of all children.
4335 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4336 CI != E; ++CI)
4337 if (*CI) {
4338 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4339 if (newStmt)
4340 *CI = newStmt;
4341 }
4342
4343 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4344 // Rewrite the block body in place.
4345 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4346
4347 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff80c54752008-10-29 18:15:37 +00004348 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4349 RewrittenBlockExprs[BE] = Str;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004350
4351 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4352 //blockTranscribed->dump();
Steve Naroff80c54752008-10-29 18:15:37 +00004353 ReplaceStmt(S, blockTranscribed);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004354 return blockTranscribed;
4355 }
4356 // Handle specific things.
4357 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4358 return RewriteAtEncode(AtEncode);
4359
4360 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4361 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4362
Steve Naroff0e948412008-12-04 16:24:46 +00004363 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4364 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4365 if (BinOp) {
4366 // Because the rewriter doesn't allow us to rewrite rewritten code,
4367 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffedb4bc92008-12-09 12:56:34 +00004368 DisableReplaceStmt = true;
4369 // Save the source range. Even if we disable the replacement, the
4370 // rewritten node will have been inserted into the tree. If the synthesized
4371 // node is at the 'end', the rewriter will fail. Consider this:
4372 // self.errorHandler = handler ? handler :
4373 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4374 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff0e948412008-12-04 16:24:46 +00004375 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffedb4bc92008-12-09 12:56:34 +00004376 DisableReplaceStmt = false;
Steve Naroff102c3f22008-12-04 23:50:32 +00004377 //
4378 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4379 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4380 // to see the original expression). Consider this example:
4381 //
4382 // Foo *obj1, *obj2;
4383 //
4384 // obj1.i = [obj2 rrrr];
4385 //
4386 // 'BinOp' for the previous expression looks like:
4387 //
4388 // (BinaryOperator 0x231ccf0 'int' '='
4389 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4390 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4391 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4392 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4393 //
4394 // 'newStmt' represents the rewritten message expression. For example:
4395 //
4396 // (CallExpr 0x231d300 'id':'struct objc_object *'
4397 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4398 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4399 // (CStyleCastExpr 0x231d220 'void *'
4400 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4401 //
4402 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4403 // can be used as the setter argument. ReplaceStmt() will still 'see'
4404 // the original RHS (since we haven't altered BinOp).
4405 //
4406 // This implies the Rewrite* routines can no longer delete the original
4407 // node. As a result, we now leak the original AST nodes.
4408 //
Steve Naroffedb4bc92008-12-09 12:56:34 +00004409 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff0e948412008-12-04 16:24:46 +00004410 } else {
4411 return RewritePropertyGetter(PropRefExpr);
Steve Narofff6ce8a12008-12-03 00:56:33 +00004412 }
4413 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004414 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4415 return RewriteAtSelector(AtSelector);
4416
4417 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4418 return RewriteObjCStringLiteral(AtString);
4419
4420 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff0e948412008-12-04 16:24:46 +00004421#if 0
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004422 // Before we rewrite it, put the original message expression in a comment.
4423 SourceLocation startLoc = MessExpr->getLocStart();
4424 SourceLocation endLoc = MessExpr->getLocEnd();
4425
4426 const char *startBuf = SM->getCharacterData(startLoc);
4427 const char *endBuf = SM->getCharacterData(endLoc);
4428
4429 std::string messString;
4430 messString += "// ";
4431 messString.append(startBuf, endBuf-startBuf+1);
4432 messString += "\n";
4433
4434 // FIXME: Missing definition of
4435 // InsertText(clang::SourceLocation, char const*, unsigned int).
4436 // InsertText(startLoc, messString.c_str(), messString.size());
4437 // Tried this, but it didn't work either...
4438 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff0e948412008-12-04 16:24:46 +00004439#endif
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004440 return RewriteMessageExpr(MessExpr);
4441 }
4442
4443 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4444 return RewriteObjCTryStmt(StmtTry);
4445
4446 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4447 return RewriteObjCSynchronizedStmt(StmtTry);
4448
4449 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4450 return RewriteObjCThrowStmt(StmtThrow);
4451
4452 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4453 return RewriteObjCProtocolExpr(ProtocolExp);
4454
4455 if (ObjCForCollectionStmt *StmtForCollection =
4456 dyn_cast<ObjCForCollectionStmt>(S))
4457 return RewriteObjCForCollectionStmt(StmtForCollection,
4458 OrigStmtRange.getEnd());
4459 if (BreakStmt *StmtBreakStmt =
4460 dyn_cast<BreakStmt>(S))
4461 return RewriteBreakStmt(StmtBreakStmt);
4462 if (ContinueStmt *StmtContinueStmt =
4463 dyn_cast<ContinueStmt>(S))
4464 return RewriteContinueStmt(StmtContinueStmt);
4465
4466 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4467 // and cast exprs.
4468 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4469 // FIXME: What we're doing here is modifying the type-specifier that
4470 // precedes the first Decl. In the future the DeclGroup should have
4471 // a separate type-specifier that we can rewrite.
4472 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4473
4474 // Blocks rewrite rules.
4475 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4476 DI != DE; ++DI) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00004477 Decl *SD = *DI;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004478 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004479 if (isTopLevelBlockPointerType(ND->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004480 RewriteBlockPointerDecl(ND);
4481 else if (ND->getType()->isFunctionPointerType())
4482 CheckFunctionPointerDecl(ND->getType(), ND);
4483 }
4484 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004485 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004486 RewriteBlockPointerDecl(TD);
4487 else if (TD->getUnderlyingType()->isFunctionPointerType())
4488 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4489 }
4490 }
4491 }
4492
4493 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4494 RewriteObjCQualifiedInterfaceTypes(CE);
4495
4496 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4497 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4498 assert(!Stmts.empty() && "Statement stack is empty");
4499 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4500 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4501 && "Statement stack mismatch");
4502 Stmts.pop_back();
4503 }
4504 // Handle blocks rewriting.
4505 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4506 if (BDRE->isByRef())
Steve Naroff450d2fc2009-04-29 16:37:50 +00004507 return RewriteBlockDeclRefExpr(BDRE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004508 }
4509 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00004510 if (CE->getCallee()->getType()->isBlockPointerType()) {
4511 Stmt *BlockCall = SynthesizeBlockCall(CE);
4512 ReplaceStmt(S, BlockCall);
4513 return BlockCall;
4514 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004515 }
Steve Naroff7f1412d2008-11-03 23:29:32 +00004516 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004517 RewriteCastExpr(CE);
4518 }
4519#if 0
4520 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004521 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004522 // Get the new text.
4523 std::string SStr;
4524 llvm::raw_string_ostream Buf(SStr);
4525 Replacement->printPretty(Buf);
4526 const std::string &Str = Buf.str();
4527
4528 printf("CAST = %s\n", &Str[0]);
4529 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4530 delete S;
4531 return Replacement;
4532 }
4533#endif
4534 // Return this stmt unmodified.
4535 return S;
4536}
4537
4538/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4539/// main file of the input.
4540void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4541 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffee8d4972008-12-17 00:20:22 +00004542 if (FD->isOverloadedOperator())
4543 return;
4544
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004545 // Since function prototypes don't have ParmDecl's, we check the function
4546 // prototype. This enables us to rewrite function declarations and
4547 // definitions using the same code.
Douglas Gregor4fa58902009-02-26 23:50:07 +00004548 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004549
Sebastian Redlbc9ef252009-04-26 20:35:05 +00004550 // FIXME: If this should support Obj-C++, support CXXTryStmt
4551 if (CompoundStmt *Body = FD->getCompoundBody(*Context)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004552 CurFunctionDef = FD;
Steve Naroff0e948412008-12-04 16:24:46 +00004553 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004554 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004555 Body =
4556 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4557 FD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004558 CurrentBody = 0;
4559 if (PropParentMap) {
4560 delete PropParentMap;
4561 PropParentMap = 0;
4562 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004563 // This synthesizes and inserts the block "impl" struct, invoke function,
4564 // and any copy/dispose helper functions.
4565 InsertBlockLiteralsWithinFunction(FD);
4566 CurFunctionDef = 0;
4567 }
4568 return;
4569 }
4570 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Ted Kremenek30916072009-03-12 18:33:24 +00004571 if (CompoundStmt *Body = MD->getBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004572 CurMethodDef = MD;
Steve Naroff0e948412008-12-04 16:24:46 +00004573 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004574 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004575 Body =
4576 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4577 MD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004578 CurrentBody = 0;
4579 if (PropParentMap) {
4580 delete PropParentMap;
4581 PropParentMap = 0;
4582 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004583 InsertBlockLiteralsWithinMethod(MD);
4584 CurMethodDef = 0;
4585 }
4586 }
4587 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4588 ClassImplementation.push_back(CI);
4589 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4590 CategoryImplementation.push_back(CI);
4591 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4592 RewriteForwardClassDecl(CD);
4593 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4594 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffd896f4b2008-12-11 21:05:33 +00004595 if (isTopLevelBlockPointerType(VD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004596 RewriteBlockPointerDecl(VD);
Steve Naroff80c54752008-10-29 18:15:37 +00004597 else if (VD->getType()->isFunctionPointerType()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004598 CheckFunctionPointerDecl(VD->getType(), VD);
4599 if (VD->getInit()) {
Steve Naroff7f1412d2008-11-03 23:29:32 +00004600 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004601 RewriteCastExpr(CE);
4602 }
4603 }
4604 }
Steve Naroff80c54752008-10-29 18:15:37 +00004605 if (VD->getInit()) {
4606 GlobalVarDecl = VD;
Steve Naroff0e948412008-12-04 16:24:46 +00004607 CollectPropertySetters(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004608 CurrentBody = VD->getInit();
Steve Naroff80c54752008-10-29 18:15:37 +00004609 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004610 CurrentBody = 0;
4611 if (PropParentMap) {
4612 delete PropParentMap;
4613 PropParentMap = 0;
4614 }
Douglas Gregor24afd4a2008-11-17 14:58:09 +00004615 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004616 VD->getNameAsCString());
Steve Naroff80c54752008-10-29 18:15:37 +00004617 GlobalVarDecl = 0;
4618
4619 // This is needed for blocks.
Steve Naroff7f1412d2008-11-03 23:29:32 +00004620 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff80c54752008-10-29 18:15:37 +00004621 RewriteCastExpr(CE);
4622 }
4623 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004624 return;
4625 }
4626 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004627 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004628 RewriteBlockPointerDecl(TD);
4629 else if (TD->getUnderlyingType()->isFunctionPointerType())
4630 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4631 return;
4632 }
4633 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4634 if (RD->isDefinition()) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004635 for (RecordDecl::field_iterator i = RD->field_begin(*Context),
4636 e = RD->field_end(*Context); i != e; ++i) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004637 FieldDecl *FD = *i;
Steve Naroffd896f4b2008-12-11 21:05:33 +00004638 if (isTopLevelBlockPointerType(FD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004639 RewriteBlockPointerDecl(FD);
4640 }
4641 }
4642 return;
4643 }
4644 // Nothing yet.
4645}
4646
Chris Lattner2a594d02009-03-28 04:11:33 +00004647void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004648 // Get the top-level buffer that this corresponds to.
4649
4650 // Rewrite tabs if we care.
4651 //RewriteTabs();
4652
4653 if (Diags.hasErrorOccurred())
4654 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004655
4656 RewriteInclude();
4657
Steve Naroff450d2fc2009-04-29 16:37:50 +00004658 // Here's a great place to add any extra declarations that may be needed.
4659 // Write out meta data for each @protocol(<expr>).
4660 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4661 E = ProtocolExprDecls.end(); I != E; ++I)
4662 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4663
Chris Lattnerf4f776a2009-01-17 06:22:33 +00004664 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004665 Preamble.c_str(), Preamble.size(), false);
Steve Naroff901d8fd2008-11-14 14:10:01 +00004666 if (ClassImplementation.size() || CategoryImplementation.size())
4667 RewriteImplementations();
Steve Naroff450d2fc2009-04-29 16:37:50 +00004668
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004669 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4670 // we are done.
4671 if (const RewriteBuffer *RewriteBuf =
4672 Rewrite.getRewriteBufferFor(MainFileID)) {
4673 //printf("Changed:\n");
4674 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4675 } else {
4676 fprintf(stderr, "No changes\n");
4677 }
Steve Naroff21658f62008-11-13 20:07:04 +00004678
Steve Naroff450d2fc2009-04-29 16:37:50 +00004679 if (ClassImplementation.size() || CategoryImplementation.size() ||
4680 ProtocolExprDecls.size()) {
Steve Naroff901d8fd2008-11-14 14:10:01 +00004681 // Rewrite Objective-c meta data*
4682 std::string ResultStr;
4683 SynthesizeMetaDataIntoBuffer(ResultStr);
4684 // Emit metadata.
4685 *OutFile << ResultStr;
4686 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004687 OutFile->flush();
4688}
4689