blob: ec0018a11cbb91e971ecc432f57c6fe9cc8a3317 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000019#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000020#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000021#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000022#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000023#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000024#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000025#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000026#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000027#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000028#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000029#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000031#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000032using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000033using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034
Steve Naroff0113c9d2008-01-28 21:34:52 +000035static llvm::cl::opt<bool>
36SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
37 llvm::cl::desc("Silence ObjC rewriting warnings"));
38
Chris Lattner77cd2a02007-10-11 00:43:27 +000039namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000040 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000041 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000042 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000043 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000044 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000045 unsigned TryFinallyContainsReturnDiag;
46
Chris Lattner01c57482007-10-17 22:35:30 +000047 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000048 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000049 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000050 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000051 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000052 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000053
Ted Kremeneka526c5c2008-01-07 19:49:32 +000054 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
55 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
56 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000057 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000058 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
59 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000060 llvm::SmallVector<Stmt *, 32> Stmts;
61 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000062
Steve Naroffd82a9ab2008-03-15 00:55:56 +000063 unsigned NumObjCStringLiterals;
64
Steve Naroffebf2b562007-10-23 23:50:29 +000065 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000066 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000067 FunctionDecl *MsgSendStretFunctionDecl;
68 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000069 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000070 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000071 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000072 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000073 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000074 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000075 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000076
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000078 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000079 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000080
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000081 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000082 int BcLabelCount;
83
Steve Naroff874e2322007-11-15 10:28:18 +000084 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000085 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000086 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000087 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000088
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000089 // Needed for header files being rewritten
90 bool IsHeader;
91
Steve Naroffa7b402d2008-03-28 22:26:09 +000092 std::string InFileName;
93 std::string OutFileName;
94
Steve Naroffba92b2e2008-03-27 22:29:16 +000095 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000096
97 // Block expressions.
98 llvm::SmallVector<BlockExpr *, 32> Blocks;
99 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
100 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +0000101
Steve Naroff54055232008-10-27 17:20:55 +0000102 // Block related declarations.
103 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
104 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
105 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
106
107 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
108
Steve Naroffc77a6362008-12-04 16:24:46 +0000109 // This maps a property to it's assignment statement.
110 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000111 // This maps a property to it's synthesied message expression.
112 // This allows us to rewrite chained getters (e.g. o.a.b.c).
113 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
114
Steve Naroff4c3580e2008-12-04 23:50:32 +0000115 // This maps an original source AST to it's rewritten form. This allows
116 // us to avoid rewriting the same node twice (which is very uncommon).
117 // This is needed to support some of the exotic property rewriting.
118 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000119
Steve Naroff54055232008-10-27 17:20:55 +0000120 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000121 VarDecl *GlobalVarDecl;
122
Steve Naroffb619d952008-12-09 12:56:34 +0000123 bool DisableReplaceStmt;
124
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000125 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000126 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000127 virtual void Initialize(ASTContext &context);
128
129 virtual void InitializeTU(TranslationUnit &TU) {
130 TU.SetOwnsDecls(false);
131 Initialize(TU.getContext());
132 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000133
Chris Lattner8a12c272007-10-11 18:38:32 +0000134
Chris Lattnerf04da132007-10-24 17:06:59 +0000135 // Top Level Driver code.
136 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000137 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000138 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000139 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000140
141 ~RewriteObjC() {}
142
143 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000144
145 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000146 Stmt *ReplacingStmt = ReplacedNodes[Old];
147
148 if (ReplacingStmt)
149 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000150
Steve Naroffb619d952008-12-09 12:56:34 +0000151 if (DisableReplaceStmt)
152 return; // Used when rewriting the assignment of a property setter.
153
Steve Naroff4c3580e2008-12-04 23:50:32 +0000154 // If replacement succeeded or warning disabled return with no warning.
155 if (!Rewrite.ReplaceStmt(Old, New)) {
156 ReplacedNodes[Old] = New;
157 return;
158 }
159 if (SilenceRewriteMacroWarning)
160 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000161 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
162 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000163 }
Steve Naroffb619d952008-12-09 12:56:34 +0000164
165 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
166 // Measaure the old text.
167 int Size = Rewrite.getRangeSize(SrcRange);
168 if (Size == -1) {
169 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
170 << Old->getSourceRange();
171 return;
172 }
173 // Get the new text.
174 std::string SStr;
175 llvm::raw_string_ostream S(SStr);
176 New->printPretty(S);
177 const std::string &Str = S.str();
178
179 // If replacement succeeded or warning disabled return with no warning.
180 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
188 }
189
Steve Naroffba92b2e2008-03-27 22:29:16 +0000190 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
191 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000192 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000193 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000194 SilenceRewriteMacroWarning)
195 return;
196
197 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
198 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000199
Chris Lattneraadaf782008-01-31 19:51:04 +0000200 void RemoveText(SourceLocation Loc, unsigned StrLen) {
201 // If removal succeeded or warning disabled return with no warning.
202 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
203 return;
204
205 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
206 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000207
Chris Lattneraadaf782008-01-31 19:51:04 +0000208 void ReplaceText(SourceLocation Start, unsigned OrigLength,
209 const char *NewStr, unsigned NewLength) {
210 // If removal succeeded or warning disabled return with no warning.
211 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
212 SilenceRewriteMacroWarning)
213 return;
214
215 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
216 }
217
Chris Lattnerf04da132007-10-24 17:06:59 +0000218 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000219 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000220 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000221 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000222 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000223 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
224 ObjCImplementationDecl *IMD,
225 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000227 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000228 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
229 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
230 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
231 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
232 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000233 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000234 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000235 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000236 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000237 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000238 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000239 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000240 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000241 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000242
Chris Lattnerf04da132007-10-24 17:06:59 +0000243 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000244 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000245 void CollectPropertySetters(Stmt *S);
246
Steve Naroff8599e7a2008-12-08 16:43:47 +0000247 Stmt *CurrentBody;
248 ParentMap *PropParentMap; // created lazily.
249
Chris Lattnere64b7772007-10-24 16:57:36 +0000250 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000251 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000252 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffb619d952008-12-09 12:56:34 +0000253 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
254 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000255 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000256 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000257 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000258 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000259 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000261 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000262 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
263 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
264 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000265 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
266 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000267 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
268 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000269 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000270 Stmt *RewriteBreakStmt(BreakStmt *S);
271 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000272 void SynthCountByEnumWithState(std::string &buf);
273
Steve Naroff09b266e2007-10-30 23:14:51 +0000274 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000275 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000276 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000277 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000278 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000279 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000280 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000281 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000282 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000283 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000284
Chris Lattnerf04da132007-10-24 17:06:59 +0000285 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000287 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000288
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000290 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000291
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000292 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
293 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000294 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000295 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000296 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000297 const char *ClassName,
298 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000299
Chris Lattner780f3292008-07-21 21:32:27 +0000300 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
301 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000302 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000303 const char *ClassName,
304 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000306 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
308 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000309 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000310 void RewriteImplementations();
311 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000312
313 // Block rewriting.
314 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
315 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
316
317 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
318 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
319
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000320 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000321 void RewriteBlockCall(CallExpr *Exp);
322 void RewriteBlockPointerDecl(NamedDecl *VD);
323 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
324 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
325
326 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
327 const char *funcName, std::string Tag);
328 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
329 const char *funcName, std::string Tag);
330 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
331 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000332 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000333 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
334 const char *FunName);
335
336 void CollectBlockDeclRefInfo(BlockExpr *Exp);
337 void GetBlockCallExprs(Stmt *S);
338 void GetBlockDeclRefExprs(Stmt *S);
339
340 // We avoid calling Type::isBlockPointerType(), since it operates on the
341 // canonical type. We only care if the top-level type is a closure pointer.
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000342 bool isTopLevelBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
Steve Naroff54055232008-10-27 17:20:55 +0000343
344 // FIXME: This predicate seems like it would be useful to add to ASTContext.
345 bool isObjCType(QualType T) {
346 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
347 return false;
348
349 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
350
351 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
352 OCT == Context->getCanonicalType(Context->getObjCClassType()))
353 return true;
354
355 if (const PointerType *PT = OCT->getAsPointerType()) {
356 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
357 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
358 return true;
359 }
360 return false;
361 }
362 bool PointerTypeTakesAnyBlockArguments(QualType QT);
363 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000364 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000365
366 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000367 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000368 };
369}
370
Steve Naroff54055232008-10-27 17:20:55 +0000371void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
372 NamedDecl *D) {
373 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
374 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
375 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000376 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000377 // All the args are checked/rewritten. Don't call twice!
378 RewriteBlockPointerDecl(D);
379 break;
380 }
381 }
382}
383
384void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
385 const PointerType *PT = funcType->getAsPointerType();
386 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
387 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
388}
389
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000390static bool IsHeaderFile(const std::string &Filename) {
391 std::string::size_type DotPos = Filename.rfind('.');
392
393 if (DotPos == std::string::npos) {
394 // no file extension
395 return false;
396 }
397
398 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
399 // C header: .h
400 // C++ header: .hh or .H;
401 return Ext == "h" || Ext == "hh" || Ext == "H";
402}
403
Steve Naroffb29b4272008-04-14 22:03:09 +0000404RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000405 Diagnostic &D, const LangOptions &LOpts)
406 : Diags(D), LangOpts(LOpts) {
407 IsHeader = IsHeaderFile(inFile);
408 InFileName = inFile;
409 OutFileName = outFile;
410 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
411 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000412 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
413 "rewriter doesn't support user-specified control flow semantics for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000414}
415
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000416ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000417 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000418 Diagnostic &Diags,
419 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000420 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000421}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000422
Steve Naroffb29b4272008-04-14 22:03:09 +0000423void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000424 Context = &context;
425 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000426 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000427 MsgSendFunctionDecl = 0;
428 MsgSendSuperFunctionDecl = 0;
429 MsgSendStretFunctionDecl = 0;
430 MsgSendSuperStretFunctionDecl = 0;
431 MsgSendFpretFunctionDecl = 0;
432 GetClassFunctionDecl = 0;
433 GetMetaClassFunctionDecl = 0;
434 SelGetUidFunctionDecl = 0;
435 CFStringFunctionDecl = 0;
436 GetProtocolFunctionDecl = 0;
437 ConstantStringClassReference = 0;
438 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000439 CurMethodDef = 0;
440 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000441 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000442 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000443 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000444 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000445 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000446 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000447 PropParentMap = 0;
448 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000449 DisableReplaceStmt = false;
450
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000451 // Get the ID and start/end of the main file.
452 MainFileID = SM->getMainFileID();
453 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
454 MainFileStart = MainBuf->getBufferStart();
455 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000456
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000457 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000458
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000459 // declaring objc_selector outside the parameter list removes a silly
460 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000461 if (IsHeader)
462 Preamble = "#pragma once\n";
463 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000464 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000465 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000466 if (LangOpts.Microsoft) {
467 // Add a constructor for creating temporary objects.
Steve Naroff46a98a72008-12-23 20:11:22 +0000468 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) : ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000469 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000470 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000471 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000472 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
473 Preamble += "typedef struct objc_object Protocol;\n";
474 Preamble += "#define _REWRITER_typedef_Protocol\n";
475 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000476 if (LangOpts.Microsoft) {
477 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
478 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
479 } else
480 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
481 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000482 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000483 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000484 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000485 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000486 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000487 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000488 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000489 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000490 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000491 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000492 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000493 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000494 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000495 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
496 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
497 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
498 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
499 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000500 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000501 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000502 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
503 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
504 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000505 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
506 Preamble += "struct __objcFastEnumerationState {\n\t";
507 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000508 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000509 Preamble += "unsigned long *mutationsPtr;\n\t";
510 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000511 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000512 Preamble += "#define __FASTENUMERATIONSTATE\n";
513 Preamble += "#endif\n";
514 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
515 Preamble += "struct __NSConstantStringImpl {\n";
516 Preamble += " int *isa;\n";
517 Preamble += " int flags;\n";
518 Preamble += " char *str;\n";
519 Preamble += " long length;\n";
520 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000521 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
522 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
523 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000524 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000525 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000526 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
527 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000528 // Blocks preamble.
529 Preamble += "#ifndef BLOCK_IMPL\n";
530 Preamble += "#define BLOCK_IMPL\n";
531 Preamble += "struct __block_impl {\n";
532 Preamble += " void *isa;\n";
533 Preamble += " int Flags;\n";
534 Preamble += " int Size;\n";
535 Preamble += " void *FuncPtr;\n";
536 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000537 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
538 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
539 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
540 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
541 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff54055232008-10-27 17:20:55 +0000542 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000543 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000544 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
545 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000546 Preamble += "#define __attribute__(X)\n";
547 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000548}
549
550
Chris Lattnerf04da132007-10-24 17:06:59 +0000551//===----------------------------------------------------------------------===//
552// Top Level Driver Code
553//===----------------------------------------------------------------------===//
554
Steve Naroffb29b4272008-04-14 22:03:09 +0000555void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000556 // Two cases: either the decl could be in the main file, or it could be in a
557 // #included file. If the former, rewrite it now. If the later, check to see
558 // if we rewrote the #include/#import.
559 SourceLocation Loc = D->getLocation();
560 Loc = SM->getLogicalLoc(Loc);
561
562 // If this is for a builtin, ignore it.
563 if (Loc.isInvalid()) return;
564
Steve Naroffebf2b562007-10-23 23:50:29 +0000565 // Look for built-in declarations that we need to refer during the rewrite.
566 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000567 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000568 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000569 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000570 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000571 ConstantStringClassReference = FVD;
572 return;
573 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000574 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000575 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000576 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000577 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000578 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000579 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000580 } else if (ObjCForwardProtocolDecl *FP =
581 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000582 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000583 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
584 // Recurse into linkage specifications
585 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
586 DIEnd = LSD->decls_end();
587 DI != DIEnd; ++DI)
588 HandleTopLevelDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000589 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000590 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000591 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000592 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000593}
594
Chris Lattnerf04da132007-10-24 17:06:59 +0000595//===----------------------------------------------------------------------===//
596// Syntactic (non-AST) Rewriting Code
597//===----------------------------------------------------------------------===//
598
Steve Naroffb29b4272008-04-14 22:03:09 +0000599void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000600 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
601 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
602 const char *MainBufStart = MainBuf.first;
603 const char *MainBufEnd = MainBuf.second;
604 size_t ImportLen = strlen("import");
605 size_t IncludeLen = strlen("include");
606
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000607 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000608 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
609 if (*BufPtr == '#') {
610 if (++BufPtr == MainBufEnd)
611 return;
612 while (*BufPtr == ' ' || *BufPtr == '\t')
613 if (++BufPtr == MainBufEnd)
614 return;
615 if (!strncmp(BufPtr, "import", ImportLen)) {
616 // replace import with include
617 SourceLocation ImportLoc =
618 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000619 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000620 BufPtr += ImportLen;
621 }
622 }
623 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000624}
625
Steve Naroffb29b4272008-04-14 22:03:09 +0000626void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000627 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
628 const char *MainBufStart = MainBuf.first;
629 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000630
Chris Lattnerf04da132007-10-24 17:06:59 +0000631 // Loop over the whole file, looking for tabs.
632 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
633 if (*BufPtr != '\t')
634 continue;
635
636 // Okay, we found a tab. This tab will turn into at least one character,
637 // but it depends on which 'virtual column' it is in. Compute that now.
638 unsigned VCol = 0;
639 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
640 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
641 ++VCol;
642
643 // Okay, now that we know the virtual column, we know how many spaces to
644 // insert. We assume 8-character tab-stops.
645 unsigned Spaces = 8-(VCol & 7);
646
647 // Get the location of the tab.
648 SourceLocation TabLoc =
649 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
650
651 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000652 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000653 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000654}
655
Steve Naroffeb0646c2008-12-02 15:48:25 +0000656static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
657 ObjCIvarDecl *OID) {
658 std::string S;
659 S = "((struct ";
660 S += ClassDecl->getIdentifier()->getName();
661 S += "_IMPL *)self)->";
662 S += OID->getNameAsCString();
663 return S;
664}
665
Steve Naroffa0876e82008-12-02 17:36:43 +0000666void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
667 ObjCImplementationDecl *IMD,
668 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000669 SourceLocation startLoc = PID->getLocStart();
670 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000671 const char *startBuf = SM->getCharacterData(startLoc);
672 assert((*startBuf == '@') && "bogus @synthesize location");
673 const char *semiBuf = strchr(startBuf, ';');
674 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
675 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
676
677 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
678 return; // FIXME: is this correct?
679
680 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000681 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000682 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000683 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000684
685 if (!OID)
686 return;
687
688 std::string Getr;
689 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
690 Getr += "{ ";
691 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000692 // FIXME: deal with code generation implications for various property
693 // attributes (copy, retain, nonatomic).
694 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000695 Getr += "return " + getIvarAccessString(ClassDecl, OID);
696 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000697 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000698
699 // Add the rewritten getter to trigger meta data generation. An alternate, and
700 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
701 // with properties explicitly. The following addInstanceMethod() required far
702 // less code change (and actually models what the rewriter is doing).
703 if (IMD)
704 IMD->addInstanceMethod(PD->getGetterMethodDecl());
705 else
706 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000707
708 if (PD->isReadOnly())
709 return;
710
711 // Generate the 'setter' function.
712 std::string Setr;
713 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000714 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000715 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000716 // FIXME: deal with code generation implications for various property
717 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000718 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000719 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000720 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000721 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000722 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000723
724 // Add the rewritten setter to trigger meta data generation.
725 if (IMD)
726 IMD->addInstanceMethod(PD->getSetterMethodDecl());
727 else
728 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000729}
Chris Lattner8a12c272007-10-11 18:38:32 +0000730
Steve Naroffb29b4272008-04-14 22:03:09 +0000731void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000732 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000733 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000734
735 // Get the start location and compute the semi location.
736 SourceLocation startLoc = ClassDecl->getLocation();
737 const char *startBuf = SM->getCharacterData(startLoc);
738 const char *semiPtr = strchr(startBuf, ';');
739
740 // Translate to typedef's that forward reference structs with the same name
741 // as the class. As a convenience, we include the original declaration
742 // as a comment.
743 std::string typedefString;
744 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000745 typedefString.append(startBuf, semiPtr-startBuf+1);
746 typedefString += "\n";
747 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000748 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000749 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000750 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000751 typedefString += "\n";
752 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000753 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000754 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000755 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000756 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000757 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000758 }
759
760 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000761 ReplaceText(startLoc, semiPtr-startBuf+1,
762 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000763}
764
Steve Naroffb29b4272008-04-14 22:03:09 +0000765void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000766 SourceLocation LocStart = Method->getLocStart();
767 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000768
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000769 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000770 InsertText(LocStart, "#if 0\n", 6);
771 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000772 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000773 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000774 }
775}
776
Steve Naroff6327e0d2009-01-11 01:06:09 +0000777void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000778{
Steve Naroff6327e0d2009-01-11 01:06:09 +0000779 SourceLocation Loc = prop->getLocation();
780
781 ReplaceText(Loc, 0, "// ", 3);
782
783 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000784}
785
Steve Naroffb29b4272008-04-14 22:03:09 +0000786void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000787 SourceLocation LocStart = CatDecl->getLocStart();
788
789 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000790 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000791
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000792 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000793 E = CatDecl->instmeth_end(); I != E; ++I)
794 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000795 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000796 E = CatDecl->classmeth_end(); I != E; ++I)
797 RewriteMethodDeclaration(*I);
798
Steve Naroff423cb562007-10-30 13:30:57 +0000799 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000800 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000801}
802
Steve Naroffb29b4272008-04-14 22:03:09 +0000803void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000804 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000805
Steve Naroff752d6ef2007-10-30 16:42:30 +0000806 SourceLocation LocStart = PDecl->getLocStart();
807
808 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000809 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000810
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000811 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000812 E = PDecl->instmeth_end(); I != E; ++I)
813 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000814 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000815 E = PDecl->classmeth_end(); I != E; ++I)
816 RewriteMethodDeclaration(*I);
817
Steve Naroff752d6ef2007-10-30 16:42:30 +0000818 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000819 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000820 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000821
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000822 // Must comment out @optional/@required
823 const char *startBuf = SM->getCharacterData(LocStart);
824 const char *endBuf = SM->getCharacterData(LocEnd);
825 for (const char *p = startBuf; p < endBuf; p++) {
826 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
827 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000828 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000829 ReplaceText(OptionalLoc, strlen("@optional"),
830 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000831
832 }
833 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
834 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000835 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000836 ReplaceText(OptionalLoc, strlen("@required"),
837 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000838
839 }
840 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000841}
842
Steve Naroffb29b4272008-04-14 22:03:09 +0000843void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000844 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000845 if (LocStart.isInvalid())
846 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000847 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000848 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000849}
850
Steve Naroffb29b4272008-04-14 22:03:09 +0000851void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000852 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000853 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000854 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000855 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000856 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000857 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000858 else if (OMD->getResultType()->isFunctionPointerType() ||
859 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000860 // needs special handling, since pointer-to-functions have special
861 // syntax (where a decaration models use).
862 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000863 QualType PointeeTy;
864 if (const PointerType* PT = retType->getAsPointerType())
865 PointeeTy = PT->getPointeeType();
866 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
867 PointeeTy = BPT->getPointeeType();
868 if ((FPRetType = PointeeTy->getAsFunctionType())) {
869 ResultStr += FPRetType->getResultType().getAsString();
870 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000871 }
872 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000873 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000874 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000875
876 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000877 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000878
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000879 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000880 NameStr += "_I_";
881 else
882 NameStr += "_C_";
883
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000884 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000885 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000886
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000887 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000888 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000889 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000890 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000891 }
Steve Naroff563b8282008-04-04 22:23:44 +0000892 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000893 {
894 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000895 int len = selString.size();
896 for (int i = 0; i < len; i++)
897 if (selString[i] == ':')
898 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000899 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000900 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000901 // Remember this name for metadata emission
902 MethodInternalNames[OMD] = NameStr;
903 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000904
905 // Rewrite arguments
906 ResultStr += "(";
907
908 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000909 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000910 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000911 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000912 if (!LangOpts.Microsoft) {
913 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
914 ResultStr += "struct ";
915 }
916 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000917 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000918 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000919 }
920 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000921 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000922
923 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000924 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000925 ResultStr += " _cmd";
926
927 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000928 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000929 ParmVarDecl *PDecl = OMD->getParamDecl(i);
930 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000931 if (PDecl->getType()->isObjCQualifiedIdType()) {
932 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000933 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000934 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000935 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000936 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000937 // Make sure we convert "t (^)(...)" to "t (*)(...)".
938 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
939 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
940 } else
941 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000942 ResultStr += Name;
943 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000944 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000945 if (OMD->isVariadic())
946 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000947 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000948
Steve Naroff76e429d2008-07-16 14:40:40 +0000949 if (FPRetType) {
950 ResultStr += ")"; // close the precedence "scope" for "*".
951
952 // Now, emit the argument types (if any).
953 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
954 ResultStr += "(";
955 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
956 if (i) ResultStr += ", ";
957 std::string ParamStr = FT->getArgType(i).getAsString();
958 ResultStr += ParamStr;
959 }
960 if (FT->isVariadic()) {
961 if (FT->getNumArgs()) ResultStr += ", ";
962 ResultStr += "...";
963 }
964 ResultStr += ")";
965 } else {
966 ResultStr += "()";
967 }
968 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000969}
Steve Naroffb29b4272008-04-14 22:03:09 +0000970void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000971 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
972 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000973
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000974 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000975 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000976 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000977 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000978
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000979 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000980 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
981 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000982 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000983 ObjCMethodDecl *OMD = *I;
984 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000985 SourceLocation LocStart = OMD->getLocStart();
986 SourceLocation LocEnd = OMD->getBody()->getLocStart();
987
988 const char *startBuf = SM->getCharacterData(LocStart);
989 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000990 ReplaceText(LocStart, endBuf-startBuf,
991 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000992 }
993
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000994 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000995 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
996 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000997 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000998 ObjCMethodDecl *OMD = *I;
999 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001000 SourceLocation LocStart = OMD->getLocStart();
1001 SourceLocation LocEnd = OMD->getBody()->getLocStart();
1002
1003 const char *startBuf = SM->getCharacterData(LocStart);
1004 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001005 ReplaceText(LocStart, endBuf-startBuf,
1006 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001007 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001008 for (ObjCCategoryImplDecl::propimpl_iterator
1009 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1010 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001011 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001012 }
1013
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001014 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001015 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001016 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001017 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001018}
1019
Steve Naroffb29b4272008-04-14 22:03:09 +00001020void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001021 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001022 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001023 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001024 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001025 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001026 ResultStr += "\n";
1027 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001028 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001029 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001030 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001031 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001032 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001033 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001034 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001035 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001036 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001037
Steve Naroff6327e0d2009-01-11 01:06:09 +00001038 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1039 E = ClassDecl->prop_end(); I != E; ++I)
1040 RewriteProperty(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001041 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001042 E = ClassDecl->instmeth_end(); I != E; ++I)
1043 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001044 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001045 E = ClassDecl->classmeth_end(); I != E; ++I)
1046 RewriteMethodDeclaration(*I);
1047
Steve Naroff2feac5e2007-10-30 03:43:13 +00001048 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001049 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001050}
1051
Steve Naroffb619d952008-12-09 12:56:34 +00001052Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1053 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001054 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1055 // This allows us to reuse all the fun and games in SynthMessageExpr().
1056 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1057 ObjCMessageExpr *MsgExpr;
1058 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1059 llvm::SmallVector<Expr *, 1> ExprVec;
1060 ExprVec.push_back(newStmt);
1061
Steve Naroff8599e7a2008-12-08 16:43:47 +00001062 Stmt *Receiver = PropRefExpr->getBase();
1063 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1064 if (PRE && PropGetters[PRE]) {
1065 // This allows us to handle chain/nested property getters.
1066 Receiver = PropGetters[PRE];
1067 }
1068 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001069 PDecl->getSetterName(), PDecl->getType(),
1070 PDecl->getSetterMethodDecl(),
1071 SourceLocation(), SourceLocation(),
1072 &ExprVec[0], 1);
1073 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1074
1075 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001076 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001077 //delete BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00001078 delete MsgExpr;
1079 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001080}
1081
Steve Naroffc77a6362008-12-04 16:24:46 +00001082Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001083 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1084 // This allows us to reuse all the fun and games in SynthMessageExpr().
1085 ObjCMessageExpr *MsgExpr;
1086 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1087
Steve Naroff8599e7a2008-12-08 16:43:47 +00001088 Stmt *Receiver = PropRefExpr->getBase();
1089
1090 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1091 if (PRE && PropGetters[PRE]) {
1092 // This allows us to handle chain/nested property getters.
1093 Receiver = PropGetters[PRE];
1094 }
1095 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001096 PDecl->getGetterName(), PDecl->getType(),
1097 PDecl->getGetterMethodDecl(),
1098 SourceLocation(), SourceLocation(),
1099 0, 0);
1100
Steve Naroff4c3580e2008-12-04 23:50:32 +00001101 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001102
1103 if (!PropParentMap)
1104 PropParentMap = new ParentMap(CurrentBody);
1105
1106 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1107 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1108 // We stash away the ReplacingStmt since actually doing the
1109 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1110 PropGetters[PropRefExpr] = ReplacingStmt;
1111 delete MsgExpr;
1112 return PropRefExpr; // return the original...
1113 } else {
1114 ReplaceStmt(PropRefExpr, ReplacingStmt);
1115 // delete PropRefExpr; elsewhere...
1116 delete MsgExpr;
1117 return ReplacingStmt;
1118 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001119}
1120
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001121Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1122 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001123 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001124 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001125 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001126 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1127 // lookup which class implements the instance variable.
1128 ObjCInterfaceDecl *clsDeclared = 0;
1129 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1130 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1131
1132 // Synthesize an explicit cast to gain access to the ivar.
1133 std::string RecName = clsDeclared->getIdentifier()->getName();
1134 RecName += "_IMPL";
1135 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001136 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001137 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001138 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1139 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001140 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001141 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001142 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001143 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1144 IV->getBase()->getLocEnd(),
1145 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001146 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001147 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001148 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1149 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001150 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001151 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001152 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001153 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001154
1155 ReplaceStmt(IV->getBase(), PE);
1156 // Cannot delete IV->getBase(), since PE points to it.
1157 // Replace the old base with the cast. This is important when doing
1158 // embedded rewrites. For example, [newInv->_container addObject:0].
1159 IV->setBase(PE);
1160 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001161 }
Steve Naroff84472a82008-04-18 21:55:08 +00001162 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001163 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1164
1165 // Explicit ivar refs need to have a cast inserted.
1166 // FIXME: consider sharing some of this code with the code above.
1167 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001168 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001169 // lookup which class implements the instance variable.
1170 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001171 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001172 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1173
1174 // Synthesize an explicit cast to gain access to the ivar.
1175 std::string RecName = clsDeclared->getIdentifier()->getName();
1176 RecName += "_IMPL";
1177 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001178 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001179 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001180 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1181 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001182 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001183 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001184 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001185 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1186 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001187 ReplaceStmt(IV->getBase(), PE);
1188 // Cannot delete IV->getBase(), since PE points to it.
1189 // Replace the old base with the cast. This is important when doing
1190 // embedded rewrites. For example, [newInv->_container addObject:0].
1191 IV->setBase(PE);
1192 return IV;
1193 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001194 }
Steve Naroff84472a82008-04-18 21:55:08 +00001195 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001196}
1197
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001198/// SynthCountByEnumWithState - To print:
1199/// ((unsigned int (*)
1200/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1201/// (void *)objc_msgSend)((id)l_collection,
1202/// sel_registerName(
1203/// "countByEnumeratingWithState:objects:count:"),
1204/// &enumState,
1205/// (id *)items, (unsigned int)16)
1206///
Steve Naroffb29b4272008-04-14 22:03:09 +00001207void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001208 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1209 "id *, unsigned int))(void *)objc_msgSend)";
1210 buf += "\n\t\t";
1211 buf += "((id)l_collection,\n\t\t";
1212 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1213 buf += "\n\t\t";
1214 buf += "&enumState, "
1215 "(id *)items, (unsigned int)16)";
1216}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001217
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001218/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1219/// statement to exit to its outer synthesized loop.
1220///
Steve Naroffb29b4272008-04-14 22:03:09 +00001221Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001222 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1223 return S;
1224 // replace break with goto __break_label
1225 std::string buf;
1226
1227 SourceLocation startLoc = S->getLocStart();
1228 buf = "goto __break_label_";
1229 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001230 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001231
1232 return 0;
1233}
1234
1235/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1236/// statement to continue with its inner synthesized loop.
1237///
Steve Naroffb29b4272008-04-14 22:03:09 +00001238Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001239 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1240 return S;
1241 // replace continue with goto __continue_label
1242 std::string buf;
1243
1244 SourceLocation startLoc = S->getLocStart();
1245 buf = "goto __continue_label_";
1246 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001247 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001248
1249 return 0;
1250}
1251
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001252/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001253/// It rewrites:
1254/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001255
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001256/// Into:
1257/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001258/// type elem;
1259/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001260/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001261/// id l_collection = (id)collection;
1262/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1263/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001264/// if (limit) {
1265/// unsigned long startMutations = *enumState.mutationsPtr;
1266/// do {
1267/// unsigned long counter = 0;
1268/// do {
1269/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001270/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001271/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001272/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001273/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001274/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001275/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1276/// objects:items count:16]);
1277/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001278/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001279/// }
1280/// else
1281/// elem = nil;
1282/// }
1283///
Steve Naroffb29b4272008-04-14 22:03:09 +00001284Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001285 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001286 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1287 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1288 "ObjCForCollectionStmt Statement stack mismatch");
1289 assert(!ObjCBcLabelNo.empty() &&
1290 "ObjCForCollectionStmt - Label No stack empty");
1291
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001292 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001293 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001294 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001295 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001296 std::string buf;
1297 buf = "\n{\n\t";
1298 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1299 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001300 ScopedDecl* D = DS->getSolitaryDecl();
1301 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001302 elementTypeAsString = ElementType.getAsString();
1303 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001304 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001305 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001306 buf += elementName;
1307 buf += ";\n\t";
1308 }
Chris Lattner06767512008-04-08 05:52:18 +00001309 else {
1310 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001311 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001312 elementTypeAsString
1313 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001314 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001315
1316 // struct __objcFastEnumerationState enumState = { 0 };
1317 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1318 // id items[16];
1319 buf += "id items[16];\n\t";
1320 // id l_collection = (id)
1321 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001322 // Find start location of 'collection' the hard way!
1323 const char *startCollectionBuf = startBuf;
1324 startCollectionBuf += 3; // skip 'for'
1325 startCollectionBuf = strchr(startCollectionBuf, '(');
1326 startCollectionBuf++; // skip '('
1327 // find 'in' and skip it.
1328 while (*startCollectionBuf != ' ' ||
1329 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1330 (*(startCollectionBuf+3) != ' ' &&
1331 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1332 startCollectionBuf++;
1333 startCollectionBuf += 3;
1334
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001335 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001336 ReplaceText(startLoc, startCollectionBuf - startBuf,
1337 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001338 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001339 SourceLocation rightParenLoc = S->getRParenLoc();
1340 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1341 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001342 buf = ";\n\t";
1343
1344 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1345 // objects:items count:16];
1346 // which is synthesized into:
1347 // unsigned int limit =
1348 // ((unsigned int (*)
1349 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1350 // (void *)objc_msgSend)((id)l_collection,
1351 // sel_registerName(
1352 // "countByEnumeratingWithState:objects:count:"),
1353 // (struct __objcFastEnumerationState *)&state,
1354 // (id *)items, (unsigned int)16);
1355 buf += "unsigned long limit =\n\t\t";
1356 SynthCountByEnumWithState(buf);
1357 buf += ";\n\t";
1358 /// if (limit) {
1359 /// unsigned long startMutations = *enumState.mutationsPtr;
1360 /// do {
1361 /// unsigned long counter = 0;
1362 /// do {
1363 /// if (startMutations != *enumState.mutationsPtr)
1364 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001365 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001366 buf += "if (limit) {\n\t";
1367 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1368 buf += "do {\n\t\t";
1369 buf += "unsigned long counter = 0;\n\t\t";
1370 buf += "do {\n\t\t\t";
1371 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1372 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1373 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001374 buf += " = (";
1375 buf += elementTypeAsString;
1376 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001377 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001378 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001379
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001380 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001381 /// } while (counter < limit);
1382 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1383 /// objects:items count:16]);
1384 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001385 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001386 /// }
1387 /// else
1388 /// elem = nil;
1389 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001390 ///
1391 buf = ";\n\t";
1392 buf += "__continue_label_";
1393 buf += utostr(ObjCBcLabelNo.back());
1394 buf += ": ;";
1395 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001396 buf += "} while (counter < limit);\n\t";
1397 buf += "} while (limit = ";
1398 SynthCountByEnumWithState(buf);
1399 buf += ");\n\t";
1400 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001401 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001402 buf += "__break_label_";
1403 buf += utostr(ObjCBcLabelNo.back());
1404 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001405 buf += "}\n\t";
1406 buf += "else\n\t\t";
1407 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001408 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001409 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001410
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001411 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001412 if (isa<CompoundStmt>(S->getBody())) {
1413 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1414 InsertText(endBodyLoc, buf.c_str(), buf.size());
1415 } else {
1416 /* Need to treat single statements specially. For example:
1417 *
1418 * for (A *a in b) if (stuff()) break;
1419 * for (A *a in b) xxxyy;
1420 *
1421 * The following code simply scans ahead to the semi to find the actual end.
1422 */
1423 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1424 const char *semiBuf = strchr(stmtBuf, ';');
1425 assert(semiBuf && "Can't find ';'");
1426 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1427 InsertText(endBodyLoc, buf.c_str(), buf.size());
1428 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001429 Stmts.pop_back();
1430 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001431 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001432}
1433
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001434/// RewriteObjCSynchronizedStmt -
1435/// This routine rewrites @synchronized(expr) stmt;
1436/// into:
1437/// objc_sync_enter(expr);
1438/// @try stmt @finally { objc_sync_exit(expr); }
1439///
Steve Naroffb29b4272008-04-14 22:03:09 +00001440Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001441 // Get the start location and compute the semi location.
1442 SourceLocation startLoc = S->getLocStart();
1443 const char *startBuf = SM->getCharacterData(startLoc);
1444
1445 assert((*startBuf == '@') && "bogus @synchronized location");
1446
1447 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001448 buf = "objc_sync_enter((id)";
1449 const char *lparenBuf = startBuf;
1450 while (*lparenBuf != '(') lparenBuf++;
1451 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001452 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1453 // the sync expression is typically a message expression that's already
1454 // been rewritten! (which implies the SourceLocation's are invalid).
1455 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001456 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001457 while (*endBuf != ')') endBuf--;
1458 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001459 buf = ");\n";
1460 // declare a new scope with two variables, _stack and _rethrow.
1461 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1462 buf += "int buf[18/*32-bit i386*/];\n";
1463 buf += "char *pointers[4];} _stack;\n";
1464 buf += "id volatile _rethrow = 0;\n";
1465 buf += "objc_exception_try_enter(&_stack);\n";
1466 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001467 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001468 startLoc = S->getSynchBody()->getLocEnd();
1469 startBuf = SM->getCharacterData(startLoc);
1470
Steve Naroffc7089f12008-08-19 13:04:19 +00001471 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001472 SourceLocation lastCurlyLoc = startLoc;
1473 buf = "}\nelse {\n";
1474 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1475 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001476 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001477 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001478 S->getSynchExpr(),
1479 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001480 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001481 std::string syncExprBufS;
1482 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001483 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001484 buf += syncExprBuf.str();
1485 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001486 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1487 buf += "}\n";
1488 buf += "}";
1489
Chris Lattneraadaf782008-01-31 19:51:04 +00001490 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001491 return 0;
1492}
1493
Steve Naroff8c565152008-12-05 17:03:39 +00001494void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1495 // Perform a bottom up traversal of all children.
1496 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1497 CI != E; ++CI)
1498 if (*CI)
1499 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1500
1501 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1502 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1503 Diags.Report(Context->getFullLoc(S->getLocStart()),
1504 TryFinallyContainsReturnDiag);
1505 }
1506 return;
1507}
1508
Steve Naroffb29b4272008-04-14 22:03:09 +00001509Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001510 // Get the start location and compute the semi location.
1511 SourceLocation startLoc = S->getLocStart();
1512 const char *startBuf = SM->getCharacterData(startLoc);
1513
1514 assert((*startBuf == '@') && "bogus @try location");
1515
1516 std::string buf;
1517 // declare a new scope with two variables, _stack and _rethrow.
1518 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1519 buf += "int buf[18/*32-bit i386*/];\n";
1520 buf += "char *pointers[4];} _stack;\n";
1521 buf += "id volatile _rethrow = 0;\n";
1522 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001523 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001524
Chris Lattneraadaf782008-01-31 19:51:04 +00001525 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001526
1527 startLoc = S->getTryBody()->getLocEnd();
1528 startBuf = SM->getCharacterData(startLoc);
1529
1530 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001531
Steve Naroff75730982007-11-07 04:08:17 +00001532 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001533 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1534 if (catchList) {
1535 startLoc = startLoc.getFileLocWithOffset(1);
1536 buf = " /* @catch begin */ else {\n";
1537 buf += " id _caught = objc_exception_extract(&_stack);\n";
1538 buf += " objc_exception_try_enter (&_stack);\n";
1539 buf += " if (_setjmp(_stack.buf))\n";
1540 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1541 buf += " else { /* @catch continue */";
1542
1543 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001544 } else { /* no catch list */
1545 buf = "}\nelse {\n";
1546 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1547 buf += "}";
1548 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001549 }
Steve Naroff75730982007-11-07 04:08:17 +00001550 bool sawIdTypedCatch = false;
1551 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001552 while (catchList) {
1553 Stmt *catchStmt = catchList->getCatchParamStmt();
1554
1555 if (catchList == S->getCatchStmts())
1556 buf = "if ("; // we are generating code for the first catch clause
1557 else
1558 buf = "else if (";
1559 startLoc = catchList->getLocStart();
1560 startBuf = SM->getCharacterData(startLoc);
1561
1562 assert((*startBuf == '@') && "bogus @catch location");
1563
1564 const char *lParenLoc = strchr(startBuf, '(');
1565
Steve Naroffbe4b3332008-02-01 22:08:12 +00001566 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001567 // Now rewrite the body...
1568 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001569 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1570 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001571 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1572 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001573 assert((*bodyBuf == '{') && "bogus @catch body location");
1574
1575 buf += "1) { id _tmp = _caught;";
1576 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1577 buf.c_str(), buf.size());
1578 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001579 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001580 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001581 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001582 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001583 sawIdTypedCatch = true;
1584 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001585 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001586
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001587 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001588 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001589 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001590 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001591 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001592 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001593 }
1594 }
1595 // Now rewrite the body...
1596 lastCatchBody = catchList->getCatchBody();
1597 SourceLocation rParenLoc = catchList->getRParenLoc();
1598 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1599 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1600 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1601 assert((*rParenBuf == ')') && "bogus @catch paren location");
1602 assert((*bodyBuf == '{') && "bogus @catch body location");
1603
1604 buf = " = _caught;";
1605 // Here we replace ") {" with "= _caught;" (which initializes and
1606 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001607 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001608 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001609 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001610 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001611 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001612 catchList = catchList->getNextCatchStmt();
1613 }
1614 // Complete the catch list...
1615 if (lastCatchBody) {
1616 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001617 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1618 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001619
Steve Naroff378f47a2008-09-11 15:29:03 +00001620 // Insert the last (implicit) else clause *before* the right curly brace.
1621 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1622 buf = "} /* last catch end */\n";
1623 buf += "else {\n";
1624 buf += " _rethrow = _caught;\n";
1625 buf += " objc_exception_try_exit(&_stack);\n";
1626 buf += "} } /* @catch end */\n";
1627 if (!S->getFinallyStmt())
1628 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001629 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001630
1631 // Set lastCurlyLoc
1632 lastCurlyLoc = lastCatchBody->getLocEnd();
1633 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001634 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001635 startLoc = finalStmt->getLocStart();
1636 startBuf = SM->getCharacterData(startLoc);
1637 assert((*startBuf == '@') && "bogus @finally start");
1638
1639 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001640 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001641
1642 Stmt *body = finalStmt->getFinallyBody();
1643 SourceLocation startLoc = body->getLocStart();
1644 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001645 assert(*SM->getCharacterData(startLoc) == '{' &&
1646 "bogus @finally body location");
1647 assert(*SM->getCharacterData(endLoc) == '}' &&
1648 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001649
1650 startLoc = startLoc.getFileLocWithOffset(1);
1651 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001652 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001653 endLoc = endLoc.getFileLocWithOffset(-1);
1654 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001655 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001656
1657 // Set lastCurlyLoc
1658 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001659
1660 // Now check for any return/continue/go statements within the @try.
1661 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001662 } else { /* no finally clause - make sure we synthesize an implicit one */
1663 buf = "{ /* implicit finally clause */\n";
1664 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1665 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1666 buf += "}";
1667 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001668 }
1669 // Now emit the final closing curly brace...
1670 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1671 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001672 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001673 return 0;
1674}
1675
Steve Naroffb29b4272008-04-14 22:03:09 +00001676Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001677 return 0;
1678}
1679
Steve Naroffb29b4272008-04-14 22:03:09 +00001680Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001681 return 0;
1682}
1683
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001684// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001685// the throw expression is typically a message expression that's already
1686// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001687Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001688 // Get the start location and compute the semi location.
1689 SourceLocation startLoc = S->getLocStart();
1690 const char *startBuf = SM->getCharacterData(startLoc);
1691
1692 assert((*startBuf == '@') && "bogus @throw location");
1693
1694 std::string buf;
1695 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001696 if (S->getThrowExpr())
1697 buf = "objc_exception_throw(";
1698 else // add an implicit argument
1699 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001700
1701 // handle "@ throw" correctly.
1702 const char *wBuf = strchr(startBuf, 'w');
1703 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1704 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1705
Steve Naroff2bd03922007-11-07 15:32:26 +00001706 const char *semiBuf = strchr(startBuf, ';');
1707 assert((*semiBuf == ';') && "@throw: can't find ';'");
1708 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1709 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001710 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001711 return 0;
1712}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001713
Steve Naroffb29b4272008-04-14 22:03:09 +00001714Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001715 // Create a new string expression.
1716 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001717 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001718 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001719 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1720 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001721 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001722 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001723
Chris Lattner07506182007-11-30 22:53:43 +00001724 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001725 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001726 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001727}
1728
Steve Naroffb29b4272008-04-14 22:03:09 +00001729Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001730 if (!SelGetUidFunctionDecl)
1731 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001732 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1733 // Create a call to sel_registerName("selName").
1734 llvm::SmallVector<Expr*, 8> SelExprs;
1735 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001736 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1737 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001738 false, argType, SourceLocation(),
1739 SourceLocation()));
1740 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1741 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001742 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001743 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001744 return SelExp;
1745}
1746
Steve Naroffb29b4272008-04-14 22:03:09 +00001747CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001748 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001749 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001750 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001751
1752 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001753 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001754
1755 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001756 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001757 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1758 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001759
1760 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001761
Steve Naroff934f2762007-10-24 22:48:43 +00001762 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1763}
1764
Steve Naroffd5255f52007-11-01 13:24:47 +00001765static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1766 const char *&startRef, const char *&endRef) {
1767 while (startBuf < endBuf) {
1768 if (*startBuf == '<')
1769 startRef = startBuf; // mark the start.
1770 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001771 if (startRef && *startRef == '<') {
1772 endRef = startBuf; // mark the end.
1773 return true;
1774 }
1775 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001776 }
1777 startBuf++;
1778 }
1779 return false;
1780}
1781
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001782static void scanToNextArgument(const char *&argRef) {
1783 int angle = 0;
1784 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1785 if (*argRef == '<')
1786 angle++;
1787 else if (*argRef == '>')
1788 angle--;
1789 argRef++;
1790 }
1791 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1792}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001793
Steve Naroffb29b4272008-04-14 22:03:09 +00001794bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001795
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001796 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001797 return true;
1798
Steve Naroffd5255f52007-11-01 13:24:47 +00001799 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001800 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001801 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001802 return true; // we have "Class <Protocol> *".
1803 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001804 return false;
1805}
1806
Steve Naroff4f95b752008-07-29 18:15:38 +00001807void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1808 QualType Type = E->getType();
1809 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001810 SourceLocation Loc, EndLoc;
1811
1812 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1813 Loc = ECE->getLParenLoc();
1814 EndLoc = ECE->getRParenLoc();
1815 } else {
1816 Loc = E->getLocStart();
1817 EndLoc = E->getLocEnd();
1818 }
1819 // This will defend against trying to rewrite synthesized expressions.
1820 if (Loc.isInvalid() || EndLoc.isInvalid())
1821 return;
1822
Steve Naroff4f95b752008-07-29 18:15:38 +00001823 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001824 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001825 const char *startRef = 0, *endRef = 0;
1826 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1827 // Get the locations of the startRef, endRef.
1828 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1829 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1830 // Comment out the protocol references.
1831 InsertText(LessLoc, "/*", 2);
1832 InsertText(GreaterLoc, "*/", 2);
1833 }
1834 }
1835}
1836
Steve Naroffb29b4272008-04-14 22:03:09 +00001837void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001838 SourceLocation Loc;
1839 QualType Type;
1840 const FunctionTypeProto *proto = 0;
1841 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1842 Loc = VD->getLocation();
1843 Type = VD->getType();
1844 }
1845 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1846 Loc = FD->getLocation();
1847 // Check for ObjC 'id' and class types that have been adorned with protocol
1848 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1849 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1850 assert(funcType && "missing function type");
1851 proto = dyn_cast<FunctionTypeProto>(funcType);
1852 if (!proto)
1853 return;
1854 Type = proto->getResultType();
1855 }
1856 else
1857 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001858
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001859 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001860 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001861
1862 const char *endBuf = SM->getCharacterData(Loc);
1863 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001864 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001865 startBuf--; // scan backward (from the decl location) for return type.
1866 const char *startRef = 0, *endRef = 0;
1867 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1868 // Get the locations of the startRef, endRef.
1869 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1870 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1871 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001872 InsertText(LessLoc, "/*", 2);
1873 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001874 }
1875 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001876 if (!proto)
1877 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001878 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001879 const char *startBuf = SM->getCharacterData(Loc);
1880 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001881 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1882 if (needToScanForQualifiers(proto->getArgType(i))) {
1883 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001884
Steve Naroffd5255f52007-11-01 13:24:47 +00001885 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001886 // scan forward (from the decl location) for argument types.
1887 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001888 const char *startRef = 0, *endRef = 0;
1889 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1890 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001891 SourceLocation LessLoc =
1892 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1893 SourceLocation GreaterLoc =
1894 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001895 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001896 InsertText(LessLoc, "/*", 2);
1897 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001898 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001899 startBuf = ++endBuf;
1900 }
1901 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001902 // If the function name is derived from a macro expansion, then the
1903 // argument buffer will not follow the name. Need to speak with Chris.
1904 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001905 startBuf++; // scan forward (from the decl location) for argument types.
1906 startBuf++;
1907 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001908 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001909}
1910
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001911// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001912void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001913 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1914 llvm::SmallVector<QualType, 16> ArgTys;
1915 ArgTys.push_back(Context->getPointerType(
1916 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001917 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001918 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001919 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001920 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001921 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001922 SelGetUidIdent, getFuncType,
1923 FunctionDecl::Extern, false, 0);
1924}
1925
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001926// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001927void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001928 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1929 llvm::SmallVector<QualType, 16> ArgTys;
1930 ArgTys.push_back(Context->getPointerType(
1931 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001932 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001933 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001934 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001935 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001936 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001937 SelGetProtoIdent, getFuncType,
1938 FunctionDecl::Extern, false, 0);
1939}
1940
Steve Naroffb29b4272008-04-14 22:03:09 +00001941void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001942 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00001943 if (FD->getIdentifier() &&
1944 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001945 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001946 return;
1947 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001948 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001949}
1950
Steve Naroffc0a123c2008-03-11 17:37:02 +00001951// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001952void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001953 if (SuperContructorFunctionDecl)
1954 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00001955 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00001956 llvm::SmallVector<QualType, 16> ArgTys;
1957 QualType argT = Context->getObjCIdType();
1958 assert(!argT.isNull() && "Can't find 'id' type");
1959 ArgTys.push_back(argT);
1960 ArgTys.push_back(argT);
1961 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1962 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001963 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001964 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001965 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001966 msgSendIdent, msgSendType,
1967 FunctionDecl::Extern, false, 0);
1968}
1969
Steve Naroff09b266e2007-10-30 23:14:51 +00001970// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001971void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001972 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1973 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001974 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001975 assert(!argT.isNull() && "Can't find 'id' type");
1976 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001977 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001978 assert(!argT.isNull() && "Can't find 'SEL' type");
1979 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001980 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001981 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001982 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001983 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001984 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001985 msgSendIdent, msgSendType,
1986 FunctionDecl::Extern, false, 0);
1987}
1988
Steve Naroff874e2322007-11-15 10:28:18 +00001989// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001990void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001991 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1992 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001993 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001994 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001995 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001996 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1997 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1998 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001999 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002000 assert(!argT.isNull() && "Can't find 'SEL' type");
2001 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002002 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002003 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002004 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002005 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002006 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002007 msgSendIdent, msgSendType,
2008 FunctionDecl::Extern, false, 0);
2009}
2010
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002011// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002012void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002013 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2014 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002015 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002016 assert(!argT.isNull() && "Can't find 'id' type");
2017 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002018 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002019 assert(!argT.isNull() && "Can't find 'SEL' type");
2020 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002021 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002022 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002023 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002024 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002025 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002026 msgSendIdent, msgSendType,
2027 FunctionDecl::Extern, false, 0);
2028}
2029
2030// SynthMsgSendSuperStretFunctionDecl -
2031// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002032void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002033 IdentifierInfo *msgSendIdent =
2034 &Context->Idents.get("objc_msgSendSuper_stret");
2035 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002036 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002037 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002038 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002039 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2040 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2041 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002042 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002043 assert(!argT.isNull() && "Can't find 'SEL' type");
2044 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002045 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002046 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002047 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002048 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002049 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002050 msgSendIdent, msgSendType,
2051 FunctionDecl::Extern, false, 0);
2052}
2053
Steve Naroff1284db82008-05-08 22:02:18 +00002054// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002055void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002056 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2057 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002058 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002059 assert(!argT.isNull() && "Can't find 'id' type");
2060 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002061 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002062 assert(!argT.isNull() && "Can't find 'SEL' type");
2063 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002064 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002065 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002066 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002067 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002068 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002069 msgSendIdent, msgSendType,
2070 FunctionDecl::Extern, false, 0);
2071}
2072
Steve Naroff09b266e2007-10-30 23:14:51 +00002073// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002074void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002075 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2076 llvm::SmallVector<QualType, 16> ArgTys;
2077 ArgTys.push_back(Context->getPointerType(
2078 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002079 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002080 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002081 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002082 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002083 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002084 getClassIdent, getClassType,
2085 FunctionDecl::Extern, false, 0);
2086}
2087
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002088// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002089void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002090 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2091 llvm::SmallVector<QualType, 16> ArgTys;
2092 ArgTys.push_back(Context->getPointerType(
2093 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002094 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002095 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002096 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002097 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002098 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002099 getClassIdent, getClassType,
2100 FunctionDecl::Extern, false, 0);
2101}
2102
Steve Naroffb29b4272008-04-14 22:03:09 +00002103Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002104 QualType strType = getConstantStringStructType();
2105
2106 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002107
2108 std::string tmpName = InFileName;
2109 unsigned i;
2110 for (i=0; i < tmpName.length(); i++) {
2111 char c = tmpName.at(i);
2112 // replace any non alphanumeric characters with '_'.
2113 if (!isalpha(c) && (c < '0' || c > '9'))
2114 tmpName[i] = '_';
2115 }
2116 S += tmpName;
2117 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002118 S += utostr(NumObjCStringLiterals++);
2119
Steve Naroffba92b2e2008-03-27 22:29:16 +00002120 Preamble += "static __NSConstantStringImpl " + S;
2121 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2122 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002123 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002124 std::string prettyBufS;
2125 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002126 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002127 Preamble += prettyBuf.str();
2128 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002129 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002130 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002131
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002132 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002133 &Context->Idents.get(S.c_str()), strType,
2134 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002135 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2136 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2137 Context->getPointerType(DRE->getType()),
2138 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002139 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002140 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002141 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002142 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002143 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002144 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002145}
2146
Steve Naroffb29b4272008-04-14 22:03:09 +00002147ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002148 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002149 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002150
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002151 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2152 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002153 assert(PT);
2154 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2155 return IT->getDecl();
2156 }
2157 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002158}
2159
2160// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002161QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002162 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002163 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002164 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002165 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002166 QualType FieldTypes[2];
2167
2168 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002169 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002170 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002171 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002172
Steve Naroff874e2322007-11-15 10:28:18 +00002173 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002174 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregor482b77d2009-01-12 23:27:07 +00002175 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002176 SourceLocation(), 0,
2177 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor482b77d2009-01-12 23:27:07 +00002178 /*Mutable=*/false, 0));
Douglas Gregor44b43212008-12-11 16:49:14 +00002179 }
Steve Naroff874e2322007-11-15 10:28:18 +00002180
Douglas Gregor44b43212008-12-11 16:49:14 +00002181 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002182 }
2183 return Context->getTagDeclType(SuperStructDecl);
2184}
2185
Steve Naroffb29b4272008-04-14 22:03:09 +00002186QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002187 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002188 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002189 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002190 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002191 QualType FieldTypes[4];
2192
2193 // struct objc_object *receiver;
2194 FieldTypes[0] = Context->getObjCIdType();
2195 // int flags;
2196 FieldTypes[1] = Context->IntTy;
2197 // char *str;
2198 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2199 // long length;
2200 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002201
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002202 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002203 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregor482b77d2009-01-12 23:27:07 +00002204 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
Douglas Gregor44b43212008-12-11 16:49:14 +00002205 ConstantStringDecl,
2206 SourceLocation(), 0,
2207 FieldTypes[i],
2208 /*BitWidth=*/0,
Douglas Gregor482b77d2009-01-12 23:27:07 +00002209 /*Mutable=*/true, 0));
Douglas Gregor44b43212008-12-11 16:49:14 +00002210 }
2211
2212 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002213 }
2214 return Context->getTagDeclType(ConstantStringDecl);
2215}
2216
Steve Naroffb29b4272008-04-14 22:03:09 +00002217Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002218 if (!SelGetUidFunctionDecl)
2219 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002220 if (!MsgSendFunctionDecl)
2221 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002222 if (!MsgSendSuperFunctionDecl)
2223 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002224 if (!MsgSendStretFunctionDecl)
2225 SynthMsgSendStretFunctionDecl();
2226 if (!MsgSendSuperStretFunctionDecl)
2227 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002228 if (!MsgSendFpretFunctionDecl)
2229 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002230 if (!GetClassFunctionDecl)
2231 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002232 if (!GetMetaClassFunctionDecl)
2233 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002234
Steve Naroff874e2322007-11-15 10:28:18 +00002235 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002236 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2237 // May need to use objc_msgSend_stret() as well.
2238 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002239 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002240 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002241 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002242 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002243 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002244 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002245 }
Steve Naroff874e2322007-11-15 10:28:18 +00002246
Steve Naroff934f2762007-10-24 22:48:43 +00002247 // Synthesize a call to objc_msgSend().
2248 llvm::SmallVector<Expr*, 8> MsgExprs;
2249 IdentifierInfo *clsName = Exp->getClassName();
2250
2251 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2252 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002253 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2254 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002255 if (!strcmp(clsName->getName(), "super")) {
2256 MsgSendFlavor = MsgSendSuperFunctionDecl;
2257 if (MsgSendStretFlavor)
2258 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2259 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2260
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002261 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002262 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002263
2264 llvm::SmallVector<Expr*, 4> InitExprs;
2265
2266 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002267 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002268 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002269 Context->getObjCIdType(),
2270 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002271 llvm::SmallVector<Expr*, 8> ClsExprs;
2272 QualType argType = Context->getPointerType(Context->CharTy);
2273 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2274 SuperDecl->getIdentifier()->getLength(),
2275 false, argType, SourceLocation(),
2276 SourceLocation()));
2277 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2278 &ClsExprs[0],
2279 ClsExprs.size());
2280 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002281 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002282 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002283 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002284 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002285 // struct objc_super
2286 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002287 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002288
Steve Naroff23f41272008-03-11 18:14:26 +00002289 if (LangOpts.Microsoft) {
2290 SynthSuperContructorFunctionDecl();
2291 // Simulate a contructor call...
2292 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2293 superType, SourceLocation());
2294 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2295 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002296 // The code for super is a little tricky to prevent collision with
2297 // the structure definition in the header. The rewriter has it's own
2298 // internal definition (__rw_objc_super) that is uses. This is why
2299 // we need the cast below. For example:
2300 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2301 //
2302 SuperRep = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2303 Context->getPointerType(SuperRep->getType()),
2304 SourceLocation());
2305 SuperRep = new CStyleCastExpr(Context->getPointerType(superType),
2306 SuperRep, Context->getPointerType(superType),
2307 SourceLocation(), SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002308 } else {
2309 // (struct objc_super) { <exprs from above> }
2310 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2311 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002312 SourceLocation(), false);
2313 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2314 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002315 // struct objc_super *
2316 SuperRep = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2317 Context->getPointerType(SuperRep->getType()),
2318 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002319 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002320 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002321 } else {
2322 llvm::SmallVector<Expr*, 8> ClsExprs;
2323 QualType argType = Context->getPointerType(Context->CharTy);
2324 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2325 clsName->getLength(),
2326 false, argType, SourceLocation(),
2327 SourceLocation()));
2328 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2329 &ClsExprs[0],
2330 ClsExprs.size());
2331 MsgExprs.push_back(Cls);
2332 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002333 } else { // instance message.
2334 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002335
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002336 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002337 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002338 if (MsgSendStretFlavor)
2339 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002340 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2341
2342 llvm::SmallVector<Expr*, 4> InitExprs;
2343
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002344 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002345 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002346 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002347 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002348 SourceLocation()),
2349 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002350 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002351
2352 llvm::SmallVector<Expr*, 8> ClsExprs;
2353 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002354 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2355 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002356 false, argType, SourceLocation(),
2357 SourceLocation()));
2358 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002359 &ClsExprs[0],
2360 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002361 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002362 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002363 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002364 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002365 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002366 // struct objc_super
2367 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002368 Expr *SuperRep;
2369
2370 if (LangOpts.Microsoft) {
2371 SynthSuperContructorFunctionDecl();
2372 // Simulate a contructor call...
2373 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2374 superType, SourceLocation());
2375 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2376 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002377 // The code for super is a little tricky to prevent collision with
2378 // the structure definition in the header. The rewriter has it's own
2379 // internal definition (__rw_objc_super) that is uses. This is why
2380 // we need the cast below. For example:
2381 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2382 //
2383 SuperRep = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2384 Context->getPointerType(SuperRep->getType()),
2385 SourceLocation());
2386 SuperRep = new CStyleCastExpr(Context->getPointerType(superType),
2387 SuperRep, Context->getPointerType(superType),
2388 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002389 } else {
2390 // (struct objc_super) { <exprs from above> }
2391 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2392 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002393 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002394 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2395 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002396 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002397 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002398 // Remove all type-casts because it may contain objc-style types; e.g.
2399 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002400 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002401 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002402 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002403 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002404 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002405 MsgExprs.push_back(recExpr);
2406 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002407 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002408 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002409 llvm::SmallVector<Expr*, 8> SelExprs;
2410 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002411 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2412 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002413 false, argType, SourceLocation(),
2414 SourceLocation()));
2415 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2416 &SelExprs[0], SelExprs.size());
2417 MsgExprs.push_back(SelExp);
2418
2419 // Now push any user supplied arguments.
2420 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002421 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002422 // Make all implicit casts explicit...ICE comes in handy:-)
2423 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2424 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002425 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002426 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002427 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002428 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002429 }
2430 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002431 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002432 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002433 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002434 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002435 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002436 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002437 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002438 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002439 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002440 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002441 // We've transferred the ownership to MsgExprs. Null out the argument in
2442 // the original expression, since we will delete it below.
2443 Exp->setArg(i, 0);
2444 }
Steve Naroffab972d32007-11-04 22:37:50 +00002445 // Generate the funky cast.
2446 CastExpr *cast;
2447 llvm::SmallVector<QualType, 8> ArgTypes;
2448 QualType returnType;
2449
2450 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002451 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2452 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2453 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002454 ArgTypes.push_back(Context->getObjCIdType());
2455 ArgTypes.push_back(Context->getObjCSelType());
2456 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002457 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002458 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002459 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2460 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002461 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002462 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002463 if (isTopLevelBlockPointerType(t)) {
Steve Naroffa206b062008-10-29 14:49:46 +00002464 const BlockPointerType *BPT = t->getAsBlockPointerType();
2465 t = Context->getPointerType(BPT->getPointeeType());
2466 }
Steve Naroff352336b2007-11-05 14:36:37 +00002467 ArgTypes.push_back(t);
2468 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002469 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2470 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002471 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002472 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002473 }
2474 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002475 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002476
2477 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002478 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2479 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002480
2481 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2482 // If we don't do this cast, we get the following bizarre warning/note:
2483 // xx.m:13: warning: function called through a non-compatible type
2484 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002485 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002486 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002487 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002488
Steve Naroffab972d32007-11-04 22:37:50 +00002489 // Now do the "normal" pointer to function cast.
2490 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002491 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002492 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002493 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002494 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002495 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002496
2497 // Don't forget the parens to enforce the proper binding.
2498 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2499
2500 const FunctionType *FT = msgSendType->getAsFunctionType();
2501 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2502 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002503 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002504 if (MsgSendStretFlavor) {
2505 // We have the method which returns a struct/union. Must also generate
2506 // call to objc_msgSend_stret and hang both varieties on a conditional
2507 // expression which dictate which one to envoke depending on size of
2508 // method's return type.
2509
2510 // Create a reference to the objc_msgSend_stret() declaration.
2511 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2512 SourceLocation());
2513 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002514 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002515 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002516 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002517 // Now do the "normal" pointer to function cast.
2518 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002519 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002520 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002521 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002522 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002523
2524 // Don't forget the parens to enforce the proper binding.
2525 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2526
2527 FT = msgSendType->getAsFunctionType();
2528 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2529 FT->getResultType(), SourceLocation());
2530
2531 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002532 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2533 returnType.getAsOpaquePtr(),
2534 Context->getSizeType(),
2535 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002536 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2537 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2538 // For X86 it is more complicated and some kind of target specific routine
2539 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002540 unsigned IntSize =
2541 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002542 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2543 Context->IntTy,
2544 SourceLocation());
2545 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2546 BinaryOperator::LE,
2547 Context->IntTy,
2548 SourceLocation());
2549 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2550 ConditionalOperator *CondExpr =
2551 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002552 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002553 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002554 return ReplacingStmt;
2555}
2556
Steve Naroffb29b4272008-04-14 22:03:09 +00002557Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002558 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002559
Steve Naroffc77a6362008-12-04 16:24:46 +00002560 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002561 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002562 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002563
Steve Naroff4c3580e2008-12-04 23:50:32 +00002564 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002565 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002566}
2567
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002568/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2569/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002570Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002571 if (!GetProtocolFunctionDecl)
2572 SynthGetProtocolFunctionDecl();
2573 // Create a call to objc_getProtocol("ProtocolName").
2574 llvm::SmallVector<Expr*, 8> ProtoExprs;
2575 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002576 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2577 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002578 false, argType, SourceLocation(),
2579 SourceLocation()));
2580 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2581 &ProtoExprs[0],
2582 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002583 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002584 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002585 return ProtoExp;
2586
2587}
2588
Steve Naroffbaf58c32008-05-31 14:15:04 +00002589bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2590 const char *endBuf) {
2591 while (startBuf < endBuf) {
2592 if (*startBuf == '#') {
2593 // Skip whitespace.
2594 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2595 ;
2596 if (!strncmp(startBuf, "if", strlen("if")) ||
2597 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2598 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2599 !strncmp(startBuf, "define", strlen("define")) ||
2600 !strncmp(startBuf, "undef", strlen("undef")) ||
2601 !strncmp(startBuf, "else", strlen("else")) ||
2602 !strncmp(startBuf, "elif", strlen("elif")) ||
2603 !strncmp(startBuf, "endif", strlen("endif")) ||
2604 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2605 !strncmp(startBuf, "include", strlen("include")) ||
2606 !strncmp(startBuf, "import", strlen("import")) ||
2607 !strncmp(startBuf, "include_next", strlen("include_next")))
2608 return true;
2609 }
2610 startBuf++;
2611 }
2612 return false;
2613}
2614
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002615/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002616/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002617void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002618 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002619 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002620 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002621 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002622 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002623 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002624 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002625 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002626 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002627 SourceLocation LocStart = CDecl->getLocStart();
2628 SourceLocation LocEnd = CDecl->getLocEnd();
2629
2630 const char *startBuf = SM->getCharacterData(LocStart);
2631 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002632
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002633 // If no ivars and no root or if its root, directly or indirectly,
2634 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002635 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2636 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002637 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002638 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002639 return;
2640 }
2641
2642 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002643 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002644 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002645 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002646 if (LangOpts.Microsoft)
2647 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002648
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002649 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002650 const char *cursor = strchr(startBuf, '{');
2651 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002652 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002653 // If the buffer contains preprocessor directives, we do more fine-grained
2654 // rewrites. This is intended to fix code that looks like (which occurs in
2655 // NSURL.h, for example):
2656 //
2657 // #ifdef XYZ
2658 // @interface Foo : NSObject
2659 // #else
2660 // @interface FooBar : NSObject
2661 // #endif
2662 // {
2663 // int i;
2664 // }
2665 // @end
2666 //
2667 // This clause is segregated to avoid breaking the common case.
2668 if (BufferContainsPPDirectives(startBuf, cursor)) {
2669 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2670 CDecl->getClassLoc();
2671 const char *endHeader = SM->getCharacterData(L);
2672 endHeader += Lexer::MeasureTokenLength(L, *SM);
2673
Chris Lattner3db6cae2008-07-21 18:19:38 +00002674 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002675 // advance to the end of the referenced protocols.
2676 while (endHeader < cursor && *endHeader != '>') endHeader++;
2677 endHeader++;
2678 }
2679 // rewrite the original header
2680 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2681 } else {
2682 // rewrite the original header *without* disturbing the '{'
2683 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2684 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002685 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002686 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002687 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002688 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002689 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002690 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002691
2692 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002693 SourceLocation OnePastCurly =
2694 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2695 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002696 }
2697 cursor++; // past '{'
2698
2699 // Now comment out any visibility specifiers.
2700 while (cursor < endBuf) {
2701 if (*cursor == '@') {
2702 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002703 // Skip whitespace.
2704 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2705 /*scan*/;
2706
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002707 // FIXME: presence of @public, etc. inside comment results in
2708 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002709 if (!strncmp(cursor, "public", strlen("public")) ||
2710 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002711 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002712 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002713 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002714 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002715 // FIXME: If there are cases where '<' is used in ivar declaration part
2716 // of user code, then scan the ivar list and use needToScanForQualifiers
2717 // for type checking.
2718 else if (*cursor == '<') {
2719 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002720 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002721 cursor = strchr(cursor, '>');
2722 cursor++;
2723 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002724 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002725 } else if (*cursor == '^') { // rewrite block specifier.
2726 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2727 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002728 }
Steve Narofffea763e82007-11-14 19:25:57 +00002729 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002730 }
Steve Narofffea763e82007-11-14 19:25:57 +00002731 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002732 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002733 } else { // we don't have any instance variables - insert super struct.
2734 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2735 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002736 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002737 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002738 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002739 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002740 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002741 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002742 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002743 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002744 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002745}
2746
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002747// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002748/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002749void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002750 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002751 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002752 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002753 const char *ClassName,
2754 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002755 if (MethodBegin == MethodEnd) return;
2756
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002757 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002758 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002759 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002760 SEL _cmd;
2761 char *method_types;
2762 void *_imp;
2763 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002764 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002765 Result += "\nstruct _objc_method {\n";
2766 Result += "\tSEL _cmd;\n";
2767 Result += "\tchar *method_types;\n";
2768 Result += "\tvoid *_imp;\n";
2769 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002770
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002771 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002772 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002773
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002774 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002775
2776 /* struct {
2777 struct _objc_method_list *next_method;
2778 int method_count;
2779 struct _objc_method method_list[];
2780 }
2781 */
2782 Result += "\nstatic struct {\n";
2783 Result += "\tstruct _objc_method_list *next_method;\n";
2784 Result += "\tint method_count;\n";
2785 Result += "\tstruct _objc_method method_list[";
2786 Result += utostr(MethodEnd-MethodBegin);
2787 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002788 Result += prefix;
2789 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2790 Result += "_METHODS_";
2791 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002792 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002793 Result += IsInstanceMethod ? "inst" : "cls";
2794 Result += "_meth\")))= ";
2795 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002796
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002797 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002798 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002799 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002800 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002801 Result += "\", \"";
2802 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002803 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002804 Result += MethodInternalNames[*MethodBegin];
2805 Result += "}\n";
2806 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2807 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002808 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002809 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002810 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002811 Result += "\", \"";
2812 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002813 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002814 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002815 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002816 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002817 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002818}
2819
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002820/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002821void RewriteObjC::
2822RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2823 const char *prefix,
2824 const char *ClassName,
2825 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002826 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002827 if (Protocols.empty()) return;
2828
2829 for (unsigned i = 0; i != Protocols.size(); i++) {
2830 ObjCProtocolDecl *PDecl = Protocols[i];
2831 // Output struct protocol_methods holder of method selector and type.
2832 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2833 /* struct protocol_methods {
2834 SEL _cmd;
2835 char *method_types;
2836 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002837 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002838 Result += "\nstruct protocol_methods {\n";
2839 Result += "\tSEL _cmd;\n";
2840 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002841 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002842
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002843 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002844 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002845 // Do not synthesize the protocol more than once.
2846 if (ObjCSynthesizedProtocols.count(PDecl))
2847 continue;
2848
2849 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2850 unsigned NumMethods = PDecl->getNumInstanceMethods();
2851 /* struct _objc_protocol_method_list {
2852 int protocol_method_count;
2853 struct protocol_methods protocols[];
2854 }
2855 */
2856 Result += "\nstatic struct {\n";
2857 Result += "\tint protocol_method_count;\n";
2858 Result += "\tstruct protocol_methods protocols[";
2859 Result += utostr(NumMethods);
2860 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002861 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002862 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2863 "{\n\t" + utostr(NumMethods) + "\n";
2864
2865 // Output instance methods declared in this protocol.
2866 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2867 E = PDecl->instmeth_end(); I != E; ++I) {
2868 if (I == PDecl->instmeth_begin())
2869 Result += "\t ,{{(SEL)\"";
2870 else
2871 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002872 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002873 std::string MethodTypeString;
2874 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2875 Result += "\", \"";
2876 Result += MethodTypeString;
2877 Result += "\"}\n";
2878 }
2879 Result += "\t }\n};\n";
2880 }
2881
2882 // Output class methods declared in this protocol.
2883 int NumMethods = PDecl->getNumClassMethods();
2884 if (NumMethods > 0) {
2885 /* struct _objc_protocol_method_list {
2886 int protocol_method_count;
2887 struct protocol_methods protocols[];
2888 }
2889 */
2890 Result += "\nstatic struct {\n";
2891 Result += "\tint protocol_method_count;\n";
2892 Result += "\tstruct protocol_methods protocols[";
2893 Result += utostr(NumMethods);
2894 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002895 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002896 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2897 "{\n\t";
2898 Result += utostr(NumMethods);
2899 Result += "\n";
2900
2901 // Output instance methods declared in this protocol.
2902 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2903 E = PDecl->classmeth_end(); I != E; ++I) {
2904 if (I == PDecl->classmeth_begin())
2905 Result += "\t ,{{(SEL)\"";
2906 else
2907 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002908 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002909 std::string MethodTypeString;
2910 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2911 Result += "\", \"";
2912 Result += MethodTypeString;
2913 Result += "\"}\n";
2914 }
2915 Result += "\t }\n};\n";
2916 }
2917
2918 // Output:
2919 /* struct _objc_protocol {
2920 // Objective-C 1.0 extensions
2921 struct _objc_protocol_extension *isa;
2922 char *protocol_name;
2923 struct _objc_protocol **protocol_list;
2924 struct _objc_protocol_method_list *instance_methods;
2925 struct _objc_protocol_method_list *class_methods;
2926 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002927 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002928 static bool objc_protocol = false;
2929 if (!objc_protocol) {
2930 Result += "\nstruct _objc_protocol {\n";
2931 Result += "\tstruct _objc_protocol_extension *isa;\n";
2932 Result += "\tchar *protocol_name;\n";
2933 Result += "\tstruct _objc_protocol **protocol_list;\n";
2934 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2935 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2936 Result += "};\n";
2937
2938 objc_protocol = true;
2939 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002940
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002941 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002942 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002943 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2944 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002945 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002946 Result += "\", 0, ";
2947 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2948 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002949 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002950 Result += ", ";
2951 }
2952 else
2953 Result += "0, ";
2954 if (PDecl->getNumClassMethods() > 0) {
2955 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002956 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002957 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002958 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002959 else
2960 Result += "0\n";
2961 Result += "};\n";
2962
2963 // Mark this protocol as having been generated.
2964 if (!ObjCSynthesizedProtocols.insert(PDecl))
2965 assert(false && "protocol already synthesized");
2966 }
2967 // Output the top lovel protocol meta-data for the class.
2968 /* struct _objc_protocol_list {
2969 struct _objc_protocol_list *next;
2970 int protocol_count;
2971 struct _objc_protocol *class_protocols[];
2972 }
2973 */
2974 Result += "\nstatic struct {\n";
2975 Result += "\tstruct _objc_protocol_list *next;\n";
2976 Result += "\tint protocol_count;\n";
2977 Result += "\tstruct _objc_protocol *class_protocols[";
2978 Result += utostr(Protocols.size());
2979 Result += "];\n} _OBJC_";
2980 Result += prefix;
2981 Result += "_PROTOCOLS_";
2982 Result += ClassName;
2983 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2984 "{\n\t0, ";
2985 Result += utostr(Protocols.size());
2986 Result += "\n";
2987
2988 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002989 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002990 Result += " \n";
2991
2992 for (unsigned i = 1; i != Protocols.size(); i++) {
2993 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002994 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002995 Result += "\n";
2996 }
2997 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002998}
2999
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003000/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003001/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003002void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003003 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003004 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003005 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003006 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003007 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3008 CDecl = CDecl->getNextClassCategory())
3009 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3010 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003011
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003012 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003013 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003014 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003015
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003016 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003017 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003018 true, "CATEGORY_", FullCategoryName.c_str(),
3019 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003020
3021 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003022 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003023 false, "CATEGORY_", FullCategoryName.c_str(),
3024 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003025
3026 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003027 // Null CDecl is case of a category implementation with no category interface
3028 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003029 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003030 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003031
3032 /* struct _objc_category {
3033 char *category_name;
3034 char *class_name;
3035 struct _objc_method_list *instance_methods;
3036 struct _objc_method_list *class_methods;
3037 struct _objc_protocol_list *protocols;
3038 // Objective-C 1.0 extensions
3039 uint32_t size; // sizeof (struct _objc_category)
3040 struct _objc_property_list *instance_properties; // category's own
3041 // @property decl.
3042 };
3043 */
3044
3045 static bool objc_category = false;
3046 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003047 Result += "\nstruct _objc_category {\n";
3048 Result += "\tchar *category_name;\n";
3049 Result += "\tchar *class_name;\n";
3050 Result += "\tstruct _objc_method_list *instance_methods;\n";
3051 Result += "\tstruct _objc_method_list *class_methods;\n";
3052 Result += "\tstruct _objc_protocol_list *protocols;\n";
3053 Result += "\tunsigned int size;\n";
3054 Result += "\tstruct _objc_property_list *instance_properties;\n";
3055 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003056 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003057 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003058 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3059 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003060 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003061 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003062 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003063 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003064 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003065
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003066 if (IDecl->getNumInstanceMethods() > 0) {
3067 Result += "\t, (struct _objc_method_list *)"
3068 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3069 Result += FullCategoryName;
3070 Result += "\n";
3071 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003072 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003073 Result += "\t, 0\n";
3074 if (IDecl->getNumClassMethods() > 0) {
3075 Result += "\t, (struct _objc_method_list *)"
3076 "&_OBJC_CATEGORY_CLASS_METHODS_";
3077 Result += FullCategoryName;
3078 Result += "\n";
3079 }
3080 else
3081 Result += "\t, 0\n";
3082
Chris Lattner780f3292008-07-21 21:32:27 +00003083 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003084 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3085 Result += FullCategoryName;
3086 Result += "\n";
3087 }
3088 else
3089 Result += "\t, 0\n";
3090 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003091}
3092
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003093/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3094/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003095void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003096 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003097 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003098 if (ivar->isBitField()) {
3099 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3100 // place all bitfields at offset 0.
3101 Result += "0";
3102 } else {
3103 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003104 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003105 if (LangOpts.Microsoft)
3106 Result += "_IMPL";
3107 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003108 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003109 Result += ")";
3110 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003111}
3112
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003113//===----------------------------------------------------------------------===//
3114// Meta Data Emission
3115//===----------------------------------------------------------------------===//
3116
Steve Naroffb29b4272008-04-14 22:03:09 +00003117void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003118 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003119 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003120
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003121 // Explictly declared @interface's are already synthesized.
3122 if (CDecl->ImplicitInterfaceDecl()) {
3123 // FIXME: Implementation of a class with no @interface (legacy) doese not
3124 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003125 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003126 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003127
Chris Lattnerbe6df082007-12-12 07:56:42 +00003128 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003129 unsigned NumIvars = !IDecl->ivar_empty()
3130 ? IDecl->ivar_size()
3131 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003132 if (NumIvars > 0) {
3133 static bool objc_ivar = false;
3134 if (!objc_ivar) {
3135 /* struct _objc_ivar {
3136 char *ivar_name;
3137 char *ivar_type;
3138 int ivar_offset;
3139 };
3140 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003141 Result += "\nstruct _objc_ivar {\n";
3142 Result += "\tchar *ivar_name;\n";
3143 Result += "\tchar *ivar_type;\n";
3144 Result += "\tint ivar_offset;\n";
3145 Result += "};\n";
3146
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003147 objc_ivar = true;
3148 }
3149
Steve Naroff946a6932008-03-11 00:12:29 +00003150 /* struct {
3151 int ivar_count;
3152 struct _objc_ivar ivar_list[nIvars];
3153 };
3154 */
3155 Result += "\nstatic struct {\n";
3156 Result += "\tint ivar_count;\n";
3157 Result += "\tstruct _objc_ivar ivar_list[";
3158 Result += utostr(NumIvars);
3159 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003160 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003161 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003162 "{\n\t";
3163 Result += utostr(NumIvars);
3164 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003165
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003166 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003167 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003168 IVI = IDecl->ivar_begin();
3169 IVE = IDecl->ivar_end();
3170 } else {
3171 IVI = CDecl->ivar_begin();
3172 IVE = CDecl->ivar_end();
3173 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003174 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003175 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003176 Result += "\", \"";
3177 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003178 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003179 Result += StrEncoding;
3180 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003181 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003182 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003183 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003184 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003185 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003186 Result += "\", \"";
3187 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003188 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003189 Result += StrEncoding;
3190 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003191 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003192 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003193 }
3194
3195 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003196 }
3197
3198 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003199 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003200 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003201
3202 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003203 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003204 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003205
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003206 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003207 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003208 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003209
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003210
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003211 // Declaration of class/meta-class metadata
3212 /* struct _objc_class {
3213 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003214 const char *super_class_name;
3215 char *name;
3216 long version;
3217 long info;
3218 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003219 struct _objc_ivar_list *ivars;
3220 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003221 struct objc_cache *cache;
3222 struct objc_protocol_list *protocols;
3223 const char *ivar_layout;
3224 struct _objc_class_ext *ext;
3225 };
3226 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003227 static bool objc_class = false;
3228 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003229 Result += "\nstruct _objc_class {\n";
3230 Result += "\tstruct _objc_class *isa;\n";
3231 Result += "\tconst char *super_class_name;\n";
3232 Result += "\tchar *name;\n";
3233 Result += "\tlong version;\n";
3234 Result += "\tlong info;\n";
3235 Result += "\tlong instance_size;\n";
3236 Result += "\tstruct _objc_ivar_list *ivars;\n";
3237 Result += "\tstruct _objc_method_list *methods;\n";
3238 Result += "\tstruct objc_cache *cache;\n";
3239 Result += "\tstruct _objc_protocol_list *protocols;\n";
3240 Result += "\tconst char *ivar_layout;\n";
3241 Result += "\tstruct _objc_class_ext *ext;\n";
3242 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003243 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003244 }
3245
3246 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003247 ObjCInterfaceDecl *RootClass = 0;
3248 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003249 while (SuperClass) {
3250 RootClass = SuperClass;
3251 SuperClass = SuperClass->getSuperClass();
3252 }
3253 SuperClass = CDecl->getSuperClass();
3254
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003255 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003256 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003257 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003258 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003259 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003260 Result += "\"";
3261
3262 if (SuperClass) {
3263 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003264 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003265 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003266 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003267 Result += "\"";
3268 }
3269 else {
3270 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003271 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003272 Result += "\"";
3273 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003274 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003275 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003276 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003277 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003278 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003279 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003280 Result += "\n";
3281 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003282 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003283 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003284 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003285 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003286 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003287 Result += ",0,0\n";
3288 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003289 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003290 Result += "\t,0,0,0,0\n";
3291 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003292
3293 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003294 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003295 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003296 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003297 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003298 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003299 if (SuperClass) {
3300 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003301 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003302 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003303 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003304 Result += "\"";
3305 }
3306 else {
3307 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003308 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003309 Result += "\"";
3310 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003311 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003312 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003313 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003314 Result += ",0";
3315 else {
3316 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003317 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003318 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003319 if (LangOpts.Microsoft)
3320 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003321 Result += ")";
3322 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003323 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003324 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003325 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003326 Result += "\n\t";
3327 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003328 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003329 Result += ",0";
3330 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003331 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003332 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003333 Result += ", 0\n\t";
3334 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003335 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003336 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003337 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003338 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003339 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003340 Result += ", 0,0\n";
3341 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003342 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003343 Result += ",0,0,0\n";
3344 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003345}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003346
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003347/// RewriteImplementations - This routine rewrites all method implementations
3348/// and emits meta-data.
3349
Steve Narofface66252008-11-13 20:07:04 +00003350void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003351 int ClsDefCount = ClassImplementation.size();
3352 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003353
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003354 // Rewrite implemented methods
3355 for (int i = 0; i < ClsDefCount; i++)
3356 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003357
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003358 for (int i = 0; i < CatDefCount; i++)
3359 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003360}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003361
Steve Narofface66252008-11-13 20:07:04 +00003362void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3363 int ClsDefCount = ClassImplementation.size();
3364 int CatDefCount = CategoryImplementation.size();
3365
Steve Naroff5df5b762008-05-07 21:23:49 +00003366 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003367 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003368 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003369 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003370 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003371
3372 // For each implemented category, write out all its meta data.
3373 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003374 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003375
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003376 // Write objc_symtab metadata
3377 /*
3378 struct _objc_symtab
3379 {
3380 long sel_ref_cnt;
3381 SEL *refs;
3382 short cls_def_cnt;
3383 short cat_def_cnt;
3384 void *defs[cls_def_cnt + cat_def_cnt];
3385 };
3386 */
3387
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003388 Result += "\nstruct _objc_symtab {\n";
3389 Result += "\tlong sel_ref_cnt;\n";
3390 Result += "\tSEL *refs;\n";
3391 Result += "\tshort cls_def_cnt;\n";
3392 Result += "\tshort cat_def_cnt;\n";
3393 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3394 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003395
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003396 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003397 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003398 Result += "\t0, 0, " + utostr(ClsDefCount)
3399 + ", " + utostr(CatDefCount) + "\n";
3400 for (int i = 0; i < ClsDefCount; i++) {
3401 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003402 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003403 Result += "\n";
3404 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003405
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003406 for (int i = 0; i < CatDefCount; i++) {
3407 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003408 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003409 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003410 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003411 Result += "\n";
3412 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003413
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003414 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003415
3416 // Write objc_module metadata
3417
3418 /*
3419 struct _objc_module {
3420 long version;
3421 long size;
3422 const char *name;
3423 struct _objc_symtab *symtab;
3424 }
3425 */
3426
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003427 Result += "\nstruct _objc_module {\n";
3428 Result += "\tlong version;\n";
3429 Result += "\tlong size;\n";
3430 Result += "\tconst char *name;\n";
3431 Result += "\tstruct _objc_symtab *symtab;\n";
3432 Result += "};\n\n";
3433 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003434 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003435 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3436 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003437 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003438
3439 if (LangOpts.Microsoft) {
3440 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003441 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003442 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3443 Result += "&_OBJC_MODULES;\n";
3444 Result += "#pragma data_seg(pop)\n\n";
3445 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003446}
Chris Lattner311ff022007-10-16 22:36:42 +00003447
Steve Naroff54055232008-10-27 17:20:55 +00003448std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3449 const char *funcName,
3450 std::string Tag) {
3451 const FunctionType *AFT = CE->getFunctionType();
3452 QualType RT = AFT->getResultType();
3453 std::string StructRef = "struct " + Tag;
3454 std::string S = "static " + RT.getAsString() + " __" +
3455 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003456
Steve Naroff54055232008-10-27 17:20:55 +00003457 BlockDecl *BD = CE->getBlockDecl();
3458
3459 if (isa<FunctionTypeNoProto>(AFT)) {
3460 S += "()";
3461 } else if (BD->param_empty()) {
3462 S += "(" + StructRef + " *__cself)";
3463 } else {
3464 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3465 assert(FT && "SynthesizeBlockFunc: No function proto");
3466 S += '(';
3467 // first add the implicit argument.
3468 S += StructRef + " *__cself, ";
3469 std::string ParamStr;
3470 for (BlockDecl::param_iterator AI = BD->param_begin(),
3471 E = BD->param_end(); AI != E; ++AI) {
3472 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003473 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003474 (*AI)->getType().getAsStringInternal(ParamStr);
3475 S += ParamStr;
3476 }
3477 if (FT->isVariadic()) {
3478 if (!BD->param_empty()) S += ", ";
3479 S += "...";
3480 }
3481 S += ')';
3482 }
3483 S += " {\n";
3484
3485 // Create local declarations to avoid rewriting all closure decl ref exprs.
3486 // First, emit a declaration for all "by ref" decls.
3487 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3488 E = BlockByRefDecls.end(); I != E; ++I) {
3489 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003490 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003491 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003492 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003493 }
3494 // Next, emit a declaration for all "by copy" declarations.
3495 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3496 E = BlockByCopyDecls.end(); I != E; ++I) {
3497 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003498 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003499 // Handle nested closure invocation. For example:
3500 //
3501 // void (^myImportedClosure)(void);
3502 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3503 //
3504 // void (^anotherClosure)(void);
3505 // anotherClosure = ^(void) {
3506 // myImportedClosure(); // import and invoke the closure
3507 // };
3508 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003509 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003510 S += "struct __block_impl *";
3511 else
3512 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003513 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003514 }
3515 std::string RewrittenStr = RewrittenBlockExprs[CE];
3516 const char *cstr = RewrittenStr.c_str();
3517 while (*cstr++ != '{') ;
3518 S += cstr;
3519 S += "\n";
3520 return S;
3521}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003522
Steve Naroff54055232008-10-27 17:20:55 +00003523std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3524 const char *funcName,
3525 std::string Tag) {
3526 std::string StructRef = "struct " + Tag;
3527 std::string S = "static void __";
3528
3529 S += funcName;
3530 S += "_block_copy_" + utostr(i);
3531 S += "(" + StructRef;
3532 S += "*dst, " + StructRef;
3533 S += "*src) {";
3534 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3535 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003536 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003537 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003538 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003539 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003540 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff54055232008-10-27 17:20:55 +00003541 }
3542 S += "\nstatic void __";
3543 S += funcName;
3544 S += "_block_dispose_" + utostr(i);
3545 S += "(" + StructRef;
3546 S += "*src) {";
3547 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3548 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003549 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003550 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003551 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003552 }
3553 S += "}\n";
3554 return S;
3555}
3556
3557std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3558 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003559 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003560 std::string Constructor = " " + Tag;
3561
3562 S += " {\n struct __block_impl impl;\n";
3563
3564 if (hasCopyDisposeHelpers)
3565 S += " void *copy;\n void *dispose;\n";
3566
3567 Constructor += "(void *fp";
3568
3569 if (hasCopyDisposeHelpers)
3570 Constructor += ", void *copyHelp, void *disposeHelp";
3571
3572 if (BlockDeclRefs.size()) {
3573 // Output all "by copy" declarations.
3574 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3575 E = BlockByCopyDecls.end(); I != E; ++I) {
3576 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003577 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003578 std::string ArgName = "_" + FieldName;
3579 // Handle nested closure invocation. For example:
3580 //
3581 // void (^myImportedBlock)(void);
3582 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3583 //
3584 // void (^anotherBlock)(void);
3585 // anotherBlock = ^(void) {
3586 // myImportedBlock(); // import and invoke the closure
3587 // };
3588 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003589 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003590 S += "struct __block_impl *";
3591 Constructor += ", void *" + ArgName;
3592 } else {
3593 (*I)->getType().getAsStringInternal(FieldName);
3594 (*I)->getType().getAsStringInternal(ArgName);
3595 Constructor += ", " + ArgName;
3596 }
3597 S += FieldName + ";\n";
3598 }
3599 // Output all "by ref" declarations.
3600 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3601 E = BlockByRefDecls.end(); I != E; ++I) {
3602 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003603 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003604 std::string ArgName = "_" + FieldName;
3605 // Handle nested closure invocation. For example:
3606 //
3607 // void (^myImportedBlock)(void);
3608 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3609 //
3610 // void (^anotherBlock)(void);
3611 // anotherBlock = ^(void) {
3612 // myImportedBlock(); // import and invoke the closure
3613 // };
3614 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003615 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003616 S += "struct __block_impl *";
3617 Constructor += ", void *" + ArgName;
3618 } else {
3619 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3620 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3621 Constructor += ", " + ArgName;
3622 }
3623 S += FieldName + "; // by ref\n";
3624 }
3625 // Finish writing the constructor.
3626 // FIXME: handle NSConcreteGlobalBlock.
3627 Constructor += ", int flags=0) {\n";
3628 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3629 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3630
3631 if (hasCopyDisposeHelpers)
3632 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3633
3634 // Initialize all "by copy" arguments.
3635 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3636 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003637 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003638 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003639 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003640 Constructor += Name + " = (struct __block_impl *)_";
3641 else
3642 Constructor += Name + " = _";
3643 Constructor += Name + ";\n";
3644 }
3645 // Initialize all "by ref" arguments.
3646 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3647 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003648 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003649 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003650 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003651 Constructor += Name + " = (struct __block_impl *)_";
3652 else
3653 Constructor += Name + " = _";
3654 Constructor += Name + ";\n";
3655 }
3656 } else {
3657 // Finish writing the constructor.
3658 // FIXME: handle NSConcreteGlobalBlock.
3659 Constructor += ", int flags=0) {\n";
3660 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3661 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3662 if (hasCopyDisposeHelpers)
3663 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3664 }
3665 Constructor += " ";
3666 Constructor += "}\n";
3667 S += Constructor;
3668 S += "};\n";
3669 return S;
3670}
3671
3672void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3673 const char *FunName) {
3674 // Insert closures that were part of the function.
3675 for (unsigned i = 0; i < Blocks.size(); i++) {
3676
3677 CollectBlockDeclRefInfo(Blocks[i]);
3678
3679 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3680
3681 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3682 ImportedBlockDecls.size() > 0);
3683
3684 InsertText(FunLocStart, CI.c_str(), CI.size());
3685
3686 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3687
3688 InsertText(FunLocStart, CF.c_str(), CF.size());
3689
3690 if (ImportedBlockDecls.size()) {
3691 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3692 InsertText(FunLocStart, HF.c_str(), HF.size());
3693 }
3694
3695 BlockDeclRefs.clear();
3696 BlockByRefDecls.clear();
3697 BlockByCopyDecls.clear();
3698 BlockCallExprs.clear();
3699 ImportedBlockDecls.clear();
3700 }
3701 Blocks.clear();
3702 RewrittenBlockExprs.clear();
3703}
3704
3705void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3706 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003707 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003708
3709 SynthesizeBlockLiterals(FunLocStart, FuncName);
3710}
3711
3712void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003713 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3714 //SourceLocation FunLocStart = MD->getLocStart();
3715 // FIXME: This hack works around a bug in Rewrite.InsertText().
3716 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003717 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003718 // Convert colons to underscores.
3719 std::string::size_type loc = 0;
3720 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3721 FuncName.replace(loc, 1, "_");
3722
3723 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3724}
3725
3726void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3727 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3728 CI != E; ++CI)
3729 if (*CI) {
3730 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3731 GetBlockDeclRefExprs(CBE->getBody());
3732 else
3733 GetBlockDeclRefExprs(*CI);
3734 }
3735 // Handle specific things.
3736 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3737 // FIXME: Handle enums.
3738 if (!isa<FunctionDecl>(CDRE->getDecl()))
3739 BlockDeclRefs.push_back(CDRE);
3740 return;
3741}
3742
3743void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3744 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3745 CI != E; ++CI)
3746 if (*CI) {
3747 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3748 GetBlockCallExprs(CBE->getBody());
3749 else
3750 GetBlockCallExprs(*CI);
3751 }
3752
3753 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3754 if (CE->getCallee()->getType()->isBlockPointerType()) {
3755 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3756 }
3757 }
3758 return;
3759}
3760
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003761Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003762 // Navigate to relevant type information.
3763 const char *closureName = 0;
3764 const BlockPointerType *CPT = 0;
3765
3766 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003767 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003768 CPT = DRE->getType()->getAsBlockPointerType();
3769 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003770 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003771 CPT = CDRE->getType()->getAsBlockPointerType();
3772 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003773 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003774 CPT = MExpr->getType()->getAsBlockPointerType();
3775 } else {
3776 assert(1 && "RewriteBlockClass: Bad type");
3777 }
3778 assert(CPT && "RewriteBlockClass: Bad type");
3779 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3780 assert(FT && "RewriteBlockClass: Bad type");
3781 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3782 // FTP will be null for closures that don't take arguments.
3783
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003784 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3785 SourceLocation(),
3786 &Context->Idents.get("__block_impl"));
3787 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003788
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003789 // Generate a funky cast.
3790 llvm::SmallVector<QualType, 8> ArgTypes;
3791
3792 // Push the block argument type.
3793 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003794 if (FTP) {
3795 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003796 E = FTP->arg_type_end(); I && (I != E); ++I) {
3797 QualType t = *I;
3798 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003799 if (isTopLevelBlockPointerType(t)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003800 const BlockPointerType *BPT = t->getAsBlockPointerType();
3801 t = Context->getPointerType(BPT->getPointeeType());
3802 }
3803 ArgTypes.push_back(t);
3804 }
Steve Naroff54055232008-10-27 17:20:55 +00003805 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003806 // Now do the pointer to function cast.
3807 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3808 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3809
3810 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003811
Steve Naroffb2f9e512008-11-03 23:29:32 +00003812 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003813 // Don't forget the parens to enforce the proper binding.
3814 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3815 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003816
Douglas Gregor44b43212008-12-11 16:49:14 +00003817 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3818 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
3819 /*BitWidth=*/0, /*Mutable=*/true, 0);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003820 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3821
Steve Naroffb2f9e512008-11-03 23:29:32 +00003822 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003823 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3824
3825 llvm::SmallVector<Expr*, 8> BlkExprs;
3826 // Add the implicit argument.
3827 BlkExprs.push_back(BlkCast);
3828 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003829 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3830 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003831 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003832 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003833 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3834 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003835}
3836
3837void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003838 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3839 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003840}
3841
3842void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3843 // FIXME: Add more elaborate code generation required by the ABI.
3844 InsertText(BDRE->getLocStart(), "*", 1);
3845}
3846
Steve Naroffb2f9e512008-11-03 23:29:32 +00003847void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3848 SourceLocation LocStart = CE->getLParenLoc();
3849 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003850
3851 // Need to avoid trying to rewrite synthesized casts.
3852 if (LocStart.isInvalid())
3853 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003854 // Need to avoid trying to rewrite casts contained in macros.
3855 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3856 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003857
Steve Naroff54055232008-10-27 17:20:55 +00003858 const char *startBuf = SM->getCharacterData(LocStart);
3859 const char *endBuf = SM->getCharacterData(LocEnd);
3860
3861 // advance the location to startArgList.
3862 const char *argPtr = startBuf;
3863
3864 while (*argPtr++ && (argPtr < endBuf)) {
3865 switch (*argPtr) {
3866 case '^':
3867 // Replace the '^' with '*'.
3868 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3869 ReplaceText(LocStart, 1, "*", 1);
3870 break;
3871 }
3872 }
3873 return;
3874}
3875
3876void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3877 SourceLocation DeclLoc = FD->getLocation();
3878 unsigned parenCount = 0;
3879
3880 // We have 1 or more arguments that have closure pointers.
3881 const char *startBuf = SM->getCharacterData(DeclLoc);
3882 const char *startArgList = strchr(startBuf, '(');
3883
3884 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3885
3886 parenCount++;
3887 // advance the location to startArgList.
3888 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3889 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3890
3891 const char *argPtr = startArgList;
3892
3893 while (*argPtr++ && parenCount) {
3894 switch (*argPtr) {
3895 case '^':
3896 // Replace the '^' with '*'.
3897 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3898 ReplaceText(DeclLoc, 1, "*", 1);
3899 break;
3900 case '(':
3901 parenCount++;
3902 break;
3903 case ')':
3904 parenCount--;
3905 break;
3906 }
3907 }
3908 return;
3909}
3910
3911bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3912 const FunctionTypeProto *FTP;
3913 const PointerType *PT = QT->getAsPointerType();
3914 if (PT) {
3915 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3916 } else {
3917 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3918 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3919 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3920 }
3921 if (FTP) {
3922 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3923 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003924 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00003925 return true;
3926 }
3927 return false;
3928}
3929
3930void RewriteObjC::GetExtentOfArgList(const char *Name,
3931 const char *&LParen, const char *&RParen) {
3932 const char *argPtr = strchr(Name, '(');
3933 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3934
3935 LParen = argPtr; // output the start.
3936 argPtr++; // skip past the left paren.
3937 unsigned parenCount = 1;
3938
3939 while (*argPtr && parenCount) {
3940 switch (*argPtr) {
3941 case '(': parenCount++; break;
3942 case ')': parenCount--; break;
3943 default: break;
3944 }
3945 if (parenCount) argPtr++;
3946 }
3947 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3948 RParen = argPtr; // output the end
3949}
3950
3951void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3952 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3953 RewriteBlockPointerFunctionArgs(FD);
3954 return;
3955 }
3956 // Handle Variables and Typedefs.
3957 SourceLocation DeclLoc = ND->getLocation();
3958 QualType DeclT;
3959 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3960 DeclT = VD->getType();
3961 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3962 DeclT = TDD->getUnderlyingType();
3963 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3964 DeclT = FD->getType();
3965 else
3966 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3967
3968 const char *startBuf = SM->getCharacterData(DeclLoc);
3969 const char *endBuf = startBuf;
3970 // scan backward (from the decl location) for the end of the previous decl.
3971 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3972 startBuf--;
3973
3974 // *startBuf != '^' if we are dealing with a pointer to function that
3975 // may take block argument types (which will be handled below).
3976 if (*startBuf == '^') {
3977 // Replace the '^' with '*', computing a negative offset.
3978 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3979 ReplaceText(DeclLoc, 1, "*", 1);
3980 }
3981 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3982 // Replace the '^' with '*' for arguments.
3983 DeclLoc = ND->getLocation();
3984 startBuf = SM->getCharacterData(DeclLoc);
3985 const char *argListBegin, *argListEnd;
3986 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3987 while (argListBegin < argListEnd) {
3988 if (*argListBegin == '^') {
3989 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3990 ReplaceText(CaretLoc, 1, "*", 1);
3991 }
3992 argListBegin++;
3993 }
3994 }
3995 return;
3996}
3997
3998void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3999 // Add initializers for any closure decl refs.
4000 GetBlockDeclRefExprs(Exp->getBody());
4001 if (BlockDeclRefs.size()) {
4002 // Unique all "by copy" declarations.
4003 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4004 if (!BlockDeclRefs[i]->isByRef())
4005 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4006 // Unique all "by ref" declarations.
4007 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4008 if (BlockDeclRefs[i]->isByRef()) {
4009 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4010 }
4011 // Find any imported blocks...they will need special attention.
4012 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff47a24222008-12-11 20:51:38 +00004013 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004014 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004015 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4016 }
4017 }
4018}
4019
Steve Narofffa15fd92008-10-28 20:29:00 +00004020FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4021 IdentifierInfo *ID = &Context->Idents.get(name);
4022 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
4023 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
4024 ID, FType, FunctionDecl::Extern, false, 0);
4025}
4026
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004027Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004028 Blocks.push_back(Exp);
4029
4030 CollectBlockDeclRefInfo(Exp);
4031 std::string FuncName;
4032
4033 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004034 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004035 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004036 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004037 // Convert colons to underscores.
4038 std::string::size_type loc = 0;
4039 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4040 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004041 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004042 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004043
4044 std::string BlockNumber = utostr(Blocks.size()-1);
4045
4046 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4047 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4048
4049 // Get a pointer to the function type so we can cast appropriately.
4050 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4051
4052 FunctionDecl *FD;
4053 Expr *NewRep;
4054
4055 // Simulate a contructor call...
4056 FD = SynthBlockInitFunctionDecl(Tag.c_str());
4057 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
4058
4059 llvm::SmallVector<Expr*, 4> InitExprs;
4060
Steve Narofffdc03722008-10-29 21:23:59 +00004061 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004062 FD = SynthBlockInitFunctionDecl(Func.c_str());
4063 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4064 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004065 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004066 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004067
4068 if (ImportedBlockDecls.size()) {
4069 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004070 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4071 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4072 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004073 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004074 InitExprs.push_back(castExpr);
4075
Steve Narofffa15fd92008-10-28 20:29:00 +00004076 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004077 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4078 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4079 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004080 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004081 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004082 }
4083 // Add initializers for any closure decl refs.
4084 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004085 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004086 // Output all "by copy" declarations.
4087 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4088 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004089 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004090 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004091 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004092 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004093 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004094 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004095 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4096 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004097 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004098 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004099 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004100 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004101 }
Steve Narofffdc03722008-10-29 21:23:59 +00004102 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004103 }
4104 // Output all "by ref" declarations.
4105 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4106 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004107 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004108 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4109 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
4110 Context->getPointerType(Exp->getType()),
4111 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004112 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004113 }
4114 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004115 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
4116 FType, SourceLocation());
4117 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
4118 Context->getPointerType(NewRep->getType()),
4119 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00004120 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004121 BlockDeclRefs.clear();
4122 BlockByRefDecls.clear();
4123 BlockByCopyDecls.clear();
4124 ImportedBlockDecls.clear();
4125 return NewRep;
4126}
4127
4128//===----------------------------------------------------------------------===//
4129// Function Body / Expression rewriting
4130//===----------------------------------------------------------------------===//
4131
Steve Naroffc77a6362008-12-04 16:24:46 +00004132// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4133// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4134// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4135// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4136// Since the rewriter isn't capable of rewriting rewritten code, it's important
4137// we get this right.
4138void RewriteObjC::CollectPropertySetters(Stmt *S) {
4139 // Perform a bottom up traversal of all children.
4140 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4141 CI != E; ++CI)
4142 if (*CI)
4143 CollectPropertySetters(*CI);
4144
4145 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4146 if (BinOp->isAssignmentOp()) {
4147 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4148 PropSetters[PRE] = BinOp;
4149 }
4150 }
4151}
4152
Steve Narofffa15fd92008-10-28 20:29:00 +00004153Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4154 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4155 isa<DoStmt>(S) || isa<ForStmt>(S))
4156 Stmts.push_back(S);
4157 else if (isa<ObjCForCollectionStmt>(S)) {
4158 Stmts.push_back(S);
4159 ObjCBcLabelNo.push_back(++BcLabelCount);
4160 }
4161
4162 SourceRange OrigStmtRange = S->getSourceRange();
4163
4164 // Perform a bottom up rewrite of all children.
4165 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4166 CI != E; ++CI)
4167 if (*CI) {
4168 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4169 if (newStmt)
4170 *CI = newStmt;
4171 }
4172
4173 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4174 // Rewrite the block body in place.
4175 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4176
4177 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004178 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4179 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004180
4181 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4182 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004183 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004184 return blockTranscribed;
4185 }
4186 // Handle specific things.
4187 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4188 return RewriteAtEncode(AtEncode);
4189
4190 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4191 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4192
Steve Naroffc77a6362008-12-04 16:24:46 +00004193 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4194 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4195 if (BinOp) {
4196 // Because the rewriter doesn't allow us to rewrite rewritten code,
4197 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004198 DisableReplaceStmt = true;
4199 // Save the source range. Even if we disable the replacement, the
4200 // rewritten node will have been inserted into the tree. If the synthesized
4201 // node is at the 'end', the rewriter will fail. Consider this:
4202 // self.errorHandler = handler ? handler :
4203 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4204 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004205 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004206 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004207 //
4208 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4209 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4210 // to see the original expression). Consider this example:
4211 //
4212 // Foo *obj1, *obj2;
4213 //
4214 // obj1.i = [obj2 rrrr];
4215 //
4216 // 'BinOp' for the previous expression looks like:
4217 //
4218 // (BinaryOperator 0x231ccf0 'int' '='
4219 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4220 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4221 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4222 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4223 //
4224 // 'newStmt' represents the rewritten message expression. For example:
4225 //
4226 // (CallExpr 0x231d300 'id':'struct objc_object *'
4227 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4228 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4229 // (CStyleCastExpr 0x231d220 'void *'
4230 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4231 //
4232 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4233 // can be used as the setter argument. ReplaceStmt() will still 'see'
4234 // the original RHS (since we haven't altered BinOp).
4235 //
4236 // This implies the Rewrite* routines can no longer delete the original
4237 // node. As a result, we now leak the original AST nodes.
4238 //
Steve Naroffb619d952008-12-09 12:56:34 +00004239 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004240 } else {
4241 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004242 }
4243 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004244 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4245 return RewriteAtSelector(AtSelector);
4246
4247 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4248 return RewriteObjCStringLiteral(AtString);
4249
4250 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004251#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004252 // Before we rewrite it, put the original message expression in a comment.
4253 SourceLocation startLoc = MessExpr->getLocStart();
4254 SourceLocation endLoc = MessExpr->getLocEnd();
4255
4256 const char *startBuf = SM->getCharacterData(startLoc);
4257 const char *endBuf = SM->getCharacterData(endLoc);
4258
4259 std::string messString;
4260 messString += "// ";
4261 messString.append(startBuf, endBuf-startBuf+1);
4262 messString += "\n";
4263
4264 // FIXME: Missing definition of
4265 // InsertText(clang::SourceLocation, char const*, unsigned int).
4266 // InsertText(startLoc, messString.c_str(), messString.size());
4267 // Tried this, but it didn't work either...
4268 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004269#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004270 return RewriteMessageExpr(MessExpr);
4271 }
4272
4273 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4274 return RewriteObjCTryStmt(StmtTry);
4275
4276 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4277 return RewriteObjCSynchronizedStmt(StmtTry);
4278
4279 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4280 return RewriteObjCThrowStmt(StmtThrow);
4281
4282 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4283 return RewriteObjCProtocolExpr(ProtocolExp);
4284
4285 if (ObjCForCollectionStmt *StmtForCollection =
4286 dyn_cast<ObjCForCollectionStmt>(S))
4287 return RewriteObjCForCollectionStmt(StmtForCollection,
4288 OrigStmtRange.getEnd());
4289 if (BreakStmt *StmtBreakStmt =
4290 dyn_cast<BreakStmt>(S))
4291 return RewriteBreakStmt(StmtBreakStmt);
4292 if (ContinueStmt *StmtContinueStmt =
4293 dyn_cast<ContinueStmt>(S))
4294 return RewriteContinueStmt(StmtContinueStmt);
4295
4296 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4297 // and cast exprs.
4298 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4299 // FIXME: What we're doing here is modifying the type-specifier that
4300 // precedes the first Decl. In the future the DeclGroup should have
4301 // a separate type-specifier that we can rewrite.
4302 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4303
4304 // Blocks rewrite rules.
4305 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4306 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004307 ScopedDecl *SD = *DI;
4308 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004309 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004310 RewriteBlockPointerDecl(ND);
4311 else if (ND->getType()->isFunctionPointerType())
4312 CheckFunctionPointerDecl(ND->getType(), ND);
4313 }
4314 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004315 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004316 RewriteBlockPointerDecl(TD);
4317 else if (TD->getUnderlyingType()->isFunctionPointerType())
4318 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4319 }
4320 }
4321 }
4322
4323 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4324 RewriteObjCQualifiedInterfaceTypes(CE);
4325
4326 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4327 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4328 assert(!Stmts.empty() && "Statement stack is empty");
4329 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4330 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4331 && "Statement stack mismatch");
4332 Stmts.pop_back();
4333 }
4334 // Handle blocks rewriting.
4335 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4336 if (BDRE->isByRef())
4337 RewriteBlockDeclRefExpr(BDRE);
4338 }
4339 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004340 if (CE->getCallee()->getType()->isBlockPointerType()) {
4341 Stmt *BlockCall = SynthesizeBlockCall(CE);
4342 ReplaceStmt(S, BlockCall);
4343 return BlockCall;
4344 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004345 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004346 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004347 RewriteCastExpr(CE);
4348 }
4349#if 0
4350 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4351 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4352 // Get the new text.
4353 std::string SStr;
4354 llvm::raw_string_ostream Buf(SStr);
4355 Replacement->printPretty(Buf);
4356 const std::string &Str = Buf.str();
4357
4358 printf("CAST = %s\n", &Str[0]);
4359 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4360 delete S;
4361 return Replacement;
4362 }
4363#endif
4364 // Return this stmt unmodified.
4365 return S;
4366}
4367
4368/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4369/// main file of the input.
4370void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4371 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004372 if (FD->isOverloadedOperator())
4373 return;
4374
Steve Narofffa15fd92008-10-28 20:29:00 +00004375 // Since function prototypes don't have ParmDecl's, we check the function
4376 // prototype. This enables us to rewrite function declarations and
4377 // definitions using the same code.
4378 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4379
4380 if (Stmt *Body = FD->getBody()) {
4381 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004382 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004383 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004384 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004385 CurrentBody = 0;
4386 if (PropParentMap) {
4387 delete PropParentMap;
4388 PropParentMap = 0;
4389 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004390 // This synthesizes and inserts the block "impl" struct, invoke function,
4391 // and any copy/dispose helper functions.
4392 InsertBlockLiteralsWithinFunction(FD);
4393 CurFunctionDef = 0;
4394 }
4395 return;
4396 }
4397 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4398 if (Stmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004399 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004400 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004401 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004402 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004403 CurrentBody = 0;
4404 if (PropParentMap) {
4405 delete PropParentMap;
4406 PropParentMap = 0;
4407 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004408 InsertBlockLiteralsWithinMethod(MD);
4409 CurMethodDef = 0;
4410 }
4411 }
4412 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4413 ClassImplementation.push_back(CI);
4414 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4415 CategoryImplementation.push_back(CI);
4416 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4417 RewriteForwardClassDecl(CD);
4418 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4419 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004420 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004421 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004422 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004423 CheckFunctionPointerDecl(VD->getType(), VD);
4424 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004425 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004426 RewriteCastExpr(CE);
4427 }
4428 }
4429 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004430 if (VD->getInit()) {
4431 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004432 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004433 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004434 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004435 CurrentBody = 0;
4436 if (PropParentMap) {
4437 delete PropParentMap;
4438 PropParentMap = 0;
4439 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004440 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004441 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004442 GlobalVarDecl = 0;
4443
4444 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004445 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004446 RewriteCastExpr(CE);
4447 }
4448 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004449 return;
4450 }
4451 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004452 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004453 RewriteBlockPointerDecl(TD);
4454 else if (TD->getUnderlyingType()->isFunctionPointerType())
4455 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4456 return;
4457 }
4458 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4459 if (RD->isDefinition()) {
Douglas Gregora4c46df2008-12-11 17:59:21 +00004460 for (RecordDecl::field_iterator i = RD->field_begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004461 e = RD->field_end(); i != e; ++i) {
4462 FieldDecl *FD = *i;
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004463 if (isTopLevelBlockPointerType(FD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004464 RewriteBlockPointerDecl(FD);
4465 }
4466 }
4467 return;
4468 }
4469 // Nothing yet.
4470}
4471
4472void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4473 // Get the top-level buffer that this corresponds to.
4474
4475 // Rewrite tabs if we care.
4476 //RewriteTabs();
4477
4478 if (Diags.hasErrorOccurred())
4479 return;
4480
4481 // Create the output file.
4482
4483 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4484 llvm::raw_ostream *OutFile;
4485 if (OutFileName == "-") {
4486 OutFile = &llvm::outs();
4487 } else if (!OutFileName.empty()) {
4488 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004489 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004490 OwnedStream.reset(OutFile);
4491 } else if (InFileName == "-") {
4492 OutFile = &llvm::outs();
4493 } else {
4494 llvm::sys::Path Path(InFileName);
4495 Path.eraseSuffix();
4496 Path.appendSuffix("cpp");
4497 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004498 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004499 OwnedStream.reset(OutFile);
4500 }
4501
4502 RewriteInclude();
4503
4504 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4505 Preamble.c_str(), Preamble.size(), false);
4506
Steve Naroff0aab7962008-11-14 14:10:01 +00004507 if (ClassImplementation.size() || CategoryImplementation.size())
4508 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004509
4510 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4511 // we are done.
4512 if (const RewriteBuffer *RewriteBuf =
4513 Rewrite.getRewriteBufferFor(MainFileID)) {
4514 //printf("Changed:\n");
4515 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4516 } else {
4517 fprintf(stderr, "No changes\n");
4518 }
Steve Narofface66252008-11-13 20:07:04 +00004519
Steve Naroff0aab7962008-11-14 14:10:01 +00004520 if (ClassImplementation.size() || CategoryImplementation.size()) {
4521 // Rewrite Objective-c meta data*
4522 std::string ResultStr;
4523 SynthesizeMetaDataIntoBuffer(ResultStr);
4524 // Emit metadata.
4525 *OutFile << ResultStr;
4526 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004527 OutFile->flush();
4528}
4529