blob: 907d7bb464f84399a596eb09185aceb39041c765 [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
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000123 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000124 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000125 virtual void Initialize(ASTContext &context);
126
127 virtual void InitializeTU(TranslationUnit &TU) {
128 TU.SetOwnsDecls(false);
129 Initialize(TU.getContext());
130 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000131
Chris Lattner8a12c272007-10-11 18:38:32 +0000132
Chris Lattnerf04da132007-10-24 17:06:59 +0000133 // Top Level Driver code.
134 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000135 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000136 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000137 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000138
139 ~RewriteObjC() {}
140
141 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000142
143 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000144 Stmt *ReplacingStmt = ReplacedNodes[Old];
145
146 if (ReplacingStmt)
147 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000148
Steve Naroff4c3580e2008-12-04 23:50:32 +0000149 // If replacement succeeded or warning disabled return with no warning.
150 if (!Rewrite.ReplaceStmt(Old, New)) {
151 ReplacedNodes[Old] = New;
152 return;
153 }
154 if (SilenceRewriteMacroWarning)
155 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000156 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
157 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000158 }
159
Steve Naroffba92b2e2008-03-27 22:29:16 +0000160 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
161 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000162 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000163 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000164 SilenceRewriteMacroWarning)
165 return;
166
167 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
168 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000169
Chris Lattneraadaf782008-01-31 19:51:04 +0000170 void RemoveText(SourceLocation Loc, unsigned StrLen) {
171 // If removal succeeded or warning disabled return with no warning.
172 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
173 return;
174
175 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
176 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000177
Chris Lattneraadaf782008-01-31 19:51:04 +0000178 void ReplaceText(SourceLocation Start, unsigned OrigLength,
179 const char *NewStr, unsigned NewLength) {
180 // If removal succeeded or warning disabled return with no warning.
181 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
182 SilenceRewriteMacroWarning)
183 return;
184
185 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
186 }
187
Chris Lattnerf04da132007-10-24 17:06:59 +0000188 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000189 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000190 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000191 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000192 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000193 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
194 ObjCImplementationDecl *IMD,
195 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000196 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000197 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
199 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
200 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
201 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
202 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000203 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000204 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000205 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000206 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000207 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000208 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000209 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000210 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000211 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000212
Chris Lattnerf04da132007-10-24 17:06:59 +0000213 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000214 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000215 void CollectPropertySetters(Stmt *S);
216
Steve Naroff8599e7a2008-12-08 16:43:47 +0000217 Stmt *CurrentBody;
218 ParentMap *PropParentMap; // created lazily.
219
Chris Lattnere64b7772007-10-24 16:57:36 +0000220 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000221 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000222 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
223 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt);
Steve Naroffb42f8412007-11-05 14:50:49 +0000224 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000225 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000226 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000227 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000228 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000229 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000230 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
232 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
233 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000234 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
235 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000236 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
237 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000238 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000239 Stmt *RewriteBreakStmt(BreakStmt *S);
240 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000241 void SynthCountByEnumWithState(std::string &buf);
242
Steve Naroff09b266e2007-10-30 23:14:51 +0000243 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000244 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000245 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000246 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000247 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000248 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000249 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000250 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000251 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000252 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000253
Chris Lattnerf04da132007-10-24 17:06:59 +0000254 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000255 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000256 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000257
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000259 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000260
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000261 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
262 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000263 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000264 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000265 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000266 const char *ClassName,
267 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000268
Chris Lattner780f3292008-07-21 21:32:27 +0000269 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
270 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000271 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000272 const char *ClassName,
273 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000274 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000275 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000276 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
277 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000278 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000279 void RewriteImplementations();
280 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000281
282 // Block rewriting.
283 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
284 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
285
286 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
287 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
288
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000289 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000290 void RewriteBlockCall(CallExpr *Exp);
291 void RewriteBlockPointerDecl(NamedDecl *VD);
292 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
293 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
294
295 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
296 const char *funcName, std::string Tag);
297 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
298 const char *funcName, std::string Tag);
299 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
300 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000301 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000302 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
303 const char *FunName);
304
305 void CollectBlockDeclRefInfo(BlockExpr *Exp);
306 void GetBlockCallExprs(Stmt *S);
307 void GetBlockDeclRefExprs(Stmt *S);
308
309 // We avoid calling Type::isBlockPointerType(), since it operates on the
310 // canonical type. We only care if the top-level type is a closure pointer.
311 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
312
313 // FIXME: This predicate seems like it would be useful to add to ASTContext.
314 bool isObjCType(QualType T) {
315 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
316 return false;
317
318 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
319
320 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
321 OCT == Context->getCanonicalType(Context->getObjCClassType()))
322 return true;
323
324 if (const PointerType *PT = OCT->getAsPointerType()) {
325 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
326 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
327 return true;
328 }
329 return false;
330 }
331 bool PointerTypeTakesAnyBlockArguments(QualType QT);
332 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000333 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000334
335 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000336 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000337 };
338}
339
Steve Naroff54055232008-10-27 17:20:55 +0000340void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
341 NamedDecl *D) {
342 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
343 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
344 E = fproto->arg_type_end(); I && (I != E); ++I)
345 if (isBlockPointerType(*I)) {
346 // All the args are checked/rewritten. Don't call twice!
347 RewriteBlockPointerDecl(D);
348 break;
349 }
350 }
351}
352
353void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
354 const PointerType *PT = funcType->getAsPointerType();
355 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
356 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
357}
358
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000359static bool IsHeaderFile(const std::string &Filename) {
360 std::string::size_type DotPos = Filename.rfind('.');
361
362 if (DotPos == std::string::npos) {
363 // no file extension
364 return false;
365 }
366
367 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
368 // C header: .h
369 // C++ header: .hh or .H;
370 return Ext == "h" || Ext == "hh" || Ext == "H";
371}
372
Steve Naroffb29b4272008-04-14 22:03:09 +0000373RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000374 Diagnostic &D, const LangOptions &LOpts)
375 : Diags(D), LangOpts(LOpts) {
376 IsHeader = IsHeaderFile(inFile);
377 InFileName = inFile;
378 OutFileName = outFile;
379 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
380 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000381 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
382 "rewriter doesn't support user-specified control flow semantics for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000383}
384
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000385ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000386 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000387 Diagnostic &Diags,
388 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000389 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000390}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000391
Steve Naroffb29b4272008-04-14 22:03:09 +0000392void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000393 Context = &context;
394 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000395 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000396 MsgSendFunctionDecl = 0;
397 MsgSendSuperFunctionDecl = 0;
398 MsgSendStretFunctionDecl = 0;
399 MsgSendSuperStretFunctionDecl = 0;
400 MsgSendFpretFunctionDecl = 0;
401 GetClassFunctionDecl = 0;
402 GetMetaClassFunctionDecl = 0;
403 SelGetUidFunctionDecl = 0;
404 CFStringFunctionDecl = 0;
405 GetProtocolFunctionDecl = 0;
406 ConstantStringClassReference = 0;
407 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000408 CurMethodDef = 0;
409 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000410 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000411 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000412 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000413 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000414 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000415
416 // Get the ID and start/end of the main file.
417 MainFileID = SM->getMainFileID();
418 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
419 MainFileStart = MainBuf->getBufferStart();
420 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000421
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000422 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000423
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000424 // declaring objc_selector outside the parameter list removes a silly
425 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000426 if (IsHeader)
427 Preamble = "#pragma once\n";
428 Preamble += "struct objc_selector; struct objc_class;\n";
429 Preamble += "#ifndef OBJC_SUPER\n";
430 Preamble += "struct objc_super { struct objc_object *object; ";
431 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000432 if (LangOpts.Microsoft) {
433 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000434 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
435 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000436 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000437 Preamble += "};\n";
438 Preamble += "#define OBJC_SUPER\n";
439 Preamble += "#endif\n";
440 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
441 Preamble += "typedef struct objc_object Protocol;\n";
442 Preamble += "#define _REWRITER_typedef_Protocol\n";
443 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000444 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000445 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
446 else
447 Preamble += "#define __OBJC_RW_EXTERN extern\n";
448 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000449 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000450 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000451 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000452 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000453 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000454 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000455 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000456 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000457 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000458 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000459 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000460 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000461 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000462 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
463 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
464 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
465 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
466 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000467 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000468 // @synchronized hooks.
469 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
470 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000471 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000472 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
473 Preamble += "struct __objcFastEnumerationState {\n\t";
474 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000475 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000476 Preamble += "unsigned long *mutationsPtr;\n\t";
477 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000478 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000479 Preamble += "#define __FASTENUMERATIONSTATE\n";
480 Preamble += "#endif\n";
481 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
482 Preamble += "struct __NSConstantStringImpl {\n";
483 Preamble += " int *isa;\n";
484 Preamble += " int flags;\n";
485 Preamble += " char *str;\n";
486 Preamble += " long length;\n";
487 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000488 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
489 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
490 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000491 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000492 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000493 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
494 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000495 // Blocks preamble.
496 Preamble += "#ifndef BLOCK_IMPL\n";
497 Preamble += "#define BLOCK_IMPL\n";
498 Preamble += "struct __block_impl {\n";
499 Preamble += " void *isa;\n";
500 Preamble += " int Flags;\n";
501 Preamble += " int Size;\n";
502 Preamble += " void *FuncPtr;\n";
503 Preamble += "};\n";
504 Preamble += "enum {\n";
505 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
506 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
507 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000508 Preamble += "// Runtime copy/destroy helper functions\n";
509 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
510 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
511 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
512 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
513 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
514 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
515 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000516 if (LangOpts.Microsoft) {
517 Preamble += "#undef __OBJC_RW_EXTERN\n";
518 Preamble += "#define __attribute__(X)\n";
519 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000520}
521
522
Chris Lattnerf04da132007-10-24 17:06:59 +0000523//===----------------------------------------------------------------------===//
524// Top Level Driver Code
525//===----------------------------------------------------------------------===//
526
Steve Naroffb29b4272008-04-14 22:03:09 +0000527void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000528 // Two cases: either the decl could be in the main file, or it could be in a
529 // #included file. If the former, rewrite it now. If the later, check to see
530 // if we rewrote the #include/#import.
531 SourceLocation Loc = D->getLocation();
532 Loc = SM->getLogicalLoc(Loc);
533
534 // If this is for a builtin, ignore it.
535 if (Loc.isInvalid()) return;
536
Steve Naroffebf2b562007-10-23 23:50:29 +0000537 // Look for built-in declarations that we need to refer during the rewrite.
538 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000539 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000540 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000541 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000542 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000543 ConstantStringClassReference = FVD;
544 return;
545 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000546 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000547 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000548 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000549 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000550 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000551 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000552 } else if (ObjCForwardProtocolDecl *FP =
553 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000554 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000555 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000556 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000557 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000558 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000559}
560
Chris Lattnerf04da132007-10-24 17:06:59 +0000561//===----------------------------------------------------------------------===//
562// Syntactic (non-AST) Rewriting Code
563//===----------------------------------------------------------------------===//
564
Steve Naroffb29b4272008-04-14 22:03:09 +0000565void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000566 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
567 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
568 const char *MainBufStart = MainBuf.first;
569 const char *MainBufEnd = MainBuf.second;
570 size_t ImportLen = strlen("import");
571 size_t IncludeLen = strlen("include");
572
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000573 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000574 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
575 if (*BufPtr == '#') {
576 if (++BufPtr == MainBufEnd)
577 return;
578 while (*BufPtr == ' ' || *BufPtr == '\t')
579 if (++BufPtr == MainBufEnd)
580 return;
581 if (!strncmp(BufPtr, "import", ImportLen)) {
582 // replace import with include
583 SourceLocation ImportLoc =
584 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000585 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000586 BufPtr += ImportLen;
587 }
588 }
589 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000590}
591
Steve Naroffb29b4272008-04-14 22:03:09 +0000592void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000593 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
594 const char *MainBufStart = MainBuf.first;
595 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000596
Chris Lattnerf04da132007-10-24 17:06:59 +0000597 // Loop over the whole file, looking for tabs.
598 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
599 if (*BufPtr != '\t')
600 continue;
601
602 // Okay, we found a tab. This tab will turn into at least one character,
603 // but it depends on which 'virtual column' it is in. Compute that now.
604 unsigned VCol = 0;
605 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
606 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
607 ++VCol;
608
609 // Okay, now that we know the virtual column, we know how many spaces to
610 // insert. We assume 8-character tab-stops.
611 unsigned Spaces = 8-(VCol & 7);
612
613 // Get the location of the tab.
614 SourceLocation TabLoc =
615 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
616
617 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000618 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000619 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000620}
621
Steve Naroffeb0646c2008-12-02 15:48:25 +0000622static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
623 ObjCIvarDecl *OID) {
624 std::string S;
625 S = "((struct ";
626 S += ClassDecl->getIdentifier()->getName();
627 S += "_IMPL *)self)->";
628 S += OID->getNameAsCString();
629 return S;
630}
631
Steve Naroffa0876e82008-12-02 17:36:43 +0000632void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
633 ObjCImplementationDecl *IMD,
634 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000635 SourceLocation startLoc = PID->getLocStart();
636 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000637 const char *startBuf = SM->getCharacterData(startLoc);
638 assert((*startBuf == '@') && "bogus @synthesize location");
639 const char *semiBuf = strchr(startBuf, ';');
640 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
641 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
642
643 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
644 return; // FIXME: is this correct?
645
646 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000647 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000648 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000649 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000650
651 if (!OID)
652 return;
653
654 std::string Getr;
655 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
656 Getr += "{ ";
657 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000658 // FIXME: deal with code generation implications for various property
659 // attributes (copy, retain, nonatomic).
660 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000661 Getr += "return " + getIvarAccessString(ClassDecl, OID);
662 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000663 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000664
665 // Add the rewritten getter to trigger meta data generation. An alternate, and
666 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
667 // with properties explicitly. The following addInstanceMethod() required far
668 // less code change (and actually models what the rewriter is doing).
669 if (IMD)
670 IMD->addInstanceMethod(PD->getGetterMethodDecl());
671 else
672 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000673
674 if (PD->isReadOnly())
675 return;
676
677 // Generate the 'setter' function.
678 std::string Setr;
679 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000680 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000681 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000682 // FIXME: deal with code generation implications for various property
683 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000684 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000685 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
686 Setr += OID->getNameAsCString();
687 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000688 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000689
690 // Add the rewritten setter to trigger meta data generation.
691 if (IMD)
692 IMD->addInstanceMethod(PD->getSetterMethodDecl());
693 else
694 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000695}
Chris Lattner8a12c272007-10-11 18:38:32 +0000696
Steve Naroffb29b4272008-04-14 22:03:09 +0000697void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000698 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000699 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000700
701 // Get the start location and compute the semi location.
702 SourceLocation startLoc = ClassDecl->getLocation();
703 const char *startBuf = SM->getCharacterData(startLoc);
704 const char *semiPtr = strchr(startBuf, ';');
705
706 // Translate to typedef's that forward reference structs with the same name
707 // as the class. As a convenience, we include the original declaration
708 // as a comment.
709 std::string typedefString;
710 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000711 typedefString.append(startBuf, semiPtr-startBuf+1);
712 typedefString += "\n";
713 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000714 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000715 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000716 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000717 typedefString += "\n";
718 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000719 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000720 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000721 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000722 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000723 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000724 }
725
726 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000727 ReplaceText(startLoc, semiPtr-startBuf+1,
728 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000729}
730
Steve Naroffb29b4272008-04-14 22:03:09 +0000731void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000732 SourceLocation LocStart = Method->getLocStart();
733 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000734
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000735 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000736 InsertText(LocStart, "#if 0\n", 6);
737 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000738 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000739 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000740 }
741}
742
Steve Naroffb29b4272008-04-14 22:03:09 +0000743void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000744{
Chris Lattner55d13b42008-03-16 21:23:50 +0000745 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000746 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000747 SourceLocation Loc = Property->getLocation();
748
Chris Lattneraadaf782008-01-31 19:51:04 +0000749 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000750
751 // FIXME: handle properties that are declared across multiple lines.
752 }
753}
754
Steve Naroffb29b4272008-04-14 22:03:09 +0000755void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000756 SourceLocation LocStart = CatDecl->getLocStart();
757
758 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000759 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000760
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000761 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000762 E = CatDecl->instmeth_end(); I != E; ++I)
763 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000764 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000765 E = CatDecl->classmeth_end(); I != E; ++I)
766 RewriteMethodDeclaration(*I);
767
Steve Naroff423cb562007-10-30 13:30:57 +0000768 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000769 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000770}
771
Steve Naroffb29b4272008-04-14 22:03:09 +0000772void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000773 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000774
Steve Naroff752d6ef2007-10-30 16:42:30 +0000775 SourceLocation LocStart = PDecl->getLocStart();
776
777 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000778 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000779
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000780 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000781 E = PDecl->instmeth_end(); I != E; ++I)
782 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000783 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000784 E = PDecl->classmeth_end(); I != E; ++I)
785 RewriteMethodDeclaration(*I);
786
Steve Naroff752d6ef2007-10-30 16:42:30 +0000787 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000788 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000789 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000790
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000791 // Must comment out @optional/@required
792 const char *startBuf = SM->getCharacterData(LocStart);
793 const char *endBuf = SM->getCharacterData(LocEnd);
794 for (const char *p = startBuf; p < endBuf; p++) {
795 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
796 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000797 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000798 ReplaceText(OptionalLoc, strlen("@optional"),
799 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000800
801 }
802 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
803 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000804 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000805 ReplaceText(OptionalLoc, strlen("@required"),
806 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000807
808 }
809 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000810}
811
Steve Naroffb29b4272008-04-14 22:03:09 +0000812void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000813 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000814 if (LocStart.isInvalid())
815 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000816 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000817 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000818}
819
Steve Naroffb29b4272008-04-14 22:03:09 +0000820void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000821 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000822 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000823 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000824 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000825 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000826 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000827 else if (OMD->getResultType()->isFunctionPointerType()) {
828 // needs special handling, since pointer-to-functions have special
829 // syntax (where a decaration models use).
830 QualType retType = OMD->getResultType();
831 if (const PointerType* PT = retType->getAsPointerType()) {
832 QualType PointeeTy = PT->getPointeeType();
833 if ((FPRetType = PointeeTy->getAsFunctionType())) {
834 ResultStr += FPRetType->getResultType().getAsString();
835 ResultStr += "(*";
836 }
837 }
838 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000839 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000840 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000841
842 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000843 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000844
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000845 if (OMD->isInstance())
846 NameStr += "_I_";
847 else
848 NameStr += "_C_";
849
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000850 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000851 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000852
853 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000854 if (ObjCCategoryImplDecl *CID =
855 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000856 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000857 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000858 }
Steve Naroff563b8282008-04-04 22:23:44 +0000859 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000860 {
861 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000862 int len = selString.size();
863 for (int i = 0; i < len; i++)
864 if (selString[i] == ':')
865 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000866 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000867 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000868 // Remember this name for metadata emission
869 MethodInternalNames[OMD] = NameStr;
870 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000871
872 // Rewrite arguments
873 ResultStr += "(";
874
875 // invisible arguments
876 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000877 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000878 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000879 if (!LangOpts.Microsoft) {
880 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
881 ResultStr += "struct ";
882 }
883 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000884 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000885 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000886 }
887 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000888 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000889
890 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000891 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000892 ResultStr += " _cmd";
893
894 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000895 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000896 ParmVarDecl *PDecl = OMD->getParamDecl(i);
897 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000898 if (PDecl->getType()->isObjCQualifiedIdType()) {
899 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000900 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000901 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000902 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000903 if (isBlockPointerType(PDecl->getType())) {
904 // Make sure we convert "t (^)(...)" to "t (*)(...)".
905 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
906 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
907 } else
908 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000909 ResultStr += Name;
910 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000911 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000912 if (OMD->isVariadic())
913 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000914 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000915
Steve Naroff76e429d2008-07-16 14:40:40 +0000916 if (FPRetType) {
917 ResultStr += ")"; // close the precedence "scope" for "*".
918
919 // Now, emit the argument types (if any).
920 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
921 ResultStr += "(";
922 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
923 if (i) ResultStr += ", ";
924 std::string ParamStr = FT->getArgType(i).getAsString();
925 ResultStr += ParamStr;
926 }
927 if (FT->isVariadic()) {
928 if (FT->getNumArgs()) ResultStr += ", ";
929 ResultStr += "...";
930 }
931 ResultStr += ")";
932 } else {
933 ResultStr += "()";
934 }
935 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000936}
Steve Naroffb29b4272008-04-14 22:03:09 +0000937void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000938 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
939 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000940
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000941 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000942 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000943 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000944 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000945
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000946 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000947 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
948 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000949 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000950 ObjCMethodDecl *OMD = *I;
951 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000952 SourceLocation LocStart = OMD->getLocStart();
953 SourceLocation LocEnd = OMD->getBody()->getLocStart();
954
955 const char *startBuf = SM->getCharacterData(LocStart);
956 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000957 ReplaceText(LocStart, endBuf-startBuf,
958 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000959 }
960
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000961 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000962 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
963 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000964 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000965 ObjCMethodDecl *OMD = *I;
966 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000967 SourceLocation LocStart = OMD->getLocStart();
968 SourceLocation LocEnd = OMD->getBody()->getLocStart();
969
970 const char *startBuf = SM->getCharacterData(LocStart);
971 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000972 ReplaceText(LocStart, endBuf-startBuf,
973 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974 }
Steve Naroffd40910b2008-12-01 20:33:01 +0000975 for (ObjCCategoryImplDecl::propimpl_iterator
976 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
977 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +0000978 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +0000979 }
980
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000981 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000982 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000983 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000984 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000985}
986
Steve Naroffb29b4272008-04-14 22:03:09 +0000987void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000988 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000989 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000990 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000991 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000992 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000993 ResultStr += "\n";
994 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000995 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000996 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000997 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000998 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000999 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001000 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001001 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001002 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001003 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001004
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001005 RewriteProperties(ClassDecl->getNumPropertyDecl(),
1006 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001007 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001008 E = ClassDecl->instmeth_end(); I != E; ++I)
1009 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001010 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001011 E = ClassDecl->classmeth_end(); I != E; ++I)
1012 RewriteMethodDeclaration(*I);
1013
Steve Naroff2feac5e2007-10-30 03:43:13 +00001014 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001015 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001016}
1017
Steve Naroffc77a6362008-12-04 16:24:46 +00001018Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt) {
1019 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1020 // This allows us to reuse all the fun and games in SynthMessageExpr().
1021 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1022 ObjCMessageExpr *MsgExpr;
1023 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1024 llvm::SmallVector<Expr *, 1> ExprVec;
1025 ExprVec.push_back(newStmt);
1026
Steve Naroff8599e7a2008-12-08 16:43:47 +00001027 Stmt *Receiver = PropRefExpr->getBase();
1028 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1029 if (PRE && PropGetters[PRE]) {
1030 // This allows us to handle chain/nested property getters.
1031 Receiver = PropGetters[PRE];
1032 }
1033 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001034 PDecl->getSetterName(), PDecl->getType(),
1035 PDecl->getSetterMethodDecl(),
1036 SourceLocation(), SourceLocation(),
1037 &ExprVec[0], 1);
1038 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1039
1040 // Now do the actual rewrite.
1041 ReplaceStmt(BinOp, ReplacingStmt);
1042 delete BinOp;
1043 delete MsgExpr;
1044 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001045}
1046
Steve Naroffc77a6362008-12-04 16:24:46 +00001047Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001048 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1049 // This allows us to reuse all the fun and games in SynthMessageExpr().
1050 ObjCMessageExpr *MsgExpr;
1051 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1052
Steve Naroff8599e7a2008-12-08 16:43:47 +00001053 Stmt *Receiver = PropRefExpr->getBase();
1054
1055 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1056 if (PRE && PropGetters[PRE]) {
1057 // This allows us to handle chain/nested property getters.
1058 Receiver = PropGetters[PRE];
1059 }
1060 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001061 PDecl->getGetterName(), PDecl->getType(),
1062 PDecl->getGetterMethodDecl(),
1063 SourceLocation(), SourceLocation(),
1064 0, 0);
1065
Steve Naroff4c3580e2008-12-04 23:50:32 +00001066 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001067
1068 if (!PropParentMap)
1069 PropParentMap = new ParentMap(CurrentBody);
1070
1071 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1072 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1073 // We stash away the ReplacingStmt since actually doing the
1074 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1075 PropGetters[PropRefExpr] = ReplacingStmt;
1076 delete MsgExpr;
1077 return PropRefExpr; // return the original...
1078 } else {
1079 ReplaceStmt(PropRefExpr, ReplacingStmt);
1080 // delete PropRefExpr; elsewhere...
1081 delete MsgExpr;
1082 return ReplacingStmt;
1083 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001084}
1085
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001086Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1087 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001088 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001089 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001090 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001091 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1092 // lookup which class implements the instance variable.
1093 ObjCInterfaceDecl *clsDeclared = 0;
1094 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1095 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1096
1097 // Synthesize an explicit cast to gain access to the ivar.
1098 std::string RecName = clsDeclared->getIdentifier()->getName();
1099 RecName += "_IMPL";
1100 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001101 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001102 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001103 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1104 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001105 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001106 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001107 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001108 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1109 IV->getBase()->getLocEnd(),
1110 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001111 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001112 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001113 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1114 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001115 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001116 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001117 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001118 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001119
1120 ReplaceStmt(IV->getBase(), PE);
1121 // Cannot delete IV->getBase(), since PE points to it.
1122 // Replace the old base with the cast. This is important when doing
1123 // embedded rewrites. For example, [newInv->_container addObject:0].
1124 IV->setBase(PE);
1125 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001126 }
Steve Naroff84472a82008-04-18 21:55:08 +00001127 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001128 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1129
1130 // Explicit ivar refs need to have a cast inserted.
1131 // FIXME: consider sharing some of this code with the code above.
1132 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001133 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001134 // lookup which class implements the instance variable.
1135 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001136 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001137 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1138
1139 // Synthesize an explicit cast to gain access to the ivar.
1140 std::string RecName = clsDeclared->getIdentifier()->getName();
1141 RecName += "_IMPL";
1142 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001143 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001144 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001145 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1146 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001147 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001148 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001149 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001150 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1151 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001152 ReplaceStmt(IV->getBase(), PE);
1153 // Cannot delete IV->getBase(), since PE points to it.
1154 // Replace the old base with the cast. This is important when doing
1155 // embedded rewrites. For example, [newInv->_container addObject:0].
1156 IV->setBase(PE);
1157 return IV;
1158 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001159 }
Steve Naroff84472a82008-04-18 21:55:08 +00001160 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001161}
1162
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001163/// SynthCountByEnumWithState - To print:
1164/// ((unsigned int (*)
1165/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1166/// (void *)objc_msgSend)((id)l_collection,
1167/// sel_registerName(
1168/// "countByEnumeratingWithState:objects:count:"),
1169/// &enumState,
1170/// (id *)items, (unsigned int)16)
1171///
Steve Naroffb29b4272008-04-14 22:03:09 +00001172void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001173 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1174 "id *, unsigned int))(void *)objc_msgSend)";
1175 buf += "\n\t\t";
1176 buf += "((id)l_collection,\n\t\t";
1177 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1178 buf += "\n\t\t";
1179 buf += "&enumState, "
1180 "(id *)items, (unsigned int)16)";
1181}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001182
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001183/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1184/// statement to exit to its outer synthesized loop.
1185///
Steve Naroffb29b4272008-04-14 22:03:09 +00001186Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001187 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1188 return S;
1189 // replace break with goto __break_label
1190 std::string buf;
1191
1192 SourceLocation startLoc = S->getLocStart();
1193 buf = "goto __break_label_";
1194 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001195 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001196
1197 return 0;
1198}
1199
1200/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1201/// statement to continue with its inner synthesized loop.
1202///
Steve Naroffb29b4272008-04-14 22:03:09 +00001203Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001204 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1205 return S;
1206 // replace continue with goto __continue_label
1207 std::string buf;
1208
1209 SourceLocation startLoc = S->getLocStart();
1210 buf = "goto __continue_label_";
1211 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001212 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001213
1214 return 0;
1215}
1216
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001217/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001218/// It rewrites:
1219/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001220
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001221/// Into:
1222/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001223/// type elem;
1224/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001225/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001226/// id l_collection = (id)collection;
1227/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1228/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001229/// if (limit) {
1230/// unsigned long startMutations = *enumState.mutationsPtr;
1231/// do {
1232/// unsigned long counter = 0;
1233/// do {
1234/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001235/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001236/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001237/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001238/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001239/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001240/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1241/// objects:items count:16]);
1242/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001243/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001244/// }
1245/// else
1246/// elem = nil;
1247/// }
1248///
Steve Naroffb29b4272008-04-14 22:03:09 +00001249Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001250 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001251 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1252 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1253 "ObjCForCollectionStmt Statement stack mismatch");
1254 assert(!ObjCBcLabelNo.empty() &&
1255 "ObjCForCollectionStmt - Label No stack empty");
1256
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001257 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001258 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001259 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001260 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001261 std::string buf;
1262 buf = "\n{\n\t";
1263 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1264 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001265 ScopedDecl* D = DS->getSolitaryDecl();
1266 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001267 elementTypeAsString = ElementType.getAsString();
1268 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001269 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001270 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001271 buf += elementName;
1272 buf += ";\n\t";
1273 }
Chris Lattner06767512008-04-08 05:52:18 +00001274 else {
1275 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001276 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001277 elementTypeAsString
1278 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001279 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001280
1281 // struct __objcFastEnumerationState enumState = { 0 };
1282 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1283 // id items[16];
1284 buf += "id items[16];\n\t";
1285 // id l_collection = (id)
1286 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001287 // Find start location of 'collection' the hard way!
1288 const char *startCollectionBuf = startBuf;
1289 startCollectionBuf += 3; // skip 'for'
1290 startCollectionBuf = strchr(startCollectionBuf, '(');
1291 startCollectionBuf++; // skip '('
1292 // find 'in' and skip it.
1293 while (*startCollectionBuf != ' ' ||
1294 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1295 (*(startCollectionBuf+3) != ' ' &&
1296 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1297 startCollectionBuf++;
1298 startCollectionBuf += 3;
1299
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001300 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001301 ReplaceText(startLoc, startCollectionBuf - startBuf,
1302 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001303 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001304 SourceLocation rightParenLoc = S->getRParenLoc();
1305 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1306 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001307 buf = ";\n\t";
1308
1309 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1310 // objects:items count:16];
1311 // which is synthesized into:
1312 // unsigned int limit =
1313 // ((unsigned int (*)
1314 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1315 // (void *)objc_msgSend)((id)l_collection,
1316 // sel_registerName(
1317 // "countByEnumeratingWithState:objects:count:"),
1318 // (struct __objcFastEnumerationState *)&state,
1319 // (id *)items, (unsigned int)16);
1320 buf += "unsigned long limit =\n\t\t";
1321 SynthCountByEnumWithState(buf);
1322 buf += ";\n\t";
1323 /// if (limit) {
1324 /// unsigned long startMutations = *enumState.mutationsPtr;
1325 /// do {
1326 /// unsigned long counter = 0;
1327 /// do {
1328 /// if (startMutations != *enumState.mutationsPtr)
1329 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001330 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001331 buf += "if (limit) {\n\t";
1332 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1333 buf += "do {\n\t\t";
1334 buf += "unsigned long counter = 0;\n\t\t";
1335 buf += "do {\n\t\t\t";
1336 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1337 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1338 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001339 buf += " = (";
1340 buf += elementTypeAsString;
1341 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001342 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001343 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001344
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001345 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001346 /// } while (counter < limit);
1347 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1348 /// objects:items count:16]);
1349 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001350 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001351 /// }
1352 /// else
1353 /// elem = nil;
1354 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001355 ///
1356 buf = ";\n\t";
1357 buf += "__continue_label_";
1358 buf += utostr(ObjCBcLabelNo.back());
1359 buf += ": ;";
1360 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001361 buf += "} while (counter < limit);\n\t";
1362 buf += "} while (limit = ";
1363 SynthCountByEnumWithState(buf);
1364 buf += ");\n\t";
1365 buf += elementName;
1366 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001367 buf += "__break_label_";
1368 buf += utostr(ObjCBcLabelNo.back());
1369 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001370 buf += "}\n\t";
1371 buf += "else\n\t\t";
1372 buf += elementName;
1373 buf += " = nil;\n";
1374 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001375
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001376 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001377 if (isa<CompoundStmt>(S->getBody())) {
1378 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1379 InsertText(endBodyLoc, buf.c_str(), buf.size());
1380 } else {
1381 /* Need to treat single statements specially. For example:
1382 *
1383 * for (A *a in b) if (stuff()) break;
1384 * for (A *a in b) xxxyy;
1385 *
1386 * The following code simply scans ahead to the semi to find the actual end.
1387 */
1388 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1389 const char *semiBuf = strchr(stmtBuf, ';');
1390 assert(semiBuf && "Can't find ';'");
1391 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1392 InsertText(endBodyLoc, buf.c_str(), buf.size());
1393 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001394 Stmts.pop_back();
1395 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001396 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001397}
1398
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001399/// RewriteObjCSynchronizedStmt -
1400/// This routine rewrites @synchronized(expr) stmt;
1401/// into:
1402/// objc_sync_enter(expr);
1403/// @try stmt @finally { objc_sync_exit(expr); }
1404///
Steve Naroffb29b4272008-04-14 22:03:09 +00001405Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001406 // Get the start location and compute the semi location.
1407 SourceLocation startLoc = S->getLocStart();
1408 const char *startBuf = SM->getCharacterData(startLoc);
1409
1410 assert((*startBuf == '@') && "bogus @synchronized location");
1411
1412 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001413 buf = "objc_sync_enter((id)";
1414 const char *lparenBuf = startBuf;
1415 while (*lparenBuf != '(') lparenBuf++;
1416 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001417 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1418 // the sync expression is typically a message expression that's already
1419 // been rewritten! (which implies the SourceLocation's are invalid).
1420 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001421 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001422 while (*endBuf != ')') endBuf--;
1423 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001424 buf = ");\n";
1425 // declare a new scope with two variables, _stack and _rethrow.
1426 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1427 buf += "int buf[18/*32-bit i386*/];\n";
1428 buf += "char *pointers[4];} _stack;\n";
1429 buf += "id volatile _rethrow = 0;\n";
1430 buf += "objc_exception_try_enter(&_stack);\n";
1431 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001432 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001433 startLoc = S->getSynchBody()->getLocEnd();
1434 startBuf = SM->getCharacterData(startLoc);
1435
Steve Naroffc7089f12008-08-19 13:04:19 +00001436 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001437 SourceLocation lastCurlyLoc = startLoc;
1438 buf = "}\nelse {\n";
1439 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1440 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001441 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001442 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001443 S->getSynchExpr(),
1444 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001445 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001446 std::string syncExprBufS;
1447 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001448 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001449 buf += syncExprBuf.str();
1450 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001451 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1452 buf += "}\n";
1453 buf += "}";
1454
Chris Lattneraadaf782008-01-31 19:51:04 +00001455 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001456 return 0;
1457}
1458
Steve Naroff8c565152008-12-05 17:03:39 +00001459void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1460 // Perform a bottom up traversal of all children.
1461 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1462 CI != E; ++CI)
1463 if (*CI)
1464 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1465
1466 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1467 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1468 Diags.Report(Context->getFullLoc(S->getLocStart()),
1469 TryFinallyContainsReturnDiag);
1470 }
1471 return;
1472}
1473
Steve Naroffb29b4272008-04-14 22:03:09 +00001474Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001475 // Get the start location and compute the semi location.
1476 SourceLocation startLoc = S->getLocStart();
1477 const char *startBuf = SM->getCharacterData(startLoc);
1478
1479 assert((*startBuf == '@') && "bogus @try location");
1480
1481 std::string buf;
1482 // declare a new scope with two variables, _stack and _rethrow.
1483 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1484 buf += "int buf[18/*32-bit i386*/];\n";
1485 buf += "char *pointers[4];} _stack;\n";
1486 buf += "id volatile _rethrow = 0;\n";
1487 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001488 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001489
Chris Lattneraadaf782008-01-31 19:51:04 +00001490 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001491
1492 startLoc = S->getTryBody()->getLocEnd();
1493 startBuf = SM->getCharacterData(startLoc);
1494
1495 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001496
Steve Naroff75730982007-11-07 04:08:17 +00001497 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001498 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1499 if (catchList) {
1500 startLoc = startLoc.getFileLocWithOffset(1);
1501 buf = " /* @catch begin */ else {\n";
1502 buf += " id _caught = objc_exception_extract(&_stack);\n";
1503 buf += " objc_exception_try_enter (&_stack);\n";
1504 buf += " if (_setjmp(_stack.buf))\n";
1505 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1506 buf += " else { /* @catch continue */";
1507
1508 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001509 } else { /* no catch list */
1510 buf = "}\nelse {\n";
1511 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1512 buf += "}";
1513 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001514 }
Steve Naroff75730982007-11-07 04:08:17 +00001515 bool sawIdTypedCatch = false;
1516 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001517 while (catchList) {
1518 Stmt *catchStmt = catchList->getCatchParamStmt();
1519
1520 if (catchList == S->getCatchStmts())
1521 buf = "if ("; // we are generating code for the first catch clause
1522 else
1523 buf = "else if (";
1524 startLoc = catchList->getLocStart();
1525 startBuf = SM->getCharacterData(startLoc);
1526
1527 assert((*startBuf == '@') && "bogus @catch location");
1528
1529 const char *lParenLoc = strchr(startBuf, '(');
1530
Steve Naroffbe4b3332008-02-01 22:08:12 +00001531 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001532 // Now rewrite the body...
1533 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001534 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1535 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001536 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1537 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001538 assert((*bodyBuf == '{') && "bogus @catch body location");
1539
1540 buf += "1) { id _tmp = _caught;";
1541 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1542 buf.c_str(), buf.size());
1543 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001544 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001545 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001546 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001547 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001548 sawIdTypedCatch = true;
1549 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001550 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001551
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001552 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001553 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001554 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001555 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001556 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001557 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001558 }
1559 }
1560 // Now rewrite the body...
1561 lastCatchBody = catchList->getCatchBody();
1562 SourceLocation rParenLoc = catchList->getRParenLoc();
1563 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1564 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1565 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1566 assert((*rParenBuf == ')') && "bogus @catch paren location");
1567 assert((*bodyBuf == '{') && "bogus @catch body location");
1568
1569 buf = " = _caught;";
1570 // Here we replace ") {" with "= _caught;" (which initializes and
1571 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001572 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001573 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001574 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001575 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001576 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001577 catchList = catchList->getNextCatchStmt();
1578 }
1579 // Complete the catch list...
1580 if (lastCatchBody) {
1581 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001582 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1583 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001584
Steve Naroff378f47a2008-09-11 15:29:03 +00001585 // Insert the last (implicit) else clause *before* the right curly brace.
1586 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1587 buf = "} /* last catch end */\n";
1588 buf += "else {\n";
1589 buf += " _rethrow = _caught;\n";
1590 buf += " objc_exception_try_exit(&_stack);\n";
1591 buf += "} } /* @catch end */\n";
1592 if (!S->getFinallyStmt())
1593 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001594 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001595
1596 // Set lastCurlyLoc
1597 lastCurlyLoc = lastCatchBody->getLocEnd();
1598 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001599 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001600 startLoc = finalStmt->getLocStart();
1601 startBuf = SM->getCharacterData(startLoc);
1602 assert((*startBuf == '@') && "bogus @finally start");
1603
1604 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001605 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001606
1607 Stmt *body = finalStmt->getFinallyBody();
1608 SourceLocation startLoc = body->getLocStart();
1609 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001610 assert(*SM->getCharacterData(startLoc) == '{' &&
1611 "bogus @finally body location");
1612 assert(*SM->getCharacterData(endLoc) == '}' &&
1613 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001614
1615 startLoc = startLoc.getFileLocWithOffset(1);
1616 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001617 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001618 endLoc = endLoc.getFileLocWithOffset(-1);
1619 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001620 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001621
1622 // Set lastCurlyLoc
1623 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001624
1625 // Now check for any return/continue/go statements within the @try.
1626 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001627 } else { /* no finally clause - make sure we synthesize an implicit one */
1628 buf = "{ /* implicit finally clause */\n";
1629 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1630 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1631 buf += "}";
1632 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001633 }
1634 // Now emit the final closing curly brace...
1635 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1636 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001637 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001638 return 0;
1639}
1640
Steve Naroffb29b4272008-04-14 22:03:09 +00001641Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001642 return 0;
1643}
1644
Steve Naroffb29b4272008-04-14 22:03:09 +00001645Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001646 return 0;
1647}
1648
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001649// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001650// the throw expression is typically a message expression that's already
1651// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001652Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001653 // Get the start location and compute the semi location.
1654 SourceLocation startLoc = S->getLocStart();
1655 const char *startBuf = SM->getCharacterData(startLoc);
1656
1657 assert((*startBuf == '@') && "bogus @throw location");
1658
1659 std::string buf;
1660 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001661 if (S->getThrowExpr())
1662 buf = "objc_exception_throw(";
1663 else // add an implicit argument
1664 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001665
1666 // handle "@ throw" correctly.
1667 const char *wBuf = strchr(startBuf, 'w');
1668 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1669 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1670
Steve Naroff2bd03922007-11-07 15:32:26 +00001671 const char *semiBuf = strchr(startBuf, ';');
1672 assert((*semiBuf == ';') && "@throw: can't find ';'");
1673 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1674 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001675 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001676 return 0;
1677}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001678
Steve Naroffb29b4272008-04-14 22:03:09 +00001679Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001680 // Create a new string expression.
1681 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001682 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001683 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001684 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1685 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001686 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001687 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001688
Chris Lattner07506182007-11-30 22:53:43 +00001689 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001690 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001691 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001692}
1693
Steve Naroffb29b4272008-04-14 22:03:09 +00001694Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001695 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1696 // Create a call to sel_registerName("selName").
1697 llvm::SmallVector<Expr*, 8> SelExprs;
1698 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001699 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1700 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001701 false, argType, SourceLocation(),
1702 SourceLocation()));
1703 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1704 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001705 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001706 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001707 return SelExp;
1708}
1709
Steve Naroffb29b4272008-04-14 22:03:09 +00001710CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001711 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001712 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001713 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001714
1715 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001716 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001717
1718 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001719 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001720 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1721 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001722
1723 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001724
Steve Naroff934f2762007-10-24 22:48:43 +00001725 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1726}
1727
Steve Naroffd5255f52007-11-01 13:24:47 +00001728static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1729 const char *&startRef, const char *&endRef) {
1730 while (startBuf < endBuf) {
1731 if (*startBuf == '<')
1732 startRef = startBuf; // mark the start.
1733 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001734 if (startRef && *startRef == '<') {
1735 endRef = startBuf; // mark the end.
1736 return true;
1737 }
1738 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001739 }
1740 startBuf++;
1741 }
1742 return false;
1743}
1744
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001745static void scanToNextArgument(const char *&argRef) {
1746 int angle = 0;
1747 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1748 if (*argRef == '<')
1749 angle++;
1750 else if (*argRef == '>')
1751 angle--;
1752 argRef++;
1753 }
1754 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1755}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001756
Steve Naroffb29b4272008-04-14 22:03:09 +00001757bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001758
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001759 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001760 return true;
1761
Steve Naroffd5255f52007-11-01 13:24:47 +00001762 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001763 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001764 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001765 return true; // we have "Class <Protocol> *".
1766 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001767 return false;
1768}
1769
Steve Naroff4f95b752008-07-29 18:15:38 +00001770void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1771 QualType Type = E->getType();
1772 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001773 SourceLocation Loc, EndLoc;
1774
1775 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1776 Loc = ECE->getLParenLoc();
1777 EndLoc = ECE->getRParenLoc();
1778 } else {
1779 Loc = E->getLocStart();
1780 EndLoc = E->getLocEnd();
1781 }
1782 // This will defend against trying to rewrite synthesized expressions.
1783 if (Loc.isInvalid() || EndLoc.isInvalid())
1784 return;
1785
Steve Naroff4f95b752008-07-29 18:15:38 +00001786 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001787 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001788 const char *startRef = 0, *endRef = 0;
1789 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1790 // Get the locations of the startRef, endRef.
1791 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1792 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1793 // Comment out the protocol references.
1794 InsertText(LessLoc, "/*", 2);
1795 InsertText(GreaterLoc, "*/", 2);
1796 }
1797 }
1798}
1799
Steve Naroffb29b4272008-04-14 22:03:09 +00001800void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001801 SourceLocation Loc;
1802 QualType Type;
1803 const FunctionTypeProto *proto = 0;
1804 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1805 Loc = VD->getLocation();
1806 Type = VD->getType();
1807 }
1808 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1809 Loc = FD->getLocation();
1810 // Check for ObjC 'id' and class types that have been adorned with protocol
1811 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1812 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1813 assert(funcType && "missing function type");
1814 proto = dyn_cast<FunctionTypeProto>(funcType);
1815 if (!proto)
1816 return;
1817 Type = proto->getResultType();
1818 }
1819 else
1820 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001821
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001822 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001823 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001824
1825 const char *endBuf = SM->getCharacterData(Loc);
1826 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001827 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001828 startBuf--; // scan backward (from the decl location) for return type.
1829 const char *startRef = 0, *endRef = 0;
1830 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1831 // Get the locations of the startRef, endRef.
1832 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1833 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1834 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001835 InsertText(LessLoc, "/*", 2);
1836 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001837 }
1838 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001839 if (!proto)
1840 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001841 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001842 const char *startBuf = SM->getCharacterData(Loc);
1843 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001844 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1845 if (needToScanForQualifiers(proto->getArgType(i))) {
1846 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001847
Steve Naroffd5255f52007-11-01 13:24:47 +00001848 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001849 // scan forward (from the decl location) for argument types.
1850 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001851 const char *startRef = 0, *endRef = 0;
1852 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1853 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001854 SourceLocation LessLoc =
1855 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1856 SourceLocation GreaterLoc =
1857 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001858 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001859 InsertText(LessLoc, "/*", 2);
1860 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001861 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001862 startBuf = ++endBuf;
1863 }
1864 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001865 // If the function name is derived from a macro expansion, then the
1866 // argument buffer will not follow the name. Need to speak with Chris.
1867 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001868 startBuf++; // scan forward (from the decl location) for argument types.
1869 startBuf++;
1870 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001871 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001872}
1873
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001874// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001875void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001876 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1877 llvm::SmallVector<QualType, 16> ArgTys;
1878 ArgTys.push_back(Context->getPointerType(
1879 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001880 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001881 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001882 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001883 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001884 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001885 SelGetUidIdent, getFuncType,
1886 FunctionDecl::Extern, false, 0);
1887}
1888
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001889// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001890void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001891 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1892 llvm::SmallVector<QualType, 16> ArgTys;
1893 ArgTys.push_back(Context->getPointerType(
1894 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001895 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001896 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001897 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001898 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001899 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001900 SelGetProtoIdent, getFuncType,
1901 FunctionDecl::Extern, false, 0);
1902}
1903
Steve Naroffb29b4272008-04-14 22:03:09 +00001904void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001905 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001906 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001907 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001908 return;
1909 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001910 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001911}
1912
Steve Naroffc0a123c2008-03-11 17:37:02 +00001913// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001914void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001915 if (SuperContructorFunctionDecl)
1916 return;
1917 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1918 llvm::SmallVector<QualType, 16> ArgTys;
1919 QualType argT = Context->getObjCIdType();
1920 assert(!argT.isNull() && "Can't find 'id' type");
1921 ArgTys.push_back(argT);
1922 ArgTys.push_back(argT);
1923 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1924 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001925 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001926 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001927 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001928 msgSendIdent, msgSendType,
1929 FunctionDecl::Extern, false, 0);
1930}
1931
Steve Naroff09b266e2007-10-30 23:14:51 +00001932// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001933void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001934 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1935 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001936 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001937 assert(!argT.isNull() && "Can't find 'id' type");
1938 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001939 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001940 assert(!argT.isNull() && "Can't find 'SEL' type");
1941 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001942 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001943 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001944 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001945 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001946 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001947 msgSendIdent, msgSendType,
1948 FunctionDecl::Extern, false, 0);
1949}
1950
Steve Naroff874e2322007-11-15 10:28:18 +00001951// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001952void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001953 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1954 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001955 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001956 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001957 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001958 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1959 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1960 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001961 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001962 assert(!argT.isNull() && "Can't find 'SEL' type");
1963 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001964 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001965 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001966 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001967 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001968 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001969 msgSendIdent, msgSendType,
1970 FunctionDecl::Extern, false, 0);
1971}
1972
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001973// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001974void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001975 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1976 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001977 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001978 assert(!argT.isNull() && "Can't find 'id' type");
1979 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001980 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001981 assert(!argT.isNull() && "Can't find 'SEL' type");
1982 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001983 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001984 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001985 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001986 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001987 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001988 msgSendIdent, msgSendType,
1989 FunctionDecl::Extern, false, 0);
1990}
1991
1992// SynthMsgSendSuperStretFunctionDecl -
1993// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001994void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001995 IdentifierInfo *msgSendIdent =
1996 &Context->Idents.get("objc_msgSendSuper_stret");
1997 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001998 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001999 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002000 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002001 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2002 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2003 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002004 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002005 assert(!argT.isNull() && "Can't find 'SEL' type");
2006 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002007 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002008 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002009 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002010 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002011 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002012 msgSendIdent, msgSendType,
2013 FunctionDecl::Extern, false, 0);
2014}
2015
Steve Naroff1284db82008-05-08 22:02:18 +00002016// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002017void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002018 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2019 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002020 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002021 assert(!argT.isNull() && "Can't find 'id' type");
2022 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002023 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002024 assert(!argT.isNull() && "Can't find 'SEL' type");
2025 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002026 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002027 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002028 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002029 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002030 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002031 msgSendIdent, msgSendType,
2032 FunctionDecl::Extern, false, 0);
2033}
2034
Steve Naroff09b266e2007-10-30 23:14:51 +00002035// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002036void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002037 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2038 llvm::SmallVector<QualType, 16> ArgTys;
2039 ArgTys.push_back(Context->getPointerType(
2040 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002041 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002042 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002043 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002044 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002045 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002046 getClassIdent, getClassType,
2047 FunctionDecl::Extern, false, 0);
2048}
2049
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002050// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002051void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002052 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2053 llvm::SmallVector<QualType, 16> ArgTys;
2054 ArgTys.push_back(Context->getPointerType(
2055 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002056 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002057 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002058 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002059 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002060 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002061 getClassIdent, getClassType,
2062 FunctionDecl::Extern, false, 0);
2063}
2064
Steve Naroffb29b4272008-04-14 22:03:09 +00002065Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002066 QualType strType = getConstantStringStructType();
2067
2068 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002069
2070 std::string tmpName = InFileName;
2071 unsigned i;
2072 for (i=0; i < tmpName.length(); i++) {
2073 char c = tmpName.at(i);
2074 // replace any non alphanumeric characters with '_'.
2075 if (!isalpha(c) && (c < '0' || c > '9'))
2076 tmpName[i] = '_';
2077 }
2078 S += tmpName;
2079 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002080 S += utostr(NumObjCStringLiterals++);
2081
Steve Naroffba92b2e2008-03-27 22:29:16 +00002082 Preamble += "static __NSConstantStringImpl " + S;
2083 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2084 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002085 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002086 std::string prettyBufS;
2087 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002088 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002089 Preamble += prettyBuf.str();
2090 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002091 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002092 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002093
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002094 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002095 &Context->Idents.get(S.c_str()), strType,
2096 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002097 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2098 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2099 Context->getPointerType(DRE->getType()),
2100 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002101 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002102 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002103 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002104 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002105 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002106 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002107}
2108
Steve Naroffb29b4272008-04-14 22:03:09 +00002109ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002110 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002111 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002112
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002113 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2114 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002115 assert(PT);
2116 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2117 return IT->getDecl();
2118 }
2119 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002120}
2121
2122// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002123QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002124 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002125 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002126 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002127 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002128 QualType FieldTypes[2];
2129
2130 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002131 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002132 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002133 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002134 // Create fields
2135 FieldDecl *FieldDecls[2];
2136
2137 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002138 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002139 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002140
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002141 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002142 }
2143 return Context->getTagDeclType(SuperStructDecl);
2144}
2145
Steve Naroffb29b4272008-04-14 22:03:09 +00002146QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002147 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002148 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002149 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002150 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002151 QualType FieldTypes[4];
2152
2153 // struct objc_object *receiver;
2154 FieldTypes[0] = Context->getObjCIdType();
2155 // int flags;
2156 FieldTypes[1] = Context->IntTy;
2157 // char *str;
2158 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2159 // long length;
2160 FieldTypes[3] = Context->LongTy;
2161 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002162 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002163
2164 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002165 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002166 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002167
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002168 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002169 }
2170 return Context->getTagDeclType(ConstantStringDecl);
2171}
2172
Steve Naroffb29b4272008-04-14 22:03:09 +00002173Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002174 if (!SelGetUidFunctionDecl)
2175 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002176 if (!MsgSendFunctionDecl)
2177 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002178 if (!MsgSendSuperFunctionDecl)
2179 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002180 if (!MsgSendStretFunctionDecl)
2181 SynthMsgSendStretFunctionDecl();
2182 if (!MsgSendSuperStretFunctionDecl)
2183 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002184 if (!MsgSendFpretFunctionDecl)
2185 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002186 if (!GetClassFunctionDecl)
2187 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002188 if (!GetMetaClassFunctionDecl)
2189 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002190
Steve Naroff874e2322007-11-15 10:28:18 +00002191 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002192 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2193 // May need to use objc_msgSend_stret() as well.
2194 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002195 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002196 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002197 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002198 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002199 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002200 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002201 }
Steve Naroff874e2322007-11-15 10:28:18 +00002202
Steve Naroff934f2762007-10-24 22:48:43 +00002203 // Synthesize a call to objc_msgSend().
2204 llvm::SmallVector<Expr*, 8> MsgExprs;
2205 IdentifierInfo *clsName = Exp->getClassName();
2206
2207 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2208 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002209 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2210 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002211 if (!strcmp(clsName->getName(), "super")) {
2212 MsgSendFlavor = MsgSendSuperFunctionDecl;
2213 if (MsgSendStretFlavor)
2214 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2215 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2216
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002217 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002218 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002219
2220 llvm::SmallVector<Expr*, 4> InitExprs;
2221
2222 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002223 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002224 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002225 Context->getObjCIdType(),
2226 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002227 llvm::SmallVector<Expr*, 8> ClsExprs;
2228 QualType argType = Context->getPointerType(Context->CharTy);
2229 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2230 SuperDecl->getIdentifier()->getLength(),
2231 false, argType, SourceLocation(),
2232 SourceLocation()));
2233 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2234 &ClsExprs[0],
2235 ClsExprs.size());
2236 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002237 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002238 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002239 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002240 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002241 // struct objc_super
2242 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002243 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002244
Steve Naroff23f41272008-03-11 18:14:26 +00002245 if (LangOpts.Microsoft) {
2246 SynthSuperContructorFunctionDecl();
2247 // Simulate a contructor call...
2248 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2249 superType, SourceLocation());
2250 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2251 superType, SourceLocation());
2252 } else {
2253 // (struct objc_super) { <exprs from above> }
2254 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2255 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002256 SourceLocation(), false);
2257 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2258 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002259 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002260 // struct objc_super *
2261 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2262 Context->getPointerType(SuperRep->getType()),
2263 SourceLocation());
2264 MsgExprs.push_back(Unop);
2265 } else {
2266 llvm::SmallVector<Expr*, 8> ClsExprs;
2267 QualType argType = Context->getPointerType(Context->CharTy);
2268 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2269 clsName->getLength(),
2270 false, argType, SourceLocation(),
2271 SourceLocation()));
2272 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2273 &ClsExprs[0],
2274 ClsExprs.size());
2275 MsgExprs.push_back(Cls);
2276 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002277 } else { // instance message.
2278 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002279
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002280 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002281 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002282 if (MsgSendStretFlavor)
2283 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002284 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2285
2286 llvm::SmallVector<Expr*, 4> InitExprs;
2287
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002288 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002289 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002290 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002291 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002292 SourceLocation()),
2293 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002294 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002295
2296 llvm::SmallVector<Expr*, 8> ClsExprs;
2297 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002298 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2299 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002300 false, argType, SourceLocation(),
2301 SourceLocation()));
2302 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002303 &ClsExprs[0],
2304 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002305 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002306 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002307 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002308 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002309 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002310 // struct objc_super
2311 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002312 Expr *SuperRep;
2313
2314 if (LangOpts.Microsoft) {
2315 SynthSuperContructorFunctionDecl();
2316 // Simulate a contructor call...
2317 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2318 superType, SourceLocation());
2319 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2320 superType, SourceLocation());
2321 } else {
2322 // (struct objc_super) { <exprs from above> }
2323 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2324 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002325 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002326 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2327 }
Steve Naroff874e2322007-11-15 10:28:18 +00002328 // struct objc_super *
2329 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2330 Context->getPointerType(SuperRep->getType()),
2331 SourceLocation());
2332 MsgExprs.push_back(Unop);
2333 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002334 // Remove all type-casts because it may contain objc-style types; e.g.
2335 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002336 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002337 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002338 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002339 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002340 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002341 MsgExprs.push_back(recExpr);
2342 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002343 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002344 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002345 llvm::SmallVector<Expr*, 8> SelExprs;
2346 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002347 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2348 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002349 false, argType, SourceLocation(),
2350 SourceLocation()));
2351 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2352 &SelExprs[0], SelExprs.size());
2353 MsgExprs.push_back(SelExp);
2354
2355 // Now push any user supplied arguments.
2356 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002357 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002358 // Make all implicit casts explicit...ICE comes in handy:-)
2359 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2360 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002361 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002362 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002363 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002364 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002365 }
2366 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002367 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002368 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002369 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002370 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002371 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002372 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002373 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002374 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002375 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002376 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002377 // We've transferred the ownership to MsgExprs. Null out the argument in
2378 // the original expression, since we will delete it below.
2379 Exp->setArg(i, 0);
2380 }
Steve Naroffab972d32007-11-04 22:37:50 +00002381 // Generate the funky cast.
2382 CastExpr *cast;
2383 llvm::SmallVector<QualType, 8> ArgTypes;
2384 QualType returnType;
2385
2386 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002387 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2388 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2389 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002390 ArgTypes.push_back(Context->getObjCIdType());
2391 ArgTypes.push_back(Context->getObjCSelType());
2392 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002393 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002394 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002395 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2396 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002397 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002398 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2399 if (isBlockPointerType(t)) {
2400 const BlockPointerType *BPT = t->getAsBlockPointerType();
2401 t = Context->getPointerType(BPT->getPointeeType());
2402 }
Steve Naroff352336b2007-11-05 14:36:37 +00002403 ArgTypes.push_back(t);
2404 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002405 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2406 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002407 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002408 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002409 }
2410 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002411 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002412
2413 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002414 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2415 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002416
2417 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2418 // If we don't do this cast, we get the following bizarre warning/note:
2419 // xx.m:13: warning: function called through a non-compatible type
2420 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002421 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002422 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002423 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002424
Steve Naroffab972d32007-11-04 22:37:50 +00002425 // Now do the "normal" pointer to function cast.
2426 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002427 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002428 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002429 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002430 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002431 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002432
2433 // Don't forget the parens to enforce the proper binding.
2434 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2435
2436 const FunctionType *FT = msgSendType->getAsFunctionType();
2437 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2438 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002439 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002440 if (MsgSendStretFlavor) {
2441 // We have the method which returns a struct/union. Must also generate
2442 // call to objc_msgSend_stret and hang both varieties on a conditional
2443 // expression which dictate which one to envoke depending on size of
2444 // method's return type.
2445
2446 // Create a reference to the objc_msgSend_stret() declaration.
2447 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2448 SourceLocation());
2449 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002450 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002451 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002452 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002453 // Now do the "normal" pointer to function cast.
2454 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002455 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002456 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002457 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002458 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002459
2460 // Don't forget the parens to enforce the proper binding.
2461 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2462
2463 FT = msgSendType->getAsFunctionType();
2464 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2465 FT->getResultType(), SourceLocation());
2466
2467 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002468 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2469 returnType.getAsOpaquePtr(),
2470 Context->getSizeType(),
2471 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002472 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2473 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2474 // For X86 it is more complicated and some kind of target specific routine
2475 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002476 unsigned IntSize =
2477 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002478 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2479 Context->IntTy,
2480 SourceLocation());
2481 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2482 BinaryOperator::LE,
2483 Context->IntTy,
2484 SourceLocation());
2485 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2486 ConditionalOperator *CondExpr =
2487 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002488 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002489 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002490 return ReplacingStmt;
2491}
2492
Steve Naroffb29b4272008-04-14 22:03:09 +00002493Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002494 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002495
Steve Naroffc77a6362008-12-04 16:24:46 +00002496 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002497 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002498 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002499
Steve Naroff4c3580e2008-12-04 23:50:32 +00002500 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002501 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002502}
2503
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002504/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2505/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002506Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002507 if (!GetProtocolFunctionDecl)
2508 SynthGetProtocolFunctionDecl();
2509 // Create a call to objc_getProtocol("ProtocolName").
2510 llvm::SmallVector<Expr*, 8> ProtoExprs;
2511 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002512 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2513 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002514 false, argType, SourceLocation(),
2515 SourceLocation()));
2516 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2517 &ProtoExprs[0],
2518 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002519 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002520 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002521 return ProtoExp;
2522
2523}
2524
Steve Naroffbaf58c32008-05-31 14:15:04 +00002525bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2526 const char *endBuf) {
2527 while (startBuf < endBuf) {
2528 if (*startBuf == '#') {
2529 // Skip whitespace.
2530 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2531 ;
2532 if (!strncmp(startBuf, "if", strlen("if")) ||
2533 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2534 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2535 !strncmp(startBuf, "define", strlen("define")) ||
2536 !strncmp(startBuf, "undef", strlen("undef")) ||
2537 !strncmp(startBuf, "else", strlen("else")) ||
2538 !strncmp(startBuf, "elif", strlen("elif")) ||
2539 !strncmp(startBuf, "endif", strlen("endif")) ||
2540 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2541 !strncmp(startBuf, "include", strlen("include")) ||
2542 !strncmp(startBuf, "import", strlen("import")) ||
2543 !strncmp(startBuf, "include_next", strlen("include_next")))
2544 return true;
2545 }
2546 startBuf++;
2547 }
2548 return false;
2549}
2550
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002551/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002552/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002553void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002554 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002555 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002556 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002557 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002558 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002559 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002560 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002561 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002562 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002563 SourceLocation LocStart = CDecl->getLocStart();
2564 SourceLocation LocEnd = CDecl->getLocEnd();
2565
2566 const char *startBuf = SM->getCharacterData(LocStart);
2567 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002568
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002569 // If no ivars and no root or if its root, directly or indirectly,
2570 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002571 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2572 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002573 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002574 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002575 return;
2576 }
2577
2578 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002579 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002580 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002581 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002582 if (LangOpts.Microsoft)
2583 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002584
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002585 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002586 const char *cursor = strchr(startBuf, '{');
2587 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002588 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002589 // If the buffer contains preprocessor directives, we do more fine-grained
2590 // rewrites. This is intended to fix code that looks like (which occurs in
2591 // NSURL.h, for example):
2592 //
2593 // #ifdef XYZ
2594 // @interface Foo : NSObject
2595 // #else
2596 // @interface FooBar : NSObject
2597 // #endif
2598 // {
2599 // int i;
2600 // }
2601 // @end
2602 //
2603 // This clause is segregated to avoid breaking the common case.
2604 if (BufferContainsPPDirectives(startBuf, cursor)) {
2605 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2606 CDecl->getClassLoc();
2607 const char *endHeader = SM->getCharacterData(L);
2608 endHeader += Lexer::MeasureTokenLength(L, *SM);
2609
Chris Lattner3db6cae2008-07-21 18:19:38 +00002610 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002611 // advance to the end of the referenced protocols.
2612 while (endHeader < cursor && *endHeader != '>') endHeader++;
2613 endHeader++;
2614 }
2615 // rewrite the original header
2616 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2617 } else {
2618 // rewrite the original header *without* disturbing the '{'
2619 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2620 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002621 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002622 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002623 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002624 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002625 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002626 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002627
2628 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002629 SourceLocation OnePastCurly =
2630 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2631 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002632 }
2633 cursor++; // past '{'
2634
2635 // Now comment out any visibility specifiers.
2636 while (cursor < endBuf) {
2637 if (*cursor == '@') {
2638 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002639 // Skip whitespace.
2640 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2641 /*scan*/;
2642
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002643 // FIXME: presence of @public, etc. inside comment results in
2644 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002645 if (!strncmp(cursor, "public", strlen("public")) ||
2646 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002647 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002648 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002649 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002650 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002651 // FIXME: If there are cases where '<' is used in ivar declaration part
2652 // of user code, then scan the ivar list and use needToScanForQualifiers
2653 // for type checking.
2654 else if (*cursor == '<') {
2655 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002656 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002657 cursor = strchr(cursor, '>');
2658 cursor++;
2659 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002660 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002661 } else if (*cursor == '^') { // rewrite block specifier.
2662 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2663 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002664 }
Steve Narofffea763e82007-11-14 19:25:57 +00002665 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002666 }
Steve Narofffea763e82007-11-14 19:25:57 +00002667 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002668 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002669 } else { // we don't have any instance variables - insert super struct.
2670 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2671 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002672 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002673 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002674 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002675 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002676 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002677 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002678 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002679 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002680 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002681}
2682
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002683// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002684/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002685void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002686 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002687 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002688 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002689 const char *ClassName,
2690 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002691 if (MethodBegin == MethodEnd) return;
2692
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002693 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002694 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002695 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002696 SEL _cmd;
2697 char *method_types;
2698 void *_imp;
2699 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002700 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002701 Result += "\nstruct _objc_method {\n";
2702 Result += "\tSEL _cmd;\n";
2703 Result += "\tchar *method_types;\n";
2704 Result += "\tvoid *_imp;\n";
2705 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002706
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002707 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002708 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002709
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002710 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002711
2712 /* struct {
2713 struct _objc_method_list *next_method;
2714 int method_count;
2715 struct _objc_method method_list[];
2716 }
2717 */
2718 Result += "\nstatic struct {\n";
2719 Result += "\tstruct _objc_method_list *next_method;\n";
2720 Result += "\tint method_count;\n";
2721 Result += "\tstruct _objc_method method_list[";
2722 Result += utostr(MethodEnd-MethodBegin);
2723 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002724 Result += prefix;
2725 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2726 Result += "_METHODS_";
2727 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002728 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002729 Result += IsInstanceMethod ? "inst" : "cls";
2730 Result += "_meth\")))= ";
2731 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002732
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002733 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002734 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002735 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002736 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002737 Result += "\", \"";
2738 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002739 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002740 Result += MethodInternalNames[*MethodBegin];
2741 Result += "}\n";
2742 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2743 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002744 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002745 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002746 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002747 Result += "\", \"";
2748 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002749 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002750 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002751 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002752 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002753 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002754}
2755
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002756/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002757void RewriteObjC::
2758RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2759 const char *prefix,
2760 const char *ClassName,
2761 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002762 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002763 if (Protocols.empty()) return;
2764
2765 for (unsigned i = 0; i != Protocols.size(); i++) {
2766 ObjCProtocolDecl *PDecl = Protocols[i];
2767 // Output struct protocol_methods holder of method selector and type.
2768 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2769 /* struct protocol_methods {
2770 SEL _cmd;
2771 char *method_types;
2772 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002773 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002774 Result += "\nstruct protocol_methods {\n";
2775 Result += "\tSEL _cmd;\n";
2776 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002777 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002778
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002779 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002780 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002781 // Do not synthesize the protocol more than once.
2782 if (ObjCSynthesizedProtocols.count(PDecl))
2783 continue;
2784
2785 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2786 unsigned NumMethods = PDecl->getNumInstanceMethods();
2787 /* struct _objc_protocol_method_list {
2788 int protocol_method_count;
2789 struct protocol_methods protocols[];
2790 }
2791 */
2792 Result += "\nstatic struct {\n";
2793 Result += "\tint protocol_method_count;\n";
2794 Result += "\tstruct protocol_methods protocols[";
2795 Result += utostr(NumMethods);
2796 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002797 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002798 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2799 "{\n\t" + utostr(NumMethods) + "\n";
2800
2801 // Output instance methods declared in this protocol.
2802 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2803 E = PDecl->instmeth_end(); I != E; ++I) {
2804 if (I == PDecl->instmeth_begin())
2805 Result += "\t ,{{(SEL)\"";
2806 else
2807 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002808 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002809 std::string MethodTypeString;
2810 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2811 Result += "\", \"";
2812 Result += MethodTypeString;
2813 Result += "\"}\n";
2814 }
2815 Result += "\t }\n};\n";
2816 }
2817
2818 // Output class methods declared in this protocol.
2819 int NumMethods = PDecl->getNumClassMethods();
2820 if (NumMethods > 0) {
2821 /* struct _objc_protocol_method_list {
2822 int protocol_method_count;
2823 struct protocol_methods protocols[];
2824 }
2825 */
2826 Result += "\nstatic struct {\n";
2827 Result += "\tint protocol_method_count;\n";
2828 Result += "\tstruct protocol_methods protocols[";
2829 Result += utostr(NumMethods);
2830 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002831 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002832 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2833 "{\n\t";
2834 Result += utostr(NumMethods);
2835 Result += "\n";
2836
2837 // Output instance methods declared in this protocol.
2838 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2839 E = PDecl->classmeth_end(); I != E; ++I) {
2840 if (I == PDecl->classmeth_begin())
2841 Result += "\t ,{{(SEL)\"";
2842 else
2843 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002844 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002845 std::string MethodTypeString;
2846 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2847 Result += "\", \"";
2848 Result += MethodTypeString;
2849 Result += "\"}\n";
2850 }
2851 Result += "\t }\n};\n";
2852 }
2853
2854 // Output:
2855 /* struct _objc_protocol {
2856 // Objective-C 1.0 extensions
2857 struct _objc_protocol_extension *isa;
2858 char *protocol_name;
2859 struct _objc_protocol **protocol_list;
2860 struct _objc_protocol_method_list *instance_methods;
2861 struct _objc_protocol_method_list *class_methods;
2862 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002863 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002864 static bool objc_protocol = false;
2865 if (!objc_protocol) {
2866 Result += "\nstruct _objc_protocol {\n";
2867 Result += "\tstruct _objc_protocol_extension *isa;\n";
2868 Result += "\tchar *protocol_name;\n";
2869 Result += "\tstruct _objc_protocol **protocol_list;\n";
2870 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2871 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2872 Result += "};\n";
2873
2874 objc_protocol = true;
2875 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002876
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002877 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002878 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002879 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2880 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002881 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002882 Result += "\", 0, ";
2883 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2884 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002885 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002886 Result += ", ";
2887 }
2888 else
2889 Result += "0, ";
2890 if (PDecl->getNumClassMethods() > 0) {
2891 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002892 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002893 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002894 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002895 else
2896 Result += "0\n";
2897 Result += "};\n";
2898
2899 // Mark this protocol as having been generated.
2900 if (!ObjCSynthesizedProtocols.insert(PDecl))
2901 assert(false && "protocol already synthesized");
2902 }
2903 // Output the top lovel protocol meta-data for the class.
2904 /* struct _objc_protocol_list {
2905 struct _objc_protocol_list *next;
2906 int protocol_count;
2907 struct _objc_protocol *class_protocols[];
2908 }
2909 */
2910 Result += "\nstatic struct {\n";
2911 Result += "\tstruct _objc_protocol_list *next;\n";
2912 Result += "\tint protocol_count;\n";
2913 Result += "\tstruct _objc_protocol *class_protocols[";
2914 Result += utostr(Protocols.size());
2915 Result += "];\n} _OBJC_";
2916 Result += prefix;
2917 Result += "_PROTOCOLS_";
2918 Result += ClassName;
2919 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2920 "{\n\t0, ";
2921 Result += utostr(Protocols.size());
2922 Result += "\n";
2923
2924 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002925 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002926 Result += " \n";
2927
2928 for (unsigned i = 1; i != Protocols.size(); i++) {
2929 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002930 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002931 Result += "\n";
2932 }
2933 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002934}
2935
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002936/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002937/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002938void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002939 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002940 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002941 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002942 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002943 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2944 CDecl = CDecl->getNextClassCategory())
2945 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2946 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002947
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002948 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002949 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002950 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002951
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002952 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002953 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002954 true, "CATEGORY_", FullCategoryName.c_str(),
2955 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002956
2957 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002958 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002959 false, "CATEGORY_", FullCategoryName.c_str(),
2960 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002961
2962 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002963 // Null CDecl is case of a category implementation with no category interface
2964 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002965 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002966 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002967
2968 /* struct _objc_category {
2969 char *category_name;
2970 char *class_name;
2971 struct _objc_method_list *instance_methods;
2972 struct _objc_method_list *class_methods;
2973 struct _objc_protocol_list *protocols;
2974 // Objective-C 1.0 extensions
2975 uint32_t size; // sizeof (struct _objc_category)
2976 struct _objc_property_list *instance_properties; // category's own
2977 // @property decl.
2978 };
2979 */
2980
2981 static bool objc_category = false;
2982 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002983 Result += "\nstruct _objc_category {\n";
2984 Result += "\tchar *category_name;\n";
2985 Result += "\tchar *class_name;\n";
2986 Result += "\tstruct _objc_method_list *instance_methods;\n";
2987 Result += "\tstruct _objc_method_list *class_methods;\n";
2988 Result += "\tstruct _objc_protocol_list *protocols;\n";
2989 Result += "\tunsigned int size;\n";
2990 Result += "\tstruct _objc_property_list *instance_properties;\n";
2991 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002992 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002993 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002994 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2995 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002996 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002997 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002998 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002999 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003000 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003001
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003002 if (IDecl->getNumInstanceMethods() > 0) {
3003 Result += "\t, (struct _objc_method_list *)"
3004 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3005 Result += FullCategoryName;
3006 Result += "\n";
3007 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003008 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003009 Result += "\t, 0\n";
3010 if (IDecl->getNumClassMethods() > 0) {
3011 Result += "\t, (struct _objc_method_list *)"
3012 "&_OBJC_CATEGORY_CLASS_METHODS_";
3013 Result += FullCategoryName;
3014 Result += "\n";
3015 }
3016 else
3017 Result += "\t, 0\n";
3018
Chris Lattner780f3292008-07-21 21:32:27 +00003019 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003020 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3021 Result += FullCategoryName;
3022 Result += "\n";
3023 }
3024 else
3025 Result += "\t, 0\n";
3026 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003027}
3028
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003029/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3030/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003031void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003032 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003033 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003034 if (ivar->isBitField()) {
3035 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3036 // place all bitfields at offset 0.
3037 Result += "0";
3038 } else {
3039 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003040 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003041 if (LangOpts.Microsoft)
3042 Result += "_IMPL";
3043 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003044 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003045 Result += ")";
3046 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003047}
3048
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003049//===----------------------------------------------------------------------===//
3050// Meta Data Emission
3051//===----------------------------------------------------------------------===//
3052
Steve Naroffb29b4272008-04-14 22:03:09 +00003053void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003054 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003055 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003056
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003057 // Explictly declared @interface's are already synthesized.
3058 if (CDecl->ImplicitInterfaceDecl()) {
3059 // FIXME: Implementation of a class with no @interface (legacy) doese not
3060 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003061 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003062 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003063
Chris Lattnerbe6df082007-12-12 07:56:42 +00003064 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003065 unsigned NumIvars = !IDecl->ivar_empty()
3066 ? IDecl->ivar_size()
3067 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003068 if (NumIvars > 0) {
3069 static bool objc_ivar = false;
3070 if (!objc_ivar) {
3071 /* struct _objc_ivar {
3072 char *ivar_name;
3073 char *ivar_type;
3074 int ivar_offset;
3075 };
3076 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003077 Result += "\nstruct _objc_ivar {\n";
3078 Result += "\tchar *ivar_name;\n";
3079 Result += "\tchar *ivar_type;\n";
3080 Result += "\tint ivar_offset;\n";
3081 Result += "};\n";
3082
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003083 objc_ivar = true;
3084 }
3085
Steve Naroff946a6932008-03-11 00:12:29 +00003086 /* struct {
3087 int ivar_count;
3088 struct _objc_ivar ivar_list[nIvars];
3089 };
3090 */
3091 Result += "\nstatic struct {\n";
3092 Result += "\tint ivar_count;\n";
3093 Result += "\tstruct _objc_ivar ivar_list[";
3094 Result += utostr(NumIvars);
3095 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003096 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003097 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003098 "{\n\t";
3099 Result += utostr(NumIvars);
3100 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003101
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003102 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003103 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003104 IVI = IDecl->ivar_begin();
3105 IVE = IDecl->ivar_end();
3106 } else {
3107 IVI = CDecl->ivar_begin();
3108 IVE = CDecl->ivar_end();
3109 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003110 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003111 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003112 Result += "\", \"";
3113 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003114 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003115 Result += StrEncoding;
3116 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003117 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003118 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003119 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003120 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003121 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003122 Result += "\", \"";
3123 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003124 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003125 Result += StrEncoding;
3126 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003127 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003128 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003129 }
3130
3131 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003132 }
3133
3134 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003135 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003136 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003137
3138 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003139 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003140 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003141
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003142 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003143 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003144 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003145
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003146
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003147 // Declaration of class/meta-class metadata
3148 /* struct _objc_class {
3149 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003150 const char *super_class_name;
3151 char *name;
3152 long version;
3153 long info;
3154 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003155 struct _objc_ivar_list *ivars;
3156 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003157 struct objc_cache *cache;
3158 struct objc_protocol_list *protocols;
3159 const char *ivar_layout;
3160 struct _objc_class_ext *ext;
3161 };
3162 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003163 static bool objc_class = false;
3164 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003165 Result += "\nstruct _objc_class {\n";
3166 Result += "\tstruct _objc_class *isa;\n";
3167 Result += "\tconst char *super_class_name;\n";
3168 Result += "\tchar *name;\n";
3169 Result += "\tlong version;\n";
3170 Result += "\tlong info;\n";
3171 Result += "\tlong instance_size;\n";
3172 Result += "\tstruct _objc_ivar_list *ivars;\n";
3173 Result += "\tstruct _objc_method_list *methods;\n";
3174 Result += "\tstruct objc_cache *cache;\n";
3175 Result += "\tstruct _objc_protocol_list *protocols;\n";
3176 Result += "\tconst char *ivar_layout;\n";
3177 Result += "\tstruct _objc_class_ext *ext;\n";
3178 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003179 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003180 }
3181
3182 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003183 ObjCInterfaceDecl *RootClass = 0;
3184 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003185 while (SuperClass) {
3186 RootClass = SuperClass;
3187 SuperClass = SuperClass->getSuperClass();
3188 }
3189 SuperClass = CDecl->getSuperClass();
3190
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003191 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003192 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003193 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003194 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003195 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003196 Result += "\"";
3197
3198 if (SuperClass) {
3199 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003200 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003201 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003202 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003203 Result += "\"";
3204 }
3205 else {
3206 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003207 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003208 Result += "\"";
3209 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003210 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003211 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003212 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003213 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003214 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003215 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003216 Result += "\n";
3217 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003218 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003219 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003220 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003221 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003222 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003223 Result += ",0,0\n";
3224 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003225 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003226 Result += "\t,0,0,0,0\n";
3227 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003228
3229 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003230 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003231 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003232 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003233 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003234 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003235 if (SuperClass) {
3236 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003237 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003238 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003239 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003240 Result += "\"";
3241 }
3242 else {
3243 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003244 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003245 Result += "\"";
3246 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003247 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003248 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003249 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003250 Result += ",0";
3251 else {
3252 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003253 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003254 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003255 if (LangOpts.Microsoft)
3256 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003257 Result += ")";
3258 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003259 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003260 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003261 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003262 Result += "\n\t";
3263 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003264 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003265 Result += ",0";
3266 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003267 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003268 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003269 Result += ", 0\n\t";
3270 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003271 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003272 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003273 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003274 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003275 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003276 Result += ", 0,0\n";
3277 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003278 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003279 Result += ",0,0,0\n";
3280 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003281}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003282
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003283/// RewriteImplementations - This routine rewrites all method implementations
3284/// and emits meta-data.
3285
Steve Narofface66252008-11-13 20:07:04 +00003286void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003287 int ClsDefCount = ClassImplementation.size();
3288 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003289
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003290 // Rewrite implemented methods
3291 for (int i = 0; i < ClsDefCount; i++)
3292 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003293
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003294 for (int i = 0; i < CatDefCount; i++)
3295 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003296}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003297
Steve Narofface66252008-11-13 20:07:04 +00003298void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3299 int ClsDefCount = ClassImplementation.size();
3300 int CatDefCount = CategoryImplementation.size();
3301
Steve Naroff5df5b762008-05-07 21:23:49 +00003302 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003303 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003304 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003305 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003306 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003307
3308 // For each implemented category, write out all its meta data.
3309 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003310 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003311
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003312 // Write objc_symtab metadata
3313 /*
3314 struct _objc_symtab
3315 {
3316 long sel_ref_cnt;
3317 SEL *refs;
3318 short cls_def_cnt;
3319 short cat_def_cnt;
3320 void *defs[cls_def_cnt + cat_def_cnt];
3321 };
3322 */
3323
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003324 Result += "\nstruct _objc_symtab {\n";
3325 Result += "\tlong sel_ref_cnt;\n";
3326 Result += "\tSEL *refs;\n";
3327 Result += "\tshort cls_def_cnt;\n";
3328 Result += "\tshort cat_def_cnt;\n";
3329 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3330 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003331
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003332 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003333 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003334 Result += "\t0, 0, " + utostr(ClsDefCount)
3335 + ", " + utostr(CatDefCount) + "\n";
3336 for (int i = 0; i < ClsDefCount; i++) {
3337 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003338 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003339 Result += "\n";
3340 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003341
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003342 for (int i = 0; i < CatDefCount; i++) {
3343 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003344 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003345 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003346 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003347 Result += "\n";
3348 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003349
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003350 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003351
3352 // Write objc_module metadata
3353
3354 /*
3355 struct _objc_module {
3356 long version;
3357 long size;
3358 const char *name;
3359 struct _objc_symtab *symtab;
3360 }
3361 */
3362
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003363 Result += "\nstruct _objc_module {\n";
3364 Result += "\tlong version;\n";
3365 Result += "\tlong size;\n";
3366 Result += "\tconst char *name;\n";
3367 Result += "\tstruct _objc_symtab *symtab;\n";
3368 Result += "};\n\n";
3369 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003370 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003371 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3372 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003373 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003374
3375 if (LangOpts.Microsoft) {
3376 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003377 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003378 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3379 Result += "&_OBJC_MODULES;\n";
3380 Result += "#pragma data_seg(pop)\n\n";
3381 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003382}
Chris Lattner311ff022007-10-16 22:36:42 +00003383
Steve Naroff54055232008-10-27 17:20:55 +00003384std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3385 const char *funcName,
3386 std::string Tag) {
3387 const FunctionType *AFT = CE->getFunctionType();
3388 QualType RT = AFT->getResultType();
3389 std::string StructRef = "struct " + Tag;
3390 std::string S = "static " + RT.getAsString() + " __" +
3391 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003392
Steve Naroff54055232008-10-27 17:20:55 +00003393 BlockDecl *BD = CE->getBlockDecl();
3394
3395 if (isa<FunctionTypeNoProto>(AFT)) {
3396 S += "()";
3397 } else if (BD->param_empty()) {
3398 S += "(" + StructRef + " *__cself)";
3399 } else {
3400 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3401 assert(FT && "SynthesizeBlockFunc: No function proto");
3402 S += '(';
3403 // first add the implicit argument.
3404 S += StructRef + " *__cself, ";
3405 std::string ParamStr;
3406 for (BlockDecl::param_iterator AI = BD->param_begin(),
3407 E = BD->param_end(); AI != E; ++AI) {
3408 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003409 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003410 (*AI)->getType().getAsStringInternal(ParamStr);
3411 S += ParamStr;
3412 }
3413 if (FT->isVariadic()) {
3414 if (!BD->param_empty()) S += ", ";
3415 S += "...";
3416 }
3417 S += ')';
3418 }
3419 S += " {\n";
3420
3421 // Create local declarations to avoid rewriting all closure decl ref exprs.
3422 // First, emit a declaration for all "by ref" decls.
3423 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3424 E = BlockByRefDecls.end(); I != E; ++I) {
3425 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003426 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003427 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003428 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003429 }
3430 // Next, emit a declaration for all "by copy" declarations.
3431 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3432 E = BlockByCopyDecls.end(); I != E; ++I) {
3433 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003434 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003435 // Handle nested closure invocation. For example:
3436 //
3437 // void (^myImportedClosure)(void);
3438 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3439 //
3440 // void (^anotherClosure)(void);
3441 // anotherClosure = ^(void) {
3442 // myImportedClosure(); // import and invoke the closure
3443 // };
3444 //
3445 if (isBlockPointerType((*I)->getType()))
3446 S += "struct __block_impl *";
3447 else
3448 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003449 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003450 }
3451 std::string RewrittenStr = RewrittenBlockExprs[CE];
3452 const char *cstr = RewrittenStr.c_str();
3453 while (*cstr++ != '{') ;
3454 S += cstr;
3455 S += "\n";
3456 return S;
3457}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003458
Steve Naroff54055232008-10-27 17:20:55 +00003459std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3460 const char *funcName,
3461 std::string Tag) {
3462 std::string StructRef = "struct " + Tag;
3463 std::string S = "static void __";
3464
3465 S += funcName;
3466 S += "_block_copy_" + utostr(i);
3467 S += "(" + StructRef;
3468 S += "*dst, " + StructRef;
3469 S += "*src) {";
3470 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3471 E = ImportedBlockDecls.end(); I != E; ++I) {
3472 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003473 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003474 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003475 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003476 S += ");}";
3477 }
3478 S += "\nstatic void __";
3479 S += funcName;
3480 S += "_block_dispose_" + utostr(i);
3481 S += "(" + StructRef;
3482 S += "*src) {";
3483 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3484 E = ImportedBlockDecls.end(); I != E; ++I) {
3485 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003486 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003487 S += ");";
3488 }
3489 S += "}\n";
3490 return S;
3491}
3492
3493std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3494 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003495 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003496 std::string Constructor = " " + Tag;
3497
3498 S += " {\n struct __block_impl impl;\n";
3499
3500 if (hasCopyDisposeHelpers)
3501 S += " void *copy;\n void *dispose;\n";
3502
3503 Constructor += "(void *fp";
3504
3505 if (hasCopyDisposeHelpers)
3506 Constructor += ", void *copyHelp, void *disposeHelp";
3507
3508 if (BlockDeclRefs.size()) {
3509 // Output all "by copy" declarations.
3510 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3511 E = BlockByCopyDecls.end(); I != E; ++I) {
3512 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003513 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003514 std::string ArgName = "_" + FieldName;
3515 // Handle nested closure invocation. For example:
3516 //
3517 // void (^myImportedBlock)(void);
3518 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3519 //
3520 // void (^anotherBlock)(void);
3521 // anotherBlock = ^(void) {
3522 // myImportedBlock(); // import and invoke the closure
3523 // };
3524 //
3525 if (isBlockPointerType((*I)->getType())) {
3526 S += "struct __block_impl *";
3527 Constructor += ", void *" + ArgName;
3528 } else {
3529 (*I)->getType().getAsStringInternal(FieldName);
3530 (*I)->getType().getAsStringInternal(ArgName);
3531 Constructor += ", " + ArgName;
3532 }
3533 S += FieldName + ";\n";
3534 }
3535 // Output all "by ref" declarations.
3536 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3537 E = BlockByRefDecls.end(); I != E; ++I) {
3538 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003539 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003540 std::string ArgName = "_" + FieldName;
3541 // Handle nested closure invocation. For example:
3542 //
3543 // void (^myImportedBlock)(void);
3544 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3545 //
3546 // void (^anotherBlock)(void);
3547 // anotherBlock = ^(void) {
3548 // myImportedBlock(); // import and invoke the closure
3549 // };
3550 //
3551 if (isBlockPointerType((*I)->getType())) {
3552 S += "struct __block_impl *";
3553 Constructor += ", void *" + ArgName;
3554 } else {
3555 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3556 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3557 Constructor += ", " + ArgName;
3558 }
3559 S += FieldName + "; // by ref\n";
3560 }
3561 // Finish writing the constructor.
3562 // FIXME: handle NSConcreteGlobalBlock.
3563 Constructor += ", int flags=0) {\n";
3564 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3565 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3566
3567 if (hasCopyDisposeHelpers)
3568 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3569
3570 // Initialize all "by copy" arguments.
3571 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3572 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003573 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003574 Constructor += " ";
3575 if (isBlockPointerType((*I)->getType()))
3576 Constructor += Name + " = (struct __block_impl *)_";
3577 else
3578 Constructor += Name + " = _";
3579 Constructor += Name + ";\n";
3580 }
3581 // Initialize all "by ref" arguments.
3582 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3583 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003584 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003585 Constructor += " ";
3586 if (isBlockPointerType((*I)->getType()))
3587 Constructor += Name + " = (struct __block_impl *)_";
3588 else
3589 Constructor += Name + " = _";
3590 Constructor += Name + ";\n";
3591 }
3592 } else {
3593 // Finish writing the constructor.
3594 // FIXME: handle NSConcreteGlobalBlock.
3595 Constructor += ", int flags=0) {\n";
3596 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3597 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3598 if (hasCopyDisposeHelpers)
3599 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3600 }
3601 Constructor += " ";
3602 Constructor += "}\n";
3603 S += Constructor;
3604 S += "};\n";
3605 return S;
3606}
3607
3608void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3609 const char *FunName) {
3610 // Insert closures that were part of the function.
3611 for (unsigned i = 0; i < Blocks.size(); i++) {
3612
3613 CollectBlockDeclRefInfo(Blocks[i]);
3614
3615 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3616
3617 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3618 ImportedBlockDecls.size() > 0);
3619
3620 InsertText(FunLocStart, CI.c_str(), CI.size());
3621
3622 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3623
3624 InsertText(FunLocStart, CF.c_str(), CF.size());
3625
3626 if (ImportedBlockDecls.size()) {
3627 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3628 InsertText(FunLocStart, HF.c_str(), HF.size());
3629 }
3630
3631 BlockDeclRefs.clear();
3632 BlockByRefDecls.clear();
3633 BlockByCopyDecls.clear();
3634 BlockCallExprs.clear();
3635 ImportedBlockDecls.clear();
3636 }
3637 Blocks.clear();
3638 RewrittenBlockExprs.clear();
3639}
3640
3641void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3642 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003643 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003644
3645 SynthesizeBlockLiterals(FunLocStart, FuncName);
3646}
3647
3648void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003649 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3650 //SourceLocation FunLocStart = MD->getLocStart();
3651 // FIXME: This hack works around a bug in Rewrite.InsertText().
3652 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003653 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003654 // Convert colons to underscores.
3655 std::string::size_type loc = 0;
3656 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3657 FuncName.replace(loc, 1, "_");
3658
3659 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3660}
3661
3662void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3663 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3664 CI != E; ++CI)
3665 if (*CI) {
3666 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3667 GetBlockDeclRefExprs(CBE->getBody());
3668 else
3669 GetBlockDeclRefExprs(*CI);
3670 }
3671 // Handle specific things.
3672 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3673 // FIXME: Handle enums.
3674 if (!isa<FunctionDecl>(CDRE->getDecl()))
3675 BlockDeclRefs.push_back(CDRE);
3676 return;
3677}
3678
3679void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3680 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3681 CI != E; ++CI)
3682 if (*CI) {
3683 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3684 GetBlockCallExprs(CBE->getBody());
3685 else
3686 GetBlockCallExprs(*CI);
3687 }
3688
3689 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3690 if (CE->getCallee()->getType()->isBlockPointerType()) {
3691 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3692 }
3693 }
3694 return;
3695}
3696
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003697Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003698 // Navigate to relevant type information.
3699 const char *closureName = 0;
3700 const BlockPointerType *CPT = 0;
3701
3702 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003703 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003704 CPT = DRE->getType()->getAsBlockPointerType();
3705 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003706 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003707 CPT = CDRE->getType()->getAsBlockPointerType();
3708 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003709 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003710 CPT = MExpr->getType()->getAsBlockPointerType();
3711 } else {
3712 assert(1 && "RewriteBlockClass: Bad type");
3713 }
3714 assert(CPT && "RewriteBlockClass: Bad type");
3715 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3716 assert(FT && "RewriteBlockClass: Bad type");
3717 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3718 // FTP will be null for closures that don't take arguments.
3719
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003720 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3721 SourceLocation(),
3722 &Context->Idents.get("__block_impl"));
3723 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003724
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003725 // Generate a funky cast.
3726 llvm::SmallVector<QualType, 8> ArgTypes;
3727
3728 // Push the block argument type.
3729 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003730 if (FTP) {
3731 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003732 E = FTP->arg_type_end(); I && (I != E); ++I) {
3733 QualType t = *I;
3734 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3735 if (isBlockPointerType(t)) {
3736 const BlockPointerType *BPT = t->getAsBlockPointerType();
3737 t = Context->getPointerType(BPT->getPointeeType());
3738 }
3739 ArgTypes.push_back(t);
3740 }
Steve Naroff54055232008-10-27 17:20:55 +00003741 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003742 // Now do the pointer to function cast.
3743 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3744 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3745
3746 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003747
Steve Naroffb2f9e512008-11-03 23:29:32 +00003748 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003749 // Don't forget the parens to enforce the proper binding.
3750 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3751 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003752
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003753 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3754 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3755 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3756
Steve Naroffb2f9e512008-11-03 23:29:32 +00003757 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003758 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3759
3760 llvm::SmallVector<Expr*, 8> BlkExprs;
3761 // Add the implicit argument.
3762 BlkExprs.push_back(BlkCast);
3763 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003764 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3765 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003766 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003767 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003768 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3769 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003770}
3771
3772void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003773 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3774 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003775}
3776
3777void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3778 // FIXME: Add more elaborate code generation required by the ABI.
3779 InsertText(BDRE->getLocStart(), "*", 1);
3780}
3781
Steve Naroffb2f9e512008-11-03 23:29:32 +00003782void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3783 SourceLocation LocStart = CE->getLParenLoc();
3784 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003785
3786 // Need to avoid trying to rewrite synthesized casts.
3787 if (LocStart.isInvalid())
3788 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003789 // Need to avoid trying to rewrite casts contained in macros.
3790 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3791 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003792
Steve Naroff54055232008-10-27 17:20:55 +00003793 const char *startBuf = SM->getCharacterData(LocStart);
3794 const char *endBuf = SM->getCharacterData(LocEnd);
3795
3796 // advance the location to startArgList.
3797 const char *argPtr = startBuf;
3798
3799 while (*argPtr++ && (argPtr < endBuf)) {
3800 switch (*argPtr) {
3801 case '^':
3802 // Replace the '^' with '*'.
3803 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3804 ReplaceText(LocStart, 1, "*", 1);
3805 break;
3806 }
3807 }
3808 return;
3809}
3810
3811void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3812 SourceLocation DeclLoc = FD->getLocation();
3813 unsigned parenCount = 0;
3814
3815 // We have 1 or more arguments that have closure pointers.
3816 const char *startBuf = SM->getCharacterData(DeclLoc);
3817 const char *startArgList = strchr(startBuf, '(');
3818
3819 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3820
3821 parenCount++;
3822 // advance the location to startArgList.
3823 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3824 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3825
3826 const char *argPtr = startArgList;
3827
3828 while (*argPtr++ && parenCount) {
3829 switch (*argPtr) {
3830 case '^':
3831 // Replace the '^' with '*'.
3832 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3833 ReplaceText(DeclLoc, 1, "*", 1);
3834 break;
3835 case '(':
3836 parenCount++;
3837 break;
3838 case ')':
3839 parenCount--;
3840 break;
3841 }
3842 }
3843 return;
3844}
3845
3846bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3847 const FunctionTypeProto *FTP;
3848 const PointerType *PT = QT->getAsPointerType();
3849 if (PT) {
3850 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3851 } else {
3852 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3853 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3854 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3855 }
3856 if (FTP) {
3857 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3858 E = FTP->arg_type_end(); I != E; ++I)
3859 if (isBlockPointerType(*I))
3860 return true;
3861 }
3862 return false;
3863}
3864
3865void RewriteObjC::GetExtentOfArgList(const char *Name,
3866 const char *&LParen, const char *&RParen) {
3867 const char *argPtr = strchr(Name, '(');
3868 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3869
3870 LParen = argPtr; // output the start.
3871 argPtr++; // skip past the left paren.
3872 unsigned parenCount = 1;
3873
3874 while (*argPtr && parenCount) {
3875 switch (*argPtr) {
3876 case '(': parenCount++; break;
3877 case ')': parenCount--; break;
3878 default: break;
3879 }
3880 if (parenCount) argPtr++;
3881 }
3882 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3883 RParen = argPtr; // output the end
3884}
3885
3886void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3887 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3888 RewriteBlockPointerFunctionArgs(FD);
3889 return;
3890 }
3891 // Handle Variables and Typedefs.
3892 SourceLocation DeclLoc = ND->getLocation();
3893 QualType DeclT;
3894 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3895 DeclT = VD->getType();
3896 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3897 DeclT = TDD->getUnderlyingType();
3898 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3899 DeclT = FD->getType();
3900 else
3901 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3902
3903 const char *startBuf = SM->getCharacterData(DeclLoc);
3904 const char *endBuf = startBuf;
3905 // scan backward (from the decl location) for the end of the previous decl.
3906 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3907 startBuf--;
3908
3909 // *startBuf != '^' if we are dealing with a pointer to function that
3910 // may take block argument types (which will be handled below).
3911 if (*startBuf == '^') {
3912 // Replace the '^' with '*', computing a negative offset.
3913 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3914 ReplaceText(DeclLoc, 1, "*", 1);
3915 }
3916 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3917 // Replace the '^' with '*' for arguments.
3918 DeclLoc = ND->getLocation();
3919 startBuf = SM->getCharacterData(DeclLoc);
3920 const char *argListBegin, *argListEnd;
3921 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3922 while (argListBegin < argListEnd) {
3923 if (*argListBegin == '^') {
3924 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3925 ReplaceText(CaretLoc, 1, "*", 1);
3926 }
3927 argListBegin++;
3928 }
3929 }
3930 return;
3931}
3932
3933void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3934 // Add initializers for any closure decl refs.
3935 GetBlockDeclRefExprs(Exp->getBody());
3936 if (BlockDeclRefs.size()) {
3937 // Unique all "by copy" declarations.
3938 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3939 if (!BlockDeclRefs[i]->isByRef())
3940 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3941 // Unique all "by ref" declarations.
3942 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3943 if (BlockDeclRefs[i]->isByRef()) {
3944 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3945 }
3946 // Find any imported blocks...they will need special attention.
3947 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3948 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003949 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003950 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3951 }
3952 }
3953}
3954
Steve Narofffa15fd92008-10-28 20:29:00 +00003955FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3956 IdentifierInfo *ID = &Context->Idents.get(name);
3957 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3958 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3959 ID, FType, FunctionDecl::Extern, false, 0);
3960}
3961
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003962Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003963 Blocks.push_back(Exp);
3964
3965 CollectBlockDeclRefInfo(Exp);
3966 std::string FuncName;
3967
3968 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003969 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003970 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00003971 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003972 // Convert colons to underscores.
3973 std::string::size_type loc = 0;
3974 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3975 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003976 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003977 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00003978
3979 std::string BlockNumber = utostr(Blocks.size()-1);
3980
3981 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3982 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3983
3984 // Get a pointer to the function type so we can cast appropriately.
3985 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3986
3987 FunctionDecl *FD;
3988 Expr *NewRep;
3989
3990 // Simulate a contructor call...
3991 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3992 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3993
3994 llvm::SmallVector<Expr*, 4> InitExprs;
3995
Steve Narofffdc03722008-10-29 21:23:59 +00003996 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003997 FD = SynthBlockInitFunctionDecl(Func.c_str());
3998 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3999 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004000 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004001 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004002
4003 if (ImportedBlockDecls.size()) {
4004 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004005 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4006 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4007 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004008 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004009 InitExprs.push_back(castExpr);
4010
Steve Narofffa15fd92008-10-28 20:29:00 +00004011 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004012 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4013 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4014 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004015 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004016 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004017 }
4018 // Add initializers for any closure decl refs.
4019 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004020 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004021 // Output all "by copy" declarations.
4022 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4023 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004024 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004025 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004026 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004027 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004028 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004029 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004030 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4031 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004032 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004033 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004034 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004035 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004036 }
Steve Narofffdc03722008-10-29 21:23:59 +00004037 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004038 }
4039 // Output all "by ref" declarations.
4040 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4041 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004042 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004043 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4044 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
4045 Context->getPointerType(Exp->getType()),
4046 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004047 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004048 }
4049 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004050 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
4051 FType, SourceLocation());
4052 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
4053 Context->getPointerType(NewRep->getType()),
4054 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00004055 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004056 BlockDeclRefs.clear();
4057 BlockByRefDecls.clear();
4058 BlockByCopyDecls.clear();
4059 ImportedBlockDecls.clear();
4060 return NewRep;
4061}
4062
4063//===----------------------------------------------------------------------===//
4064// Function Body / Expression rewriting
4065//===----------------------------------------------------------------------===//
4066
Steve Naroffc77a6362008-12-04 16:24:46 +00004067// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4068// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4069// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4070// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4071// Since the rewriter isn't capable of rewriting rewritten code, it's important
4072// we get this right.
4073void RewriteObjC::CollectPropertySetters(Stmt *S) {
4074 // Perform a bottom up traversal of all children.
4075 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4076 CI != E; ++CI)
4077 if (*CI)
4078 CollectPropertySetters(*CI);
4079
4080 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4081 if (BinOp->isAssignmentOp()) {
4082 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4083 PropSetters[PRE] = BinOp;
4084 }
4085 }
4086}
4087
Steve Narofffa15fd92008-10-28 20:29:00 +00004088Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4089 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4090 isa<DoStmt>(S) || isa<ForStmt>(S))
4091 Stmts.push_back(S);
4092 else if (isa<ObjCForCollectionStmt>(S)) {
4093 Stmts.push_back(S);
4094 ObjCBcLabelNo.push_back(++BcLabelCount);
4095 }
4096
4097 SourceRange OrigStmtRange = S->getSourceRange();
4098
4099 // Perform a bottom up rewrite of all children.
4100 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4101 CI != E; ++CI)
4102 if (*CI) {
4103 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4104 if (newStmt)
4105 *CI = newStmt;
4106 }
4107
4108 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4109 // Rewrite the block body in place.
4110 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4111
4112 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004113 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4114 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004115
4116 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4117 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004118 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004119 return blockTranscribed;
4120 }
4121 // Handle specific things.
4122 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4123 return RewriteAtEncode(AtEncode);
4124
4125 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4126 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4127
Steve Naroffc77a6362008-12-04 16:24:46 +00004128 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4129 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4130 if (BinOp) {
4131 // Because the rewriter doesn't allow us to rewrite rewritten code,
4132 // we need to rewrite the right hand side prior to rewriting the setter.
4133 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff4c3580e2008-12-04 23:50:32 +00004134 //
4135 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4136 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4137 // to see the original expression). Consider this example:
4138 //
4139 // Foo *obj1, *obj2;
4140 //
4141 // obj1.i = [obj2 rrrr];
4142 //
4143 // 'BinOp' for the previous expression looks like:
4144 //
4145 // (BinaryOperator 0x231ccf0 'int' '='
4146 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4147 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4148 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4149 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4150 //
4151 // 'newStmt' represents the rewritten message expression. For example:
4152 //
4153 // (CallExpr 0x231d300 'id':'struct objc_object *'
4154 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4155 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4156 // (CStyleCastExpr 0x231d220 'void *'
4157 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4158 //
4159 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4160 // can be used as the setter argument. ReplaceStmt() will still 'see'
4161 // the original RHS (since we haven't altered BinOp).
4162 //
4163 // This implies the Rewrite* routines can no longer delete the original
4164 // node. As a result, we now leak the original AST nodes.
4165 //
Steve Naroffc77a6362008-12-04 16:24:46 +00004166 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt));
4167 } else {
4168 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004169 }
4170 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004171 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4172 return RewriteAtSelector(AtSelector);
4173
4174 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4175 return RewriteObjCStringLiteral(AtString);
4176
4177 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004178#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004179 // Before we rewrite it, put the original message expression in a comment.
4180 SourceLocation startLoc = MessExpr->getLocStart();
4181 SourceLocation endLoc = MessExpr->getLocEnd();
4182
4183 const char *startBuf = SM->getCharacterData(startLoc);
4184 const char *endBuf = SM->getCharacterData(endLoc);
4185
4186 std::string messString;
4187 messString += "// ";
4188 messString.append(startBuf, endBuf-startBuf+1);
4189 messString += "\n";
4190
4191 // FIXME: Missing definition of
4192 // InsertText(clang::SourceLocation, char const*, unsigned int).
4193 // InsertText(startLoc, messString.c_str(), messString.size());
4194 // Tried this, but it didn't work either...
4195 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004196#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004197 return RewriteMessageExpr(MessExpr);
4198 }
4199
4200 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4201 return RewriteObjCTryStmt(StmtTry);
4202
4203 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4204 return RewriteObjCSynchronizedStmt(StmtTry);
4205
4206 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4207 return RewriteObjCThrowStmt(StmtThrow);
4208
4209 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4210 return RewriteObjCProtocolExpr(ProtocolExp);
4211
4212 if (ObjCForCollectionStmt *StmtForCollection =
4213 dyn_cast<ObjCForCollectionStmt>(S))
4214 return RewriteObjCForCollectionStmt(StmtForCollection,
4215 OrigStmtRange.getEnd());
4216 if (BreakStmt *StmtBreakStmt =
4217 dyn_cast<BreakStmt>(S))
4218 return RewriteBreakStmt(StmtBreakStmt);
4219 if (ContinueStmt *StmtContinueStmt =
4220 dyn_cast<ContinueStmt>(S))
4221 return RewriteContinueStmt(StmtContinueStmt);
4222
4223 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4224 // and cast exprs.
4225 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4226 // FIXME: What we're doing here is modifying the type-specifier that
4227 // precedes the first Decl. In the future the DeclGroup should have
4228 // a separate type-specifier that we can rewrite.
4229 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4230
4231 // Blocks rewrite rules.
4232 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4233 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004234 ScopedDecl *SD = *DI;
4235 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4236 if (isBlockPointerType(ND->getType()))
4237 RewriteBlockPointerDecl(ND);
4238 else if (ND->getType()->isFunctionPointerType())
4239 CheckFunctionPointerDecl(ND->getType(), ND);
4240 }
4241 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4242 if (isBlockPointerType(TD->getUnderlyingType()))
4243 RewriteBlockPointerDecl(TD);
4244 else if (TD->getUnderlyingType()->isFunctionPointerType())
4245 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4246 }
4247 }
4248 }
4249
4250 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4251 RewriteObjCQualifiedInterfaceTypes(CE);
4252
4253 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4254 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4255 assert(!Stmts.empty() && "Statement stack is empty");
4256 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4257 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4258 && "Statement stack mismatch");
4259 Stmts.pop_back();
4260 }
4261 // Handle blocks rewriting.
4262 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4263 if (BDRE->isByRef())
4264 RewriteBlockDeclRefExpr(BDRE);
4265 }
4266 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004267 if (CE->getCallee()->getType()->isBlockPointerType()) {
4268 Stmt *BlockCall = SynthesizeBlockCall(CE);
4269 ReplaceStmt(S, BlockCall);
4270 return BlockCall;
4271 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004272 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004273 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004274 RewriteCastExpr(CE);
4275 }
4276#if 0
4277 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4278 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4279 // Get the new text.
4280 std::string SStr;
4281 llvm::raw_string_ostream Buf(SStr);
4282 Replacement->printPretty(Buf);
4283 const std::string &Str = Buf.str();
4284
4285 printf("CAST = %s\n", &Str[0]);
4286 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4287 delete S;
4288 return Replacement;
4289 }
4290#endif
4291 // Return this stmt unmodified.
4292 return S;
4293}
4294
4295/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4296/// main file of the input.
4297void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4298 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4299 // Since function prototypes don't have ParmDecl's, we check the function
4300 // prototype. This enables us to rewrite function declarations and
4301 // definitions using the same code.
4302 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4303
4304 if (Stmt *Body = FD->getBody()) {
4305 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004306 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004307 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004308 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004309 CurrentBody = 0;
4310 if (PropParentMap) {
4311 delete PropParentMap;
4312 PropParentMap = 0;
4313 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004314 // This synthesizes and inserts the block "impl" struct, invoke function,
4315 // and any copy/dispose helper functions.
4316 InsertBlockLiteralsWithinFunction(FD);
4317 CurFunctionDef = 0;
4318 }
4319 return;
4320 }
4321 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4322 if (Stmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004323 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004324 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004325 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004326 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004327 CurrentBody = 0;
4328 if (PropParentMap) {
4329 delete PropParentMap;
4330 PropParentMap = 0;
4331 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004332 InsertBlockLiteralsWithinMethod(MD);
4333 CurMethodDef = 0;
4334 }
4335 }
4336 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4337 ClassImplementation.push_back(CI);
4338 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4339 CategoryImplementation.push_back(CI);
4340 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4341 RewriteForwardClassDecl(CD);
4342 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4343 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004344 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004345 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004346 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004347 CheckFunctionPointerDecl(VD->getType(), VD);
4348 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004349 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004350 RewriteCastExpr(CE);
4351 }
4352 }
4353 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004354 if (VD->getInit()) {
4355 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004356 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004357 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004358 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004359 CurrentBody = 0;
4360 if (PropParentMap) {
4361 delete PropParentMap;
4362 PropParentMap = 0;
4363 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004364 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004365 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004366 GlobalVarDecl = 0;
4367
4368 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004369 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004370 RewriteCastExpr(CE);
4371 }
4372 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004373 return;
4374 }
4375 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4376 if (isBlockPointerType(TD->getUnderlyingType()))
4377 RewriteBlockPointerDecl(TD);
4378 else if (TD->getUnderlyingType()->isFunctionPointerType())
4379 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4380 return;
4381 }
4382 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4383 if (RD->isDefinition()) {
4384 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4385 e = RD->field_end(); i != e; ++i) {
4386 FieldDecl *FD = *i;
4387 if (isBlockPointerType(FD->getType()))
4388 RewriteBlockPointerDecl(FD);
4389 }
4390 }
4391 return;
4392 }
4393 // Nothing yet.
4394}
4395
4396void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4397 // Get the top-level buffer that this corresponds to.
4398
4399 // Rewrite tabs if we care.
4400 //RewriteTabs();
4401
4402 if (Diags.hasErrorOccurred())
4403 return;
4404
4405 // Create the output file.
4406
4407 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4408 llvm::raw_ostream *OutFile;
4409 if (OutFileName == "-") {
4410 OutFile = &llvm::outs();
4411 } else if (!OutFileName.empty()) {
4412 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004413 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004414 OwnedStream.reset(OutFile);
4415 } else if (InFileName == "-") {
4416 OutFile = &llvm::outs();
4417 } else {
4418 llvm::sys::Path Path(InFileName);
4419 Path.eraseSuffix();
4420 Path.appendSuffix("cpp");
4421 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004422 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004423 OwnedStream.reset(OutFile);
4424 }
4425
4426 RewriteInclude();
4427
4428 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4429 Preamble.c_str(), Preamble.size(), false);
4430
Steve Naroff0aab7962008-11-14 14:10:01 +00004431 if (ClassImplementation.size() || CategoryImplementation.size())
4432 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004433
4434 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4435 // we are done.
4436 if (const RewriteBuffer *RewriteBuf =
4437 Rewrite.getRewriteBufferFor(MainFileID)) {
4438 //printf("Changed:\n");
4439 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4440 } else {
4441 fprintf(stderr, "No changes\n");
4442 }
Steve Narofface66252008-11-13 20:07:04 +00004443
Steve Naroff0aab7962008-11-14 14:10:01 +00004444 if (ClassImplementation.size() || CategoryImplementation.size()) {
4445 // Rewrite Objective-c meta data*
4446 std::string ResultStr;
4447 SynthesizeMetaDataIntoBuffer(ResultStr);
4448 // Emit metadata.
4449 *OutFile << ResultStr;
4450 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004451 OutFile->flush();
4452}
4453