blob: b3f3e9221366baf82e44120dbe4b6af5264b2ce2 [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 Naroff4ebd7162008-12-08 17:30:33 +0000444 if (LangOpts.Microsoft) {
445 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
446 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
447 } else
448 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
449 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000450 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000451 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000452 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000453 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000454 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000455 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000456 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000457 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000458 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000459 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000460 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000461 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000462 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000463 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
464 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
465 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
466 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
467 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000468 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000469 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000470 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
471 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
472 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000473 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
474 Preamble += "struct __objcFastEnumerationState {\n\t";
475 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000476 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000477 Preamble += "unsigned long *mutationsPtr;\n\t";
478 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000479 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000480 Preamble += "#define __FASTENUMERATIONSTATE\n";
481 Preamble += "#endif\n";
482 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
483 Preamble += "struct __NSConstantStringImpl {\n";
484 Preamble += " int *isa;\n";
485 Preamble += " int flags;\n";
486 Preamble += " char *str;\n";
487 Preamble += " long length;\n";
488 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000489 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
490 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
491 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000492 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000493 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000494 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
495 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000496 // Blocks preamble.
497 Preamble += "#ifndef BLOCK_IMPL\n";
498 Preamble += "#define BLOCK_IMPL\n";
499 Preamble += "struct __block_impl {\n";
500 Preamble += " void *isa;\n";
501 Preamble += " int Flags;\n";
502 Preamble += " int Size;\n";
503 Preamble += " void *FuncPtr;\n";
504 Preamble += "};\n";
505 Preamble += "enum {\n";
506 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
507 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
508 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000509 Preamble += "// Runtime copy/destroy helper functions\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000510 Preamble += "__OBJC_RW_STATICIMPORT void _Block_copy_assign(void *, void *);\n";
511 Preamble += "__OBJC_RW_STATICIMPORT void _Block_byref_assign_copy(void *, void *);\n";
512 Preamble += "__OBJC_RW_STATICIMPORT void _Block_destroy(void *);\n";
513 Preamble += "__OBJC_RW_STATICIMPORT void _Block_byref_release(void *);\n";
514 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock;\n";
515 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000516 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000517 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000518 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
519 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000520 Preamble += "#define __attribute__(X)\n";
521 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000522}
523
524
Chris Lattnerf04da132007-10-24 17:06:59 +0000525//===----------------------------------------------------------------------===//
526// Top Level Driver Code
527//===----------------------------------------------------------------------===//
528
Steve Naroffb29b4272008-04-14 22:03:09 +0000529void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000530 // Two cases: either the decl could be in the main file, or it could be in a
531 // #included file. If the former, rewrite it now. If the later, check to see
532 // if we rewrote the #include/#import.
533 SourceLocation Loc = D->getLocation();
534 Loc = SM->getLogicalLoc(Loc);
535
536 // If this is for a builtin, ignore it.
537 if (Loc.isInvalid()) return;
538
Steve Naroffebf2b562007-10-23 23:50:29 +0000539 // Look for built-in declarations that we need to refer during the rewrite.
540 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000541 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000542 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000543 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000544 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000545 ConstantStringClassReference = FVD;
546 return;
547 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000548 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000549 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000550 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000551 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000552 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000553 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000554 } else if (ObjCForwardProtocolDecl *FP =
555 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000556 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000557 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000558 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000559 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000560 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000561}
562
Chris Lattnerf04da132007-10-24 17:06:59 +0000563//===----------------------------------------------------------------------===//
564// Syntactic (non-AST) Rewriting Code
565//===----------------------------------------------------------------------===//
566
Steve Naroffb29b4272008-04-14 22:03:09 +0000567void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000568 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
569 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
570 const char *MainBufStart = MainBuf.first;
571 const char *MainBufEnd = MainBuf.second;
572 size_t ImportLen = strlen("import");
573 size_t IncludeLen = strlen("include");
574
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000575 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000576 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
577 if (*BufPtr == '#') {
578 if (++BufPtr == MainBufEnd)
579 return;
580 while (*BufPtr == ' ' || *BufPtr == '\t')
581 if (++BufPtr == MainBufEnd)
582 return;
583 if (!strncmp(BufPtr, "import", ImportLen)) {
584 // replace import with include
585 SourceLocation ImportLoc =
586 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000587 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000588 BufPtr += ImportLen;
589 }
590 }
591 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000592}
593
Steve Naroffb29b4272008-04-14 22:03:09 +0000594void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000595 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
596 const char *MainBufStart = MainBuf.first;
597 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000598
Chris Lattnerf04da132007-10-24 17:06:59 +0000599 // Loop over the whole file, looking for tabs.
600 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
601 if (*BufPtr != '\t')
602 continue;
603
604 // Okay, we found a tab. This tab will turn into at least one character,
605 // but it depends on which 'virtual column' it is in. Compute that now.
606 unsigned VCol = 0;
607 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
608 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
609 ++VCol;
610
611 // Okay, now that we know the virtual column, we know how many spaces to
612 // insert. We assume 8-character tab-stops.
613 unsigned Spaces = 8-(VCol & 7);
614
615 // Get the location of the tab.
616 SourceLocation TabLoc =
617 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
618
619 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000620 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000621 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000622}
623
Steve Naroffeb0646c2008-12-02 15:48:25 +0000624static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
625 ObjCIvarDecl *OID) {
626 std::string S;
627 S = "((struct ";
628 S += ClassDecl->getIdentifier()->getName();
629 S += "_IMPL *)self)->";
630 S += OID->getNameAsCString();
631 return S;
632}
633
Steve Naroffa0876e82008-12-02 17:36:43 +0000634void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
635 ObjCImplementationDecl *IMD,
636 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000637 SourceLocation startLoc = PID->getLocStart();
638 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000639 const char *startBuf = SM->getCharacterData(startLoc);
640 assert((*startBuf == '@') && "bogus @synthesize location");
641 const char *semiBuf = strchr(startBuf, ';');
642 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
643 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
644
645 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
646 return; // FIXME: is this correct?
647
648 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000649 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000650 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000651 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000652
653 if (!OID)
654 return;
655
656 std::string Getr;
657 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
658 Getr += "{ ";
659 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000660 // FIXME: deal with code generation implications for various property
661 // attributes (copy, retain, nonatomic).
662 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000663 Getr += "return " + getIvarAccessString(ClassDecl, OID);
664 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000665 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000666
667 // Add the rewritten getter to trigger meta data generation. An alternate, and
668 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
669 // with properties explicitly. The following addInstanceMethod() required far
670 // less code change (and actually models what the rewriter is doing).
671 if (IMD)
672 IMD->addInstanceMethod(PD->getGetterMethodDecl());
673 else
674 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000675
676 if (PD->isReadOnly())
677 return;
678
679 // Generate the 'setter' function.
680 std::string Setr;
681 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000682 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000683 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000684 // FIXME: deal with code generation implications for various property
685 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000686 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000687 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
688 Setr += OID->getNameAsCString();
689 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000690 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000691
692 // Add the rewritten setter to trigger meta data generation.
693 if (IMD)
694 IMD->addInstanceMethod(PD->getSetterMethodDecl());
695 else
696 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000697}
Chris Lattner8a12c272007-10-11 18:38:32 +0000698
Steve Naroffb29b4272008-04-14 22:03:09 +0000699void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000700 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000701 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000702
703 // Get the start location and compute the semi location.
704 SourceLocation startLoc = ClassDecl->getLocation();
705 const char *startBuf = SM->getCharacterData(startLoc);
706 const char *semiPtr = strchr(startBuf, ';');
707
708 // Translate to typedef's that forward reference structs with the same name
709 // as the class. As a convenience, we include the original declaration
710 // as a comment.
711 std::string typedefString;
712 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000713 typedefString.append(startBuf, semiPtr-startBuf+1);
714 typedefString += "\n";
715 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000717 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000718 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000719 typedefString += "\n";
720 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000721 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000722 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000723 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000724 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000725 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000726 }
727
728 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000729 ReplaceText(startLoc, semiPtr-startBuf+1,
730 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000731}
732
Steve Naroffb29b4272008-04-14 22:03:09 +0000733void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000734 SourceLocation LocStart = Method->getLocStart();
735 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000736
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000737 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000738 InsertText(LocStart, "#if 0\n", 6);
739 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000740 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000741 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000742 }
743}
744
Steve Naroffb29b4272008-04-14 22:03:09 +0000745void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000746{
Chris Lattner55d13b42008-03-16 21:23:50 +0000747 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000748 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000749 SourceLocation Loc = Property->getLocation();
750
Chris Lattneraadaf782008-01-31 19:51:04 +0000751 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000752
753 // FIXME: handle properties that are declared across multiple lines.
754 }
755}
756
Steve Naroffb29b4272008-04-14 22:03:09 +0000757void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000758 SourceLocation LocStart = CatDecl->getLocStart();
759
760 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000761 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000762
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000763 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000764 E = CatDecl->instmeth_end(); I != E; ++I)
765 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000766 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000767 E = CatDecl->classmeth_end(); I != E; ++I)
768 RewriteMethodDeclaration(*I);
769
Steve Naroff423cb562007-10-30 13:30:57 +0000770 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000771 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000772}
773
Steve Naroffb29b4272008-04-14 22:03:09 +0000774void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000775 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000776
Steve Naroff752d6ef2007-10-30 16:42:30 +0000777 SourceLocation LocStart = PDecl->getLocStart();
778
779 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000780 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000781
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000782 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000783 E = PDecl->instmeth_end(); I != E; ++I)
784 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000785 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000786 E = PDecl->classmeth_end(); I != E; ++I)
787 RewriteMethodDeclaration(*I);
788
Steve Naroff752d6ef2007-10-30 16:42:30 +0000789 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000790 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000791 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000792
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000793 // Must comment out @optional/@required
794 const char *startBuf = SM->getCharacterData(LocStart);
795 const char *endBuf = SM->getCharacterData(LocEnd);
796 for (const char *p = startBuf; p < endBuf; p++) {
797 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
798 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000799 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000800 ReplaceText(OptionalLoc, strlen("@optional"),
801 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000802
803 }
804 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
805 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000806 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000807 ReplaceText(OptionalLoc, strlen("@required"),
808 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000809
810 }
811 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000812}
813
Steve Naroffb29b4272008-04-14 22:03:09 +0000814void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000815 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000816 if (LocStart.isInvalid())
817 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000818 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000819 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000820}
821
Steve Naroffb29b4272008-04-14 22:03:09 +0000822void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000823 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000824 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000825 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000826 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000827 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000828 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000829 else if (OMD->getResultType()->isFunctionPointerType()) {
830 // needs special handling, since pointer-to-functions have special
831 // syntax (where a decaration models use).
832 QualType retType = OMD->getResultType();
833 if (const PointerType* PT = retType->getAsPointerType()) {
834 QualType PointeeTy = PT->getPointeeType();
835 if ((FPRetType = PointeeTy->getAsFunctionType())) {
836 ResultStr += FPRetType->getResultType().getAsString();
837 ResultStr += "(*";
838 }
839 }
840 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000841 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000842 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000843
844 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000845 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000846
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000847 if (OMD->isInstance())
848 NameStr += "_I_";
849 else
850 NameStr += "_C_";
851
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000852 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000853 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000854
855 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000856 if (ObjCCategoryImplDecl *CID =
857 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000858 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000859 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000860 }
Steve Naroff563b8282008-04-04 22:23:44 +0000861 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000862 {
863 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000864 int len = selString.size();
865 for (int i = 0; i < len; i++)
866 if (selString[i] == ':')
867 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000868 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000869 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000870 // Remember this name for metadata emission
871 MethodInternalNames[OMD] = NameStr;
872 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000873
874 // Rewrite arguments
875 ResultStr += "(";
876
877 // invisible arguments
878 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000879 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000880 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000881 if (!LangOpts.Microsoft) {
882 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
883 ResultStr += "struct ";
884 }
885 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000886 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000887 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000888 }
889 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000890 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000891
892 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000893 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000894 ResultStr += " _cmd";
895
896 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000897 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000898 ParmVarDecl *PDecl = OMD->getParamDecl(i);
899 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000900 if (PDecl->getType()->isObjCQualifiedIdType()) {
901 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000902 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000903 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000904 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000905 if (isBlockPointerType(PDecl->getType())) {
906 // Make sure we convert "t (^)(...)" to "t (*)(...)".
907 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
908 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
909 } else
910 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000911 ResultStr += Name;
912 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000913 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000914 if (OMD->isVariadic())
915 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000916 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000917
Steve Naroff76e429d2008-07-16 14:40:40 +0000918 if (FPRetType) {
919 ResultStr += ")"; // close the precedence "scope" for "*".
920
921 // Now, emit the argument types (if any).
922 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
923 ResultStr += "(";
924 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
925 if (i) ResultStr += ", ";
926 std::string ParamStr = FT->getArgType(i).getAsString();
927 ResultStr += ParamStr;
928 }
929 if (FT->isVariadic()) {
930 if (FT->getNumArgs()) ResultStr += ", ";
931 ResultStr += "...";
932 }
933 ResultStr += ")";
934 } else {
935 ResultStr += "()";
936 }
937 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000938}
Steve Naroffb29b4272008-04-14 22:03:09 +0000939void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000940 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
941 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000942
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000943 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000944 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000945 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000946 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000947
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000948 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000949 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
950 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000951 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000952 ObjCMethodDecl *OMD = *I;
953 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000954 SourceLocation LocStart = OMD->getLocStart();
955 SourceLocation LocEnd = OMD->getBody()->getLocStart();
956
957 const char *startBuf = SM->getCharacterData(LocStart);
958 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000959 ReplaceText(LocStart, endBuf-startBuf,
960 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000961 }
962
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000963 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000964 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
965 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000966 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000967 ObjCMethodDecl *OMD = *I;
968 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000969 SourceLocation LocStart = OMD->getLocStart();
970 SourceLocation LocEnd = OMD->getBody()->getLocStart();
971
972 const char *startBuf = SM->getCharacterData(LocStart);
973 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000974 ReplaceText(LocStart, endBuf-startBuf,
975 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000976 }
Steve Naroffd40910b2008-12-01 20:33:01 +0000977 for (ObjCCategoryImplDecl::propimpl_iterator
978 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
979 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +0000980 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +0000981 }
982
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000983 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000984 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000985 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000986 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000987}
988
Steve Naroffb29b4272008-04-14 22:03:09 +0000989void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000990 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000991 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000992 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000993 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000994 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000995 ResultStr += "\n";
996 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000997 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000998 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000999 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001000 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001001 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001002 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001003 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001004 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001006
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001007 RewriteProperties(ClassDecl->getNumPropertyDecl(),
1008 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001009 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001010 E = ClassDecl->instmeth_end(); I != E; ++I)
1011 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001012 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001013 E = ClassDecl->classmeth_end(); I != E; ++I)
1014 RewriteMethodDeclaration(*I);
1015
Steve Naroff2feac5e2007-10-30 03:43:13 +00001016 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001017 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001018}
1019
Steve Naroffc77a6362008-12-04 16:24:46 +00001020Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt) {
1021 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1022 // This allows us to reuse all the fun and games in SynthMessageExpr().
1023 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1024 ObjCMessageExpr *MsgExpr;
1025 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1026 llvm::SmallVector<Expr *, 1> ExprVec;
1027 ExprVec.push_back(newStmt);
1028
Steve Naroff8599e7a2008-12-08 16:43:47 +00001029 Stmt *Receiver = PropRefExpr->getBase();
1030 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1031 if (PRE && PropGetters[PRE]) {
1032 // This allows us to handle chain/nested property getters.
1033 Receiver = PropGetters[PRE];
1034 }
1035 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001036 PDecl->getSetterName(), PDecl->getType(),
1037 PDecl->getSetterMethodDecl(),
1038 SourceLocation(), SourceLocation(),
1039 &ExprVec[0], 1);
1040 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1041
1042 // Now do the actual rewrite.
1043 ReplaceStmt(BinOp, ReplacingStmt);
1044 delete BinOp;
1045 delete MsgExpr;
1046 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001047}
1048
Steve Naroffc77a6362008-12-04 16:24:46 +00001049Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001050 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1051 // This allows us to reuse all the fun and games in SynthMessageExpr().
1052 ObjCMessageExpr *MsgExpr;
1053 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1054
Steve Naroff8599e7a2008-12-08 16:43:47 +00001055 Stmt *Receiver = PropRefExpr->getBase();
1056
1057 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1058 if (PRE && PropGetters[PRE]) {
1059 // This allows us to handle chain/nested property getters.
1060 Receiver = PropGetters[PRE];
1061 }
1062 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001063 PDecl->getGetterName(), PDecl->getType(),
1064 PDecl->getGetterMethodDecl(),
1065 SourceLocation(), SourceLocation(),
1066 0, 0);
1067
Steve Naroff4c3580e2008-12-04 23:50:32 +00001068 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001069
1070 if (!PropParentMap)
1071 PropParentMap = new ParentMap(CurrentBody);
1072
1073 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1074 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1075 // We stash away the ReplacingStmt since actually doing the
1076 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1077 PropGetters[PropRefExpr] = ReplacingStmt;
1078 delete MsgExpr;
1079 return PropRefExpr; // return the original...
1080 } else {
1081 ReplaceStmt(PropRefExpr, ReplacingStmt);
1082 // delete PropRefExpr; elsewhere...
1083 delete MsgExpr;
1084 return ReplacingStmt;
1085 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001086}
1087
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001088Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1089 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001090 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001091 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001092 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001093 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1094 // lookup which class implements the instance variable.
1095 ObjCInterfaceDecl *clsDeclared = 0;
1096 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1097 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1098
1099 // Synthesize an explicit cast to gain access to the ivar.
1100 std::string RecName = clsDeclared->getIdentifier()->getName();
1101 RecName += "_IMPL";
1102 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001103 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001104 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001105 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1106 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001107 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001108 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001109 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001110 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1111 IV->getBase()->getLocEnd(),
1112 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001113 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001114 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001115 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1116 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001117 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001118 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001119 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001120 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001121
1122 ReplaceStmt(IV->getBase(), PE);
1123 // Cannot delete IV->getBase(), since PE points to it.
1124 // Replace the old base with the cast. This is important when doing
1125 // embedded rewrites. For example, [newInv->_container addObject:0].
1126 IV->setBase(PE);
1127 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001128 }
Steve Naroff84472a82008-04-18 21:55:08 +00001129 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001130 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1131
1132 // Explicit ivar refs need to have a cast inserted.
1133 // FIXME: consider sharing some of this code with the code above.
1134 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001135 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001136 // lookup which class implements the instance variable.
1137 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001138 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001139 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1140
1141 // Synthesize an explicit cast to gain access to the ivar.
1142 std::string RecName = clsDeclared->getIdentifier()->getName();
1143 RecName += "_IMPL";
1144 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001145 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001146 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001147 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1148 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001149 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001150 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001151 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001152 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1153 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001154 ReplaceStmt(IV->getBase(), PE);
1155 // Cannot delete IV->getBase(), since PE points to it.
1156 // Replace the old base with the cast. This is important when doing
1157 // embedded rewrites. For example, [newInv->_container addObject:0].
1158 IV->setBase(PE);
1159 return IV;
1160 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001161 }
Steve Naroff84472a82008-04-18 21:55:08 +00001162 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001163}
1164
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001165/// SynthCountByEnumWithState - To print:
1166/// ((unsigned int (*)
1167/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1168/// (void *)objc_msgSend)((id)l_collection,
1169/// sel_registerName(
1170/// "countByEnumeratingWithState:objects:count:"),
1171/// &enumState,
1172/// (id *)items, (unsigned int)16)
1173///
Steve Naroffb29b4272008-04-14 22:03:09 +00001174void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001175 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1176 "id *, unsigned int))(void *)objc_msgSend)";
1177 buf += "\n\t\t";
1178 buf += "((id)l_collection,\n\t\t";
1179 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1180 buf += "\n\t\t";
1181 buf += "&enumState, "
1182 "(id *)items, (unsigned int)16)";
1183}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001184
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001185/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1186/// statement to exit to its outer synthesized loop.
1187///
Steve Naroffb29b4272008-04-14 22:03:09 +00001188Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001189 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1190 return S;
1191 // replace break with goto __break_label
1192 std::string buf;
1193
1194 SourceLocation startLoc = S->getLocStart();
1195 buf = "goto __break_label_";
1196 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001197 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001198
1199 return 0;
1200}
1201
1202/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1203/// statement to continue with its inner synthesized loop.
1204///
Steve Naroffb29b4272008-04-14 22:03:09 +00001205Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001206 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1207 return S;
1208 // replace continue with goto __continue_label
1209 std::string buf;
1210
1211 SourceLocation startLoc = S->getLocStart();
1212 buf = "goto __continue_label_";
1213 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001214 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001215
1216 return 0;
1217}
1218
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001219/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001220/// It rewrites:
1221/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001222
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001223/// Into:
1224/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001225/// type elem;
1226/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001227/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001228/// id l_collection = (id)collection;
1229/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1230/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001231/// if (limit) {
1232/// unsigned long startMutations = *enumState.mutationsPtr;
1233/// do {
1234/// unsigned long counter = 0;
1235/// do {
1236/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001237/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001238/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001239/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001240/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001241/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001242/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1243/// objects:items count:16]);
1244/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001245/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001246/// }
1247/// else
1248/// elem = nil;
1249/// }
1250///
Steve Naroffb29b4272008-04-14 22:03:09 +00001251Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001252 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001253 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1254 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1255 "ObjCForCollectionStmt Statement stack mismatch");
1256 assert(!ObjCBcLabelNo.empty() &&
1257 "ObjCForCollectionStmt - Label No stack empty");
1258
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001259 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001260 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001261 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001262 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001263 std::string buf;
1264 buf = "\n{\n\t";
1265 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1266 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001267 ScopedDecl* D = DS->getSolitaryDecl();
1268 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001269 elementTypeAsString = ElementType.getAsString();
1270 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001271 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001272 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001273 buf += elementName;
1274 buf += ";\n\t";
1275 }
Chris Lattner06767512008-04-08 05:52:18 +00001276 else {
1277 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001278 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001279 elementTypeAsString
1280 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001281 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001282
1283 // struct __objcFastEnumerationState enumState = { 0 };
1284 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1285 // id items[16];
1286 buf += "id items[16];\n\t";
1287 // id l_collection = (id)
1288 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001289 // Find start location of 'collection' the hard way!
1290 const char *startCollectionBuf = startBuf;
1291 startCollectionBuf += 3; // skip 'for'
1292 startCollectionBuf = strchr(startCollectionBuf, '(');
1293 startCollectionBuf++; // skip '('
1294 // find 'in' and skip it.
1295 while (*startCollectionBuf != ' ' ||
1296 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1297 (*(startCollectionBuf+3) != ' ' &&
1298 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1299 startCollectionBuf++;
1300 startCollectionBuf += 3;
1301
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001302 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001303 ReplaceText(startLoc, startCollectionBuf - startBuf,
1304 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001305 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001306 SourceLocation rightParenLoc = S->getRParenLoc();
1307 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1308 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001309 buf = ";\n\t";
1310
1311 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1312 // objects:items count:16];
1313 // which is synthesized into:
1314 // unsigned int limit =
1315 // ((unsigned int (*)
1316 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1317 // (void *)objc_msgSend)((id)l_collection,
1318 // sel_registerName(
1319 // "countByEnumeratingWithState:objects:count:"),
1320 // (struct __objcFastEnumerationState *)&state,
1321 // (id *)items, (unsigned int)16);
1322 buf += "unsigned long limit =\n\t\t";
1323 SynthCountByEnumWithState(buf);
1324 buf += ";\n\t";
1325 /// if (limit) {
1326 /// unsigned long startMutations = *enumState.mutationsPtr;
1327 /// do {
1328 /// unsigned long counter = 0;
1329 /// do {
1330 /// if (startMutations != *enumState.mutationsPtr)
1331 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001332 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001333 buf += "if (limit) {\n\t";
1334 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1335 buf += "do {\n\t\t";
1336 buf += "unsigned long counter = 0;\n\t\t";
1337 buf += "do {\n\t\t\t";
1338 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1339 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1340 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001341 buf += " = (";
1342 buf += elementTypeAsString;
1343 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001344 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001345 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001346
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001347 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001348 /// } while (counter < limit);
1349 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1350 /// objects:items count:16]);
1351 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001352 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001353 /// }
1354 /// else
1355 /// elem = nil;
1356 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001357 ///
1358 buf = ";\n\t";
1359 buf += "__continue_label_";
1360 buf += utostr(ObjCBcLabelNo.back());
1361 buf += ": ;";
1362 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001363 buf += "} while (counter < limit);\n\t";
1364 buf += "} while (limit = ";
1365 SynthCountByEnumWithState(buf);
1366 buf += ");\n\t";
1367 buf += elementName;
1368 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001369 buf += "__break_label_";
1370 buf += utostr(ObjCBcLabelNo.back());
1371 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001372 buf += "}\n\t";
1373 buf += "else\n\t\t";
1374 buf += elementName;
1375 buf += " = nil;\n";
1376 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001377
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001378 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001379 if (isa<CompoundStmt>(S->getBody())) {
1380 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1381 InsertText(endBodyLoc, buf.c_str(), buf.size());
1382 } else {
1383 /* Need to treat single statements specially. For example:
1384 *
1385 * for (A *a in b) if (stuff()) break;
1386 * for (A *a in b) xxxyy;
1387 *
1388 * The following code simply scans ahead to the semi to find the actual end.
1389 */
1390 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1391 const char *semiBuf = strchr(stmtBuf, ';');
1392 assert(semiBuf && "Can't find ';'");
1393 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1394 InsertText(endBodyLoc, buf.c_str(), buf.size());
1395 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001396 Stmts.pop_back();
1397 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001398 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001399}
1400
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001401/// RewriteObjCSynchronizedStmt -
1402/// This routine rewrites @synchronized(expr) stmt;
1403/// into:
1404/// objc_sync_enter(expr);
1405/// @try stmt @finally { objc_sync_exit(expr); }
1406///
Steve Naroffb29b4272008-04-14 22:03:09 +00001407Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001408 // Get the start location and compute the semi location.
1409 SourceLocation startLoc = S->getLocStart();
1410 const char *startBuf = SM->getCharacterData(startLoc);
1411
1412 assert((*startBuf == '@') && "bogus @synchronized location");
1413
1414 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001415 buf = "objc_sync_enter((id)";
1416 const char *lparenBuf = startBuf;
1417 while (*lparenBuf != '(') lparenBuf++;
1418 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001419 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1420 // the sync expression is typically a message expression that's already
1421 // been rewritten! (which implies the SourceLocation's are invalid).
1422 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001423 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001424 while (*endBuf != ')') endBuf--;
1425 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001426 buf = ");\n";
1427 // declare a new scope with two variables, _stack and _rethrow.
1428 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1429 buf += "int buf[18/*32-bit i386*/];\n";
1430 buf += "char *pointers[4];} _stack;\n";
1431 buf += "id volatile _rethrow = 0;\n";
1432 buf += "objc_exception_try_enter(&_stack);\n";
1433 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001434 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001435 startLoc = S->getSynchBody()->getLocEnd();
1436 startBuf = SM->getCharacterData(startLoc);
1437
Steve Naroffc7089f12008-08-19 13:04:19 +00001438 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001439 SourceLocation lastCurlyLoc = startLoc;
1440 buf = "}\nelse {\n";
1441 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1442 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001443 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001444 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001445 S->getSynchExpr(),
1446 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001447 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001448 std::string syncExprBufS;
1449 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001450 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001451 buf += syncExprBuf.str();
1452 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001453 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1454 buf += "}\n";
1455 buf += "}";
1456
Chris Lattneraadaf782008-01-31 19:51:04 +00001457 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001458 return 0;
1459}
1460
Steve Naroff8c565152008-12-05 17:03:39 +00001461void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1462 // Perform a bottom up traversal of all children.
1463 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1464 CI != E; ++CI)
1465 if (*CI)
1466 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1467
1468 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1469 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1470 Diags.Report(Context->getFullLoc(S->getLocStart()),
1471 TryFinallyContainsReturnDiag);
1472 }
1473 return;
1474}
1475
Steve Naroffb29b4272008-04-14 22:03:09 +00001476Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001477 // Get the start location and compute the semi location.
1478 SourceLocation startLoc = S->getLocStart();
1479 const char *startBuf = SM->getCharacterData(startLoc);
1480
1481 assert((*startBuf == '@') && "bogus @try location");
1482
1483 std::string buf;
1484 // declare a new scope with two variables, _stack and _rethrow.
1485 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1486 buf += "int buf[18/*32-bit i386*/];\n";
1487 buf += "char *pointers[4];} _stack;\n";
1488 buf += "id volatile _rethrow = 0;\n";
1489 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001490 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001491
Chris Lattneraadaf782008-01-31 19:51:04 +00001492 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001493
1494 startLoc = S->getTryBody()->getLocEnd();
1495 startBuf = SM->getCharacterData(startLoc);
1496
1497 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001498
Steve Naroff75730982007-11-07 04:08:17 +00001499 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001500 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1501 if (catchList) {
1502 startLoc = startLoc.getFileLocWithOffset(1);
1503 buf = " /* @catch begin */ else {\n";
1504 buf += " id _caught = objc_exception_extract(&_stack);\n";
1505 buf += " objc_exception_try_enter (&_stack);\n";
1506 buf += " if (_setjmp(_stack.buf))\n";
1507 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1508 buf += " else { /* @catch continue */";
1509
1510 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001511 } else { /* no catch list */
1512 buf = "}\nelse {\n";
1513 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1514 buf += "}";
1515 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001516 }
Steve Naroff75730982007-11-07 04:08:17 +00001517 bool sawIdTypedCatch = false;
1518 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001519 while (catchList) {
1520 Stmt *catchStmt = catchList->getCatchParamStmt();
1521
1522 if (catchList == S->getCatchStmts())
1523 buf = "if ("; // we are generating code for the first catch clause
1524 else
1525 buf = "else if (";
1526 startLoc = catchList->getLocStart();
1527 startBuf = SM->getCharacterData(startLoc);
1528
1529 assert((*startBuf == '@') && "bogus @catch location");
1530
1531 const char *lParenLoc = strchr(startBuf, '(');
1532
Steve Naroffbe4b3332008-02-01 22:08:12 +00001533 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001534 // Now rewrite the body...
1535 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001536 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1537 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001538 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1539 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001540 assert((*bodyBuf == '{') && "bogus @catch body location");
1541
1542 buf += "1) { id _tmp = _caught;";
1543 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1544 buf.c_str(), buf.size());
1545 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001546 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001547 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001548 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001549 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001550 sawIdTypedCatch = true;
1551 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001552 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001553
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001554 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001555 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001556 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001557 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001558 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001559 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001560 }
1561 }
1562 // Now rewrite the body...
1563 lastCatchBody = catchList->getCatchBody();
1564 SourceLocation rParenLoc = catchList->getRParenLoc();
1565 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1566 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1567 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1568 assert((*rParenBuf == ')') && "bogus @catch paren location");
1569 assert((*bodyBuf == '{') && "bogus @catch body location");
1570
1571 buf = " = _caught;";
1572 // Here we replace ") {" with "= _caught;" (which initializes and
1573 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001574 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001575 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001576 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001577 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001578 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001579 catchList = catchList->getNextCatchStmt();
1580 }
1581 // Complete the catch list...
1582 if (lastCatchBody) {
1583 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001584 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1585 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001586
Steve Naroff378f47a2008-09-11 15:29:03 +00001587 // Insert the last (implicit) else clause *before* the right curly brace.
1588 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1589 buf = "} /* last catch end */\n";
1590 buf += "else {\n";
1591 buf += " _rethrow = _caught;\n";
1592 buf += " objc_exception_try_exit(&_stack);\n";
1593 buf += "} } /* @catch end */\n";
1594 if (!S->getFinallyStmt())
1595 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001596 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001597
1598 // Set lastCurlyLoc
1599 lastCurlyLoc = lastCatchBody->getLocEnd();
1600 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001601 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001602 startLoc = finalStmt->getLocStart();
1603 startBuf = SM->getCharacterData(startLoc);
1604 assert((*startBuf == '@') && "bogus @finally start");
1605
1606 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001607 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001608
1609 Stmt *body = finalStmt->getFinallyBody();
1610 SourceLocation startLoc = body->getLocStart();
1611 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001612 assert(*SM->getCharacterData(startLoc) == '{' &&
1613 "bogus @finally body location");
1614 assert(*SM->getCharacterData(endLoc) == '}' &&
1615 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001616
1617 startLoc = startLoc.getFileLocWithOffset(1);
1618 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001619 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001620 endLoc = endLoc.getFileLocWithOffset(-1);
1621 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001622 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001623
1624 // Set lastCurlyLoc
1625 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001626
1627 // Now check for any return/continue/go statements within the @try.
1628 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001629 } else { /* no finally clause - make sure we synthesize an implicit one */
1630 buf = "{ /* implicit finally clause */\n";
1631 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1632 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1633 buf += "}";
1634 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001635 }
1636 // Now emit the final closing curly brace...
1637 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1638 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001639 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001640 return 0;
1641}
1642
Steve Naroffb29b4272008-04-14 22:03:09 +00001643Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001644 return 0;
1645}
1646
Steve Naroffb29b4272008-04-14 22:03:09 +00001647Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001648 return 0;
1649}
1650
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001651// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001652// the throw expression is typically a message expression that's already
1653// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001654Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001655 // Get the start location and compute the semi location.
1656 SourceLocation startLoc = S->getLocStart();
1657 const char *startBuf = SM->getCharacterData(startLoc);
1658
1659 assert((*startBuf == '@') && "bogus @throw location");
1660
1661 std::string buf;
1662 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001663 if (S->getThrowExpr())
1664 buf = "objc_exception_throw(";
1665 else // add an implicit argument
1666 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001667
1668 // handle "@ throw" correctly.
1669 const char *wBuf = strchr(startBuf, 'w');
1670 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1671 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1672
Steve Naroff2bd03922007-11-07 15:32:26 +00001673 const char *semiBuf = strchr(startBuf, ';');
1674 assert((*semiBuf == ';') && "@throw: can't find ';'");
1675 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1676 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001677 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001678 return 0;
1679}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001680
Steve Naroffb29b4272008-04-14 22:03:09 +00001681Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001682 // Create a new string expression.
1683 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001684 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001685 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001686 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1687 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001688 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001689 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001690
Chris Lattner07506182007-11-30 22:53:43 +00001691 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001692 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001693 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001694}
1695
Steve Naroffb29b4272008-04-14 22:03:09 +00001696Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001697 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1698 // Create a call to sel_registerName("selName").
1699 llvm::SmallVector<Expr*, 8> SelExprs;
1700 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001701 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1702 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001703 false, argType, SourceLocation(),
1704 SourceLocation()));
1705 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1706 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001707 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001708 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001709 return SelExp;
1710}
1711
Steve Naroffb29b4272008-04-14 22:03:09 +00001712CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001713 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001714 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001715 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001716
1717 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001718 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001719
1720 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001721 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001722 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1723 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001724
1725 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001726
Steve Naroff934f2762007-10-24 22:48:43 +00001727 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1728}
1729
Steve Naroffd5255f52007-11-01 13:24:47 +00001730static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1731 const char *&startRef, const char *&endRef) {
1732 while (startBuf < endBuf) {
1733 if (*startBuf == '<')
1734 startRef = startBuf; // mark the start.
1735 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001736 if (startRef && *startRef == '<') {
1737 endRef = startBuf; // mark the end.
1738 return true;
1739 }
1740 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001741 }
1742 startBuf++;
1743 }
1744 return false;
1745}
1746
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001747static void scanToNextArgument(const char *&argRef) {
1748 int angle = 0;
1749 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1750 if (*argRef == '<')
1751 angle++;
1752 else if (*argRef == '>')
1753 angle--;
1754 argRef++;
1755 }
1756 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1757}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001758
Steve Naroffb29b4272008-04-14 22:03:09 +00001759bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001760
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001761 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001762 return true;
1763
Steve Naroffd5255f52007-11-01 13:24:47 +00001764 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001765 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001766 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001767 return true; // we have "Class <Protocol> *".
1768 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001769 return false;
1770}
1771
Steve Naroff4f95b752008-07-29 18:15:38 +00001772void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1773 QualType Type = E->getType();
1774 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001775 SourceLocation Loc, EndLoc;
1776
1777 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1778 Loc = ECE->getLParenLoc();
1779 EndLoc = ECE->getRParenLoc();
1780 } else {
1781 Loc = E->getLocStart();
1782 EndLoc = E->getLocEnd();
1783 }
1784 // This will defend against trying to rewrite synthesized expressions.
1785 if (Loc.isInvalid() || EndLoc.isInvalid())
1786 return;
1787
Steve Naroff4f95b752008-07-29 18:15:38 +00001788 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001789 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001790 const char *startRef = 0, *endRef = 0;
1791 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1792 // Get the locations of the startRef, endRef.
1793 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1794 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1795 // Comment out the protocol references.
1796 InsertText(LessLoc, "/*", 2);
1797 InsertText(GreaterLoc, "*/", 2);
1798 }
1799 }
1800}
1801
Steve Naroffb29b4272008-04-14 22:03:09 +00001802void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001803 SourceLocation Loc;
1804 QualType Type;
1805 const FunctionTypeProto *proto = 0;
1806 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1807 Loc = VD->getLocation();
1808 Type = VD->getType();
1809 }
1810 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1811 Loc = FD->getLocation();
1812 // Check for ObjC 'id' and class types that have been adorned with protocol
1813 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1814 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1815 assert(funcType && "missing function type");
1816 proto = dyn_cast<FunctionTypeProto>(funcType);
1817 if (!proto)
1818 return;
1819 Type = proto->getResultType();
1820 }
1821 else
1822 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001823
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001824 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001825 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001826
1827 const char *endBuf = SM->getCharacterData(Loc);
1828 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001829 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001830 startBuf--; // scan backward (from the decl location) for return type.
1831 const char *startRef = 0, *endRef = 0;
1832 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1833 // Get the locations of the startRef, endRef.
1834 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1835 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1836 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001837 InsertText(LessLoc, "/*", 2);
1838 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001839 }
1840 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001841 if (!proto)
1842 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001843 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001844 const char *startBuf = SM->getCharacterData(Loc);
1845 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001846 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1847 if (needToScanForQualifiers(proto->getArgType(i))) {
1848 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001849
Steve Naroffd5255f52007-11-01 13:24:47 +00001850 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001851 // scan forward (from the decl location) for argument types.
1852 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001853 const char *startRef = 0, *endRef = 0;
1854 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1855 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001856 SourceLocation LessLoc =
1857 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1858 SourceLocation GreaterLoc =
1859 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001860 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001861 InsertText(LessLoc, "/*", 2);
1862 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001863 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001864 startBuf = ++endBuf;
1865 }
1866 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001867 // If the function name is derived from a macro expansion, then the
1868 // argument buffer will not follow the name. Need to speak with Chris.
1869 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001870 startBuf++; // scan forward (from the decl location) for argument types.
1871 startBuf++;
1872 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001873 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001874}
1875
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001876// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001877void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001878 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1879 llvm::SmallVector<QualType, 16> ArgTys;
1880 ArgTys.push_back(Context->getPointerType(
1881 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001882 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001883 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001884 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001885 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001886 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001887 SelGetUidIdent, getFuncType,
1888 FunctionDecl::Extern, false, 0);
1889}
1890
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001891// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001892void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001893 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1894 llvm::SmallVector<QualType, 16> ArgTys;
1895 ArgTys.push_back(Context->getPointerType(
1896 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001897 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001898 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001899 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001900 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001901 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001902 SelGetProtoIdent, getFuncType,
1903 FunctionDecl::Extern, false, 0);
1904}
1905
Steve Naroffb29b4272008-04-14 22:03:09 +00001906void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001907 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001908 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001909 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001910 return;
1911 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001912 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001913}
1914
Steve Naroffc0a123c2008-03-11 17:37:02 +00001915// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001916void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001917 if (SuperContructorFunctionDecl)
1918 return;
1919 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1920 llvm::SmallVector<QualType, 16> ArgTys;
1921 QualType argT = Context->getObjCIdType();
1922 assert(!argT.isNull() && "Can't find 'id' type");
1923 ArgTys.push_back(argT);
1924 ArgTys.push_back(argT);
1925 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1926 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001927 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001928 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001929 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001930 msgSendIdent, msgSendType,
1931 FunctionDecl::Extern, false, 0);
1932}
1933
Steve Naroff09b266e2007-10-30 23:14:51 +00001934// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001935void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001936 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1937 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001938 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001939 assert(!argT.isNull() && "Can't find 'id' type");
1940 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001941 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001942 assert(!argT.isNull() && "Can't find 'SEL' type");
1943 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001944 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001945 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001946 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001947 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001948 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001949 msgSendIdent, msgSendType,
1950 FunctionDecl::Extern, false, 0);
1951}
1952
Steve Naroff874e2322007-11-15 10:28:18 +00001953// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001954void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001955 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1956 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001957 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001958 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001959 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001960 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1961 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1962 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001963 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001964 assert(!argT.isNull() && "Can't find 'SEL' type");
1965 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001966 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001967 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001968 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001969 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001970 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001971 msgSendIdent, msgSendType,
1972 FunctionDecl::Extern, false, 0);
1973}
1974
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001975// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001976void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001977 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1978 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001979 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001980 assert(!argT.isNull() && "Can't find 'id' type");
1981 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001982 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001983 assert(!argT.isNull() && "Can't find 'SEL' type");
1984 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001985 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001986 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001987 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001988 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001989 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001990 msgSendIdent, msgSendType,
1991 FunctionDecl::Extern, false, 0);
1992}
1993
1994// SynthMsgSendSuperStretFunctionDecl -
1995// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001996void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001997 IdentifierInfo *msgSendIdent =
1998 &Context->Idents.get("objc_msgSendSuper_stret");
1999 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002000 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002001 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002002 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002003 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2004 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2005 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002006 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002007 assert(!argT.isNull() && "Can't find 'SEL' type");
2008 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002009 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002010 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002011 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002012 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002013 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002014 msgSendIdent, msgSendType,
2015 FunctionDecl::Extern, false, 0);
2016}
2017
Steve Naroff1284db82008-05-08 22:02:18 +00002018// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002019void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002020 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2021 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002022 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002023 assert(!argT.isNull() && "Can't find 'id' type");
2024 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002025 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002026 assert(!argT.isNull() && "Can't find 'SEL' type");
2027 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002028 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002029 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002030 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002031 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002032 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002033 msgSendIdent, msgSendType,
2034 FunctionDecl::Extern, false, 0);
2035}
2036
Steve Naroff09b266e2007-10-30 23:14:51 +00002037// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002038void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002039 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2040 llvm::SmallVector<QualType, 16> ArgTys;
2041 ArgTys.push_back(Context->getPointerType(
2042 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002043 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002044 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002045 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002046 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002047 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002048 getClassIdent, getClassType,
2049 FunctionDecl::Extern, false, 0);
2050}
2051
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002052// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002053void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002054 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2055 llvm::SmallVector<QualType, 16> ArgTys;
2056 ArgTys.push_back(Context->getPointerType(
2057 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002058 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002059 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002060 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002061 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002062 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002063 getClassIdent, getClassType,
2064 FunctionDecl::Extern, false, 0);
2065}
2066
Steve Naroffb29b4272008-04-14 22:03:09 +00002067Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002068 QualType strType = getConstantStringStructType();
2069
2070 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002071
2072 std::string tmpName = InFileName;
2073 unsigned i;
2074 for (i=0; i < tmpName.length(); i++) {
2075 char c = tmpName.at(i);
2076 // replace any non alphanumeric characters with '_'.
2077 if (!isalpha(c) && (c < '0' || c > '9'))
2078 tmpName[i] = '_';
2079 }
2080 S += tmpName;
2081 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002082 S += utostr(NumObjCStringLiterals++);
2083
Steve Naroffba92b2e2008-03-27 22:29:16 +00002084 Preamble += "static __NSConstantStringImpl " + S;
2085 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2086 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002087 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002088 std::string prettyBufS;
2089 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002090 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002091 Preamble += prettyBuf.str();
2092 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002093 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002094 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002095
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002096 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002097 &Context->Idents.get(S.c_str()), strType,
2098 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002099 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2100 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2101 Context->getPointerType(DRE->getType()),
2102 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002103 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002104 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002105 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002106 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002107 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002108 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002109}
2110
Steve Naroffb29b4272008-04-14 22:03:09 +00002111ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002112 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002113 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002114
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002115 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2116 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002117 assert(PT);
2118 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2119 return IT->getDecl();
2120 }
2121 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002122}
2123
2124// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002125QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002126 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002127 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002128 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002129 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002130 QualType FieldTypes[2];
2131
2132 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002133 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002134 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002135 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002136 // Create fields
2137 FieldDecl *FieldDecls[2];
2138
2139 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002140 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002141 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002142
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002143 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002144 }
2145 return Context->getTagDeclType(SuperStructDecl);
2146}
2147
Steve Naroffb29b4272008-04-14 22:03:09 +00002148QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002149 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002150 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002151 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002152 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002153 QualType FieldTypes[4];
2154
2155 // struct objc_object *receiver;
2156 FieldTypes[0] = Context->getObjCIdType();
2157 // int flags;
2158 FieldTypes[1] = Context->IntTy;
2159 // char *str;
2160 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2161 // long length;
2162 FieldTypes[3] = Context->LongTy;
2163 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002164 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002165
2166 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002167 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002168 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002169
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002170 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002171 }
2172 return Context->getTagDeclType(ConstantStringDecl);
2173}
2174
Steve Naroffb29b4272008-04-14 22:03:09 +00002175Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002176 if (!SelGetUidFunctionDecl)
2177 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002178 if (!MsgSendFunctionDecl)
2179 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002180 if (!MsgSendSuperFunctionDecl)
2181 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002182 if (!MsgSendStretFunctionDecl)
2183 SynthMsgSendStretFunctionDecl();
2184 if (!MsgSendSuperStretFunctionDecl)
2185 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002186 if (!MsgSendFpretFunctionDecl)
2187 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002188 if (!GetClassFunctionDecl)
2189 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002190 if (!GetMetaClassFunctionDecl)
2191 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002192
Steve Naroff874e2322007-11-15 10:28:18 +00002193 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002194 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2195 // May need to use objc_msgSend_stret() as well.
2196 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002197 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002198 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002199 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002200 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002201 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002202 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002203 }
Steve Naroff874e2322007-11-15 10:28:18 +00002204
Steve Naroff934f2762007-10-24 22:48:43 +00002205 // Synthesize a call to objc_msgSend().
2206 llvm::SmallVector<Expr*, 8> MsgExprs;
2207 IdentifierInfo *clsName = Exp->getClassName();
2208
2209 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2210 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002211 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2212 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002213 if (!strcmp(clsName->getName(), "super")) {
2214 MsgSendFlavor = MsgSendSuperFunctionDecl;
2215 if (MsgSendStretFlavor)
2216 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2217 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2218
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002219 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002220 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002221
2222 llvm::SmallVector<Expr*, 4> InitExprs;
2223
2224 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002225 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002226 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002227 Context->getObjCIdType(),
2228 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002229 llvm::SmallVector<Expr*, 8> ClsExprs;
2230 QualType argType = Context->getPointerType(Context->CharTy);
2231 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2232 SuperDecl->getIdentifier()->getLength(),
2233 false, argType, SourceLocation(),
2234 SourceLocation()));
2235 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2236 &ClsExprs[0],
2237 ClsExprs.size());
2238 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002239 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002240 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002241 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002242 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002243 // struct objc_super
2244 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002245 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002246
Steve Naroff23f41272008-03-11 18:14:26 +00002247 if (LangOpts.Microsoft) {
2248 SynthSuperContructorFunctionDecl();
2249 // Simulate a contructor call...
2250 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2251 superType, SourceLocation());
2252 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2253 superType, SourceLocation());
2254 } else {
2255 // (struct objc_super) { <exprs from above> }
2256 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2257 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002258 SourceLocation(), false);
2259 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2260 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002261 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002262 // struct objc_super *
2263 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2264 Context->getPointerType(SuperRep->getType()),
2265 SourceLocation());
2266 MsgExprs.push_back(Unop);
2267 } else {
2268 llvm::SmallVector<Expr*, 8> ClsExprs;
2269 QualType argType = Context->getPointerType(Context->CharTy);
2270 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2271 clsName->getLength(),
2272 false, argType, SourceLocation(),
2273 SourceLocation()));
2274 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2275 &ClsExprs[0],
2276 ClsExprs.size());
2277 MsgExprs.push_back(Cls);
2278 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002279 } else { // instance message.
2280 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002281
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002282 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002283 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002284 if (MsgSendStretFlavor)
2285 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002286 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2287
2288 llvm::SmallVector<Expr*, 4> InitExprs;
2289
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002290 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002291 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002292 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002293 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002294 SourceLocation()),
2295 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002296 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002297
2298 llvm::SmallVector<Expr*, 8> ClsExprs;
2299 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002300 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2301 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002302 false, argType, SourceLocation(),
2303 SourceLocation()));
2304 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002305 &ClsExprs[0],
2306 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002307 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002308 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002309 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002310 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002311 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002312 // struct objc_super
2313 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002314 Expr *SuperRep;
2315
2316 if (LangOpts.Microsoft) {
2317 SynthSuperContructorFunctionDecl();
2318 // Simulate a contructor call...
2319 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2320 superType, SourceLocation());
2321 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2322 superType, SourceLocation());
2323 } else {
2324 // (struct objc_super) { <exprs from above> }
2325 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2326 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002327 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002328 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2329 }
Steve Naroff874e2322007-11-15 10:28:18 +00002330 // struct objc_super *
2331 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2332 Context->getPointerType(SuperRep->getType()),
2333 SourceLocation());
2334 MsgExprs.push_back(Unop);
2335 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002336 // Remove all type-casts because it may contain objc-style types; e.g.
2337 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002338 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002339 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002340 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002341 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002342 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002343 MsgExprs.push_back(recExpr);
2344 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002345 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002346 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002347 llvm::SmallVector<Expr*, 8> SelExprs;
2348 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002349 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2350 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002351 false, argType, SourceLocation(),
2352 SourceLocation()));
2353 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2354 &SelExprs[0], SelExprs.size());
2355 MsgExprs.push_back(SelExp);
2356
2357 // Now push any user supplied arguments.
2358 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002359 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002360 // Make all implicit casts explicit...ICE comes in handy:-)
2361 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2362 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002363 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002364 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002365 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002366 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002367 }
2368 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002369 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002370 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002371 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002372 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002373 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002374 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002375 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002376 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002377 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002378 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002379 // We've transferred the ownership to MsgExprs. Null out the argument in
2380 // the original expression, since we will delete it below.
2381 Exp->setArg(i, 0);
2382 }
Steve Naroffab972d32007-11-04 22:37:50 +00002383 // Generate the funky cast.
2384 CastExpr *cast;
2385 llvm::SmallVector<QualType, 8> ArgTypes;
2386 QualType returnType;
2387
2388 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002389 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2390 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2391 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002392 ArgTypes.push_back(Context->getObjCIdType());
2393 ArgTypes.push_back(Context->getObjCSelType());
2394 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002395 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002396 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002397 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2398 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002399 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002400 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2401 if (isBlockPointerType(t)) {
2402 const BlockPointerType *BPT = t->getAsBlockPointerType();
2403 t = Context->getPointerType(BPT->getPointeeType());
2404 }
Steve Naroff352336b2007-11-05 14:36:37 +00002405 ArgTypes.push_back(t);
2406 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002407 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2408 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002409 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002410 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002411 }
2412 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002413 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002414
2415 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002416 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2417 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002418
2419 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2420 // If we don't do this cast, we get the following bizarre warning/note:
2421 // xx.m:13: warning: function called through a non-compatible type
2422 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002423 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002424 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002425 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002426
Steve Naroffab972d32007-11-04 22:37:50 +00002427 // Now do the "normal" pointer to function cast.
2428 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002429 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002430 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002431 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002432 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002433 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002434
2435 // Don't forget the parens to enforce the proper binding.
2436 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2437
2438 const FunctionType *FT = msgSendType->getAsFunctionType();
2439 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2440 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002441 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002442 if (MsgSendStretFlavor) {
2443 // We have the method which returns a struct/union. Must also generate
2444 // call to objc_msgSend_stret and hang both varieties on a conditional
2445 // expression which dictate which one to envoke depending on size of
2446 // method's return type.
2447
2448 // Create a reference to the objc_msgSend_stret() declaration.
2449 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2450 SourceLocation());
2451 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002452 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002453 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002454 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002455 // Now do the "normal" pointer to function cast.
2456 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002457 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002458 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002459 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002460 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002461
2462 // Don't forget the parens to enforce the proper binding.
2463 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2464
2465 FT = msgSendType->getAsFunctionType();
2466 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2467 FT->getResultType(), SourceLocation());
2468
2469 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002470 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2471 returnType.getAsOpaquePtr(),
2472 Context->getSizeType(),
2473 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002474 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2475 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2476 // For X86 it is more complicated and some kind of target specific routine
2477 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002478 unsigned IntSize =
2479 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002480 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2481 Context->IntTy,
2482 SourceLocation());
2483 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2484 BinaryOperator::LE,
2485 Context->IntTy,
2486 SourceLocation());
2487 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2488 ConditionalOperator *CondExpr =
2489 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002490 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002491 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002492 return ReplacingStmt;
2493}
2494
Steve Naroffb29b4272008-04-14 22:03:09 +00002495Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002496 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002497
Steve Naroffc77a6362008-12-04 16:24:46 +00002498 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002499 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002500 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002501
Steve Naroff4c3580e2008-12-04 23:50:32 +00002502 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002503 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002504}
2505
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002506/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2507/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002508Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002509 if (!GetProtocolFunctionDecl)
2510 SynthGetProtocolFunctionDecl();
2511 // Create a call to objc_getProtocol("ProtocolName").
2512 llvm::SmallVector<Expr*, 8> ProtoExprs;
2513 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002514 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2515 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002516 false, argType, SourceLocation(),
2517 SourceLocation()));
2518 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2519 &ProtoExprs[0],
2520 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002521 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002522 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002523 return ProtoExp;
2524
2525}
2526
Steve Naroffbaf58c32008-05-31 14:15:04 +00002527bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2528 const char *endBuf) {
2529 while (startBuf < endBuf) {
2530 if (*startBuf == '#') {
2531 // Skip whitespace.
2532 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2533 ;
2534 if (!strncmp(startBuf, "if", strlen("if")) ||
2535 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2536 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2537 !strncmp(startBuf, "define", strlen("define")) ||
2538 !strncmp(startBuf, "undef", strlen("undef")) ||
2539 !strncmp(startBuf, "else", strlen("else")) ||
2540 !strncmp(startBuf, "elif", strlen("elif")) ||
2541 !strncmp(startBuf, "endif", strlen("endif")) ||
2542 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2543 !strncmp(startBuf, "include", strlen("include")) ||
2544 !strncmp(startBuf, "import", strlen("import")) ||
2545 !strncmp(startBuf, "include_next", strlen("include_next")))
2546 return true;
2547 }
2548 startBuf++;
2549 }
2550 return false;
2551}
2552
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002553/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002554/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002555void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002556 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002557 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002558 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002559 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002560 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002561 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002562 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002563 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002564 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002565 SourceLocation LocStart = CDecl->getLocStart();
2566 SourceLocation LocEnd = CDecl->getLocEnd();
2567
2568 const char *startBuf = SM->getCharacterData(LocStart);
2569 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002570
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002571 // If no ivars and no root or if its root, directly or indirectly,
2572 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002573 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2574 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002575 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002576 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002577 return;
2578 }
2579
2580 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002581 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002582 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002583 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002584 if (LangOpts.Microsoft)
2585 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002586
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002587 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002588 const char *cursor = strchr(startBuf, '{');
2589 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002590 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002591 // If the buffer contains preprocessor directives, we do more fine-grained
2592 // rewrites. This is intended to fix code that looks like (which occurs in
2593 // NSURL.h, for example):
2594 //
2595 // #ifdef XYZ
2596 // @interface Foo : NSObject
2597 // #else
2598 // @interface FooBar : NSObject
2599 // #endif
2600 // {
2601 // int i;
2602 // }
2603 // @end
2604 //
2605 // This clause is segregated to avoid breaking the common case.
2606 if (BufferContainsPPDirectives(startBuf, cursor)) {
2607 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2608 CDecl->getClassLoc();
2609 const char *endHeader = SM->getCharacterData(L);
2610 endHeader += Lexer::MeasureTokenLength(L, *SM);
2611
Chris Lattner3db6cae2008-07-21 18:19:38 +00002612 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002613 // advance to the end of the referenced protocols.
2614 while (endHeader < cursor && *endHeader != '>') endHeader++;
2615 endHeader++;
2616 }
2617 // rewrite the original header
2618 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2619 } else {
2620 // rewrite the original header *without* disturbing the '{'
2621 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2622 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002623 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002624 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002625 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002626 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002627 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002628 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002629
2630 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002631 SourceLocation OnePastCurly =
2632 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2633 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002634 }
2635 cursor++; // past '{'
2636
2637 // Now comment out any visibility specifiers.
2638 while (cursor < endBuf) {
2639 if (*cursor == '@') {
2640 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002641 // Skip whitespace.
2642 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2643 /*scan*/;
2644
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002645 // FIXME: presence of @public, etc. inside comment results in
2646 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002647 if (!strncmp(cursor, "public", strlen("public")) ||
2648 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002649 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002650 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002651 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002652 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002653 // FIXME: If there are cases where '<' is used in ivar declaration part
2654 // of user code, then scan the ivar list and use needToScanForQualifiers
2655 // for type checking.
2656 else if (*cursor == '<') {
2657 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002658 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002659 cursor = strchr(cursor, '>');
2660 cursor++;
2661 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002662 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002663 } else if (*cursor == '^') { // rewrite block specifier.
2664 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2665 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002666 }
Steve Narofffea763e82007-11-14 19:25:57 +00002667 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002668 }
Steve Narofffea763e82007-11-14 19:25:57 +00002669 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002670 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002671 } else { // we don't have any instance variables - insert super struct.
2672 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2673 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002674 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002675 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002676 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002677 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002678 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002679 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002680 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002681 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002682 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002683}
2684
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002685// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002686/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002687void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002688 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002689 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002690 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002691 const char *ClassName,
2692 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002693 if (MethodBegin == MethodEnd) return;
2694
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002695 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002696 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002697 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002698 SEL _cmd;
2699 char *method_types;
2700 void *_imp;
2701 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002702 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002703 Result += "\nstruct _objc_method {\n";
2704 Result += "\tSEL _cmd;\n";
2705 Result += "\tchar *method_types;\n";
2706 Result += "\tvoid *_imp;\n";
2707 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002708
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002709 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002710 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002711
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002712 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002713
2714 /* struct {
2715 struct _objc_method_list *next_method;
2716 int method_count;
2717 struct _objc_method method_list[];
2718 }
2719 */
2720 Result += "\nstatic struct {\n";
2721 Result += "\tstruct _objc_method_list *next_method;\n";
2722 Result += "\tint method_count;\n";
2723 Result += "\tstruct _objc_method method_list[";
2724 Result += utostr(MethodEnd-MethodBegin);
2725 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002726 Result += prefix;
2727 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2728 Result += "_METHODS_";
2729 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002730 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002731 Result += IsInstanceMethod ? "inst" : "cls";
2732 Result += "_meth\")))= ";
2733 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002734
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002735 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002736 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002737 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002738 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002739 Result += "\", \"";
2740 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002741 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002742 Result += MethodInternalNames[*MethodBegin];
2743 Result += "}\n";
2744 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2745 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002746 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002747 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002748 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002749 Result += "\", \"";
2750 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002751 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002752 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002753 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002754 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002755 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002756}
2757
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002758/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002759void RewriteObjC::
2760RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2761 const char *prefix,
2762 const char *ClassName,
2763 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002764 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002765 if (Protocols.empty()) return;
2766
2767 for (unsigned i = 0; i != Protocols.size(); i++) {
2768 ObjCProtocolDecl *PDecl = Protocols[i];
2769 // Output struct protocol_methods holder of method selector and type.
2770 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2771 /* struct protocol_methods {
2772 SEL _cmd;
2773 char *method_types;
2774 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002775 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002776 Result += "\nstruct protocol_methods {\n";
2777 Result += "\tSEL _cmd;\n";
2778 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002779 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002780
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002781 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002782 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002783 // Do not synthesize the protocol more than once.
2784 if (ObjCSynthesizedProtocols.count(PDecl))
2785 continue;
2786
2787 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2788 unsigned NumMethods = PDecl->getNumInstanceMethods();
2789 /* struct _objc_protocol_method_list {
2790 int protocol_method_count;
2791 struct protocol_methods protocols[];
2792 }
2793 */
2794 Result += "\nstatic struct {\n";
2795 Result += "\tint protocol_method_count;\n";
2796 Result += "\tstruct protocol_methods protocols[";
2797 Result += utostr(NumMethods);
2798 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002799 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002800 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2801 "{\n\t" + utostr(NumMethods) + "\n";
2802
2803 // Output instance methods declared in this protocol.
2804 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2805 E = PDecl->instmeth_end(); I != E; ++I) {
2806 if (I == PDecl->instmeth_begin())
2807 Result += "\t ,{{(SEL)\"";
2808 else
2809 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002810 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002811 std::string MethodTypeString;
2812 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2813 Result += "\", \"";
2814 Result += MethodTypeString;
2815 Result += "\"}\n";
2816 }
2817 Result += "\t }\n};\n";
2818 }
2819
2820 // Output class methods declared in this protocol.
2821 int NumMethods = PDecl->getNumClassMethods();
2822 if (NumMethods > 0) {
2823 /* struct _objc_protocol_method_list {
2824 int protocol_method_count;
2825 struct protocol_methods protocols[];
2826 }
2827 */
2828 Result += "\nstatic struct {\n";
2829 Result += "\tint protocol_method_count;\n";
2830 Result += "\tstruct protocol_methods protocols[";
2831 Result += utostr(NumMethods);
2832 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002833 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002834 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2835 "{\n\t";
2836 Result += utostr(NumMethods);
2837 Result += "\n";
2838
2839 // Output instance methods declared in this protocol.
2840 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2841 E = PDecl->classmeth_end(); I != E; ++I) {
2842 if (I == PDecl->classmeth_begin())
2843 Result += "\t ,{{(SEL)\"";
2844 else
2845 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002846 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002847 std::string MethodTypeString;
2848 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2849 Result += "\", \"";
2850 Result += MethodTypeString;
2851 Result += "\"}\n";
2852 }
2853 Result += "\t }\n};\n";
2854 }
2855
2856 // Output:
2857 /* struct _objc_protocol {
2858 // Objective-C 1.0 extensions
2859 struct _objc_protocol_extension *isa;
2860 char *protocol_name;
2861 struct _objc_protocol **protocol_list;
2862 struct _objc_protocol_method_list *instance_methods;
2863 struct _objc_protocol_method_list *class_methods;
2864 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002865 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002866 static bool objc_protocol = false;
2867 if (!objc_protocol) {
2868 Result += "\nstruct _objc_protocol {\n";
2869 Result += "\tstruct _objc_protocol_extension *isa;\n";
2870 Result += "\tchar *protocol_name;\n";
2871 Result += "\tstruct _objc_protocol **protocol_list;\n";
2872 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2873 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2874 Result += "};\n";
2875
2876 objc_protocol = true;
2877 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002878
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002879 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002880 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002881 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2882 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002883 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002884 Result += "\", 0, ";
2885 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2886 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002887 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002888 Result += ", ";
2889 }
2890 else
2891 Result += "0, ";
2892 if (PDecl->getNumClassMethods() > 0) {
2893 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002894 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002895 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002896 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002897 else
2898 Result += "0\n";
2899 Result += "};\n";
2900
2901 // Mark this protocol as having been generated.
2902 if (!ObjCSynthesizedProtocols.insert(PDecl))
2903 assert(false && "protocol already synthesized");
2904 }
2905 // Output the top lovel protocol meta-data for the class.
2906 /* struct _objc_protocol_list {
2907 struct _objc_protocol_list *next;
2908 int protocol_count;
2909 struct _objc_protocol *class_protocols[];
2910 }
2911 */
2912 Result += "\nstatic struct {\n";
2913 Result += "\tstruct _objc_protocol_list *next;\n";
2914 Result += "\tint protocol_count;\n";
2915 Result += "\tstruct _objc_protocol *class_protocols[";
2916 Result += utostr(Protocols.size());
2917 Result += "];\n} _OBJC_";
2918 Result += prefix;
2919 Result += "_PROTOCOLS_";
2920 Result += ClassName;
2921 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2922 "{\n\t0, ";
2923 Result += utostr(Protocols.size());
2924 Result += "\n";
2925
2926 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002927 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002928 Result += " \n";
2929
2930 for (unsigned i = 1; i != Protocols.size(); i++) {
2931 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002932 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002933 Result += "\n";
2934 }
2935 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002936}
2937
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002938/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002939/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002940void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002941 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002942 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002943 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002944 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002945 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2946 CDecl = CDecl->getNextClassCategory())
2947 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2948 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002949
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002950 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002951 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002952 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002953
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002954 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002955 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002956 true, "CATEGORY_", FullCategoryName.c_str(),
2957 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002958
2959 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002960 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002961 false, "CATEGORY_", FullCategoryName.c_str(),
2962 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002963
2964 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002965 // Null CDecl is case of a category implementation with no category interface
2966 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002967 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002968 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002969
2970 /* struct _objc_category {
2971 char *category_name;
2972 char *class_name;
2973 struct _objc_method_list *instance_methods;
2974 struct _objc_method_list *class_methods;
2975 struct _objc_protocol_list *protocols;
2976 // Objective-C 1.0 extensions
2977 uint32_t size; // sizeof (struct _objc_category)
2978 struct _objc_property_list *instance_properties; // category's own
2979 // @property decl.
2980 };
2981 */
2982
2983 static bool objc_category = false;
2984 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002985 Result += "\nstruct _objc_category {\n";
2986 Result += "\tchar *category_name;\n";
2987 Result += "\tchar *class_name;\n";
2988 Result += "\tstruct _objc_method_list *instance_methods;\n";
2989 Result += "\tstruct _objc_method_list *class_methods;\n";
2990 Result += "\tstruct _objc_protocol_list *protocols;\n";
2991 Result += "\tunsigned int size;\n";
2992 Result += "\tstruct _objc_property_list *instance_properties;\n";
2993 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002994 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002995 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002996 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2997 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002998 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002999 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003000 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003001 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003002 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003003
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003004 if (IDecl->getNumInstanceMethods() > 0) {
3005 Result += "\t, (struct _objc_method_list *)"
3006 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3007 Result += FullCategoryName;
3008 Result += "\n";
3009 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003010 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003011 Result += "\t, 0\n";
3012 if (IDecl->getNumClassMethods() > 0) {
3013 Result += "\t, (struct _objc_method_list *)"
3014 "&_OBJC_CATEGORY_CLASS_METHODS_";
3015 Result += FullCategoryName;
3016 Result += "\n";
3017 }
3018 else
3019 Result += "\t, 0\n";
3020
Chris Lattner780f3292008-07-21 21:32:27 +00003021 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003022 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3023 Result += FullCategoryName;
3024 Result += "\n";
3025 }
3026 else
3027 Result += "\t, 0\n";
3028 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003029}
3030
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003031/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3032/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003033void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003034 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003035 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003036 if (ivar->isBitField()) {
3037 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3038 // place all bitfields at offset 0.
3039 Result += "0";
3040 } else {
3041 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003042 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003043 if (LangOpts.Microsoft)
3044 Result += "_IMPL";
3045 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003046 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003047 Result += ")";
3048 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003049}
3050
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003051//===----------------------------------------------------------------------===//
3052// Meta Data Emission
3053//===----------------------------------------------------------------------===//
3054
Steve Naroffb29b4272008-04-14 22:03:09 +00003055void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003056 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003057 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003058
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003059 // Explictly declared @interface's are already synthesized.
3060 if (CDecl->ImplicitInterfaceDecl()) {
3061 // FIXME: Implementation of a class with no @interface (legacy) doese not
3062 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003063 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003064 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003065
Chris Lattnerbe6df082007-12-12 07:56:42 +00003066 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003067 unsigned NumIvars = !IDecl->ivar_empty()
3068 ? IDecl->ivar_size()
3069 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003070 if (NumIvars > 0) {
3071 static bool objc_ivar = false;
3072 if (!objc_ivar) {
3073 /* struct _objc_ivar {
3074 char *ivar_name;
3075 char *ivar_type;
3076 int ivar_offset;
3077 };
3078 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003079 Result += "\nstruct _objc_ivar {\n";
3080 Result += "\tchar *ivar_name;\n";
3081 Result += "\tchar *ivar_type;\n";
3082 Result += "\tint ivar_offset;\n";
3083 Result += "};\n";
3084
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003085 objc_ivar = true;
3086 }
3087
Steve Naroff946a6932008-03-11 00:12:29 +00003088 /* struct {
3089 int ivar_count;
3090 struct _objc_ivar ivar_list[nIvars];
3091 };
3092 */
3093 Result += "\nstatic struct {\n";
3094 Result += "\tint ivar_count;\n";
3095 Result += "\tstruct _objc_ivar ivar_list[";
3096 Result += utostr(NumIvars);
3097 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003098 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003099 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003100 "{\n\t";
3101 Result += utostr(NumIvars);
3102 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003103
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003104 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003105 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003106 IVI = IDecl->ivar_begin();
3107 IVE = IDecl->ivar_end();
3108 } else {
3109 IVI = CDecl->ivar_begin();
3110 IVE = CDecl->ivar_end();
3111 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003112 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003113 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003114 Result += "\", \"";
3115 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003116 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003117 Result += StrEncoding;
3118 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003119 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003120 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003121 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003122 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003123 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003124 Result += "\", \"";
3125 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003126 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003127 Result += StrEncoding;
3128 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003129 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003130 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003131 }
3132
3133 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003134 }
3135
3136 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003137 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003138 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003139
3140 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003141 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003142 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003143
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003144 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003145 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003146 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003147
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003148
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003149 // Declaration of class/meta-class metadata
3150 /* struct _objc_class {
3151 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003152 const char *super_class_name;
3153 char *name;
3154 long version;
3155 long info;
3156 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003157 struct _objc_ivar_list *ivars;
3158 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003159 struct objc_cache *cache;
3160 struct objc_protocol_list *protocols;
3161 const char *ivar_layout;
3162 struct _objc_class_ext *ext;
3163 };
3164 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003165 static bool objc_class = false;
3166 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003167 Result += "\nstruct _objc_class {\n";
3168 Result += "\tstruct _objc_class *isa;\n";
3169 Result += "\tconst char *super_class_name;\n";
3170 Result += "\tchar *name;\n";
3171 Result += "\tlong version;\n";
3172 Result += "\tlong info;\n";
3173 Result += "\tlong instance_size;\n";
3174 Result += "\tstruct _objc_ivar_list *ivars;\n";
3175 Result += "\tstruct _objc_method_list *methods;\n";
3176 Result += "\tstruct objc_cache *cache;\n";
3177 Result += "\tstruct _objc_protocol_list *protocols;\n";
3178 Result += "\tconst char *ivar_layout;\n";
3179 Result += "\tstruct _objc_class_ext *ext;\n";
3180 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003181 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003182 }
3183
3184 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003185 ObjCInterfaceDecl *RootClass = 0;
3186 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003187 while (SuperClass) {
3188 RootClass = SuperClass;
3189 SuperClass = SuperClass->getSuperClass();
3190 }
3191 SuperClass = CDecl->getSuperClass();
3192
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003193 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003194 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003195 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003196 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003197 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003198 Result += "\"";
3199
3200 if (SuperClass) {
3201 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003202 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003203 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003204 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003205 Result += "\"";
3206 }
3207 else {
3208 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003209 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003210 Result += "\"";
3211 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003212 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003213 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003214 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003215 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003216 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003217 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003218 Result += "\n";
3219 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003220 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003221 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003222 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003223 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003224 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003225 Result += ",0,0\n";
3226 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003227 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003228 Result += "\t,0,0,0,0\n";
3229 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003230
3231 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003232 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003233 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003234 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003235 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003236 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003237 if (SuperClass) {
3238 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003239 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003240 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003241 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003242 Result += "\"";
3243 }
3244 else {
3245 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003246 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003247 Result += "\"";
3248 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003249 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003250 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003251 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003252 Result += ",0";
3253 else {
3254 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003255 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003256 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003257 if (LangOpts.Microsoft)
3258 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003259 Result += ")";
3260 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003261 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003262 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003263 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003264 Result += "\n\t";
3265 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003266 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003267 Result += ",0";
3268 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003269 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003270 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003271 Result += ", 0\n\t";
3272 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003273 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003274 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003275 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003276 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003277 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003278 Result += ", 0,0\n";
3279 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003280 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003281 Result += ",0,0,0\n";
3282 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003283}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003284
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003285/// RewriteImplementations - This routine rewrites all method implementations
3286/// and emits meta-data.
3287
Steve Narofface66252008-11-13 20:07:04 +00003288void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003289 int ClsDefCount = ClassImplementation.size();
3290 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003291
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003292 // Rewrite implemented methods
3293 for (int i = 0; i < ClsDefCount; i++)
3294 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003295
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003296 for (int i = 0; i < CatDefCount; i++)
3297 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003298}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003299
Steve Narofface66252008-11-13 20:07:04 +00003300void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3301 int ClsDefCount = ClassImplementation.size();
3302 int CatDefCount = CategoryImplementation.size();
3303
Steve Naroff5df5b762008-05-07 21:23:49 +00003304 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003305 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003306 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003307 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003308 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003309
3310 // For each implemented category, write out all its meta data.
3311 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003312 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003313
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003314 // Write objc_symtab metadata
3315 /*
3316 struct _objc_symtab
3317 {
3318 long sel_ref_cnt;
3319 SEL *refs;
3320 short cls_def_cnt;
3321 short cat_def_cnt;
3322 void *defs[cls_def_cnt + cat_def_cnt];
3323 };
3324 */
3325
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003326 Result += "\nstruct _objc_symtab {\n";
3327 Result += "\tlong sel_ref_cnt;\n";
3328 Result += "\tSEL *refs;\n";
3329 Result += "\tshort cls_def_cnt;\n";
3330 Result += "\tshort cat_def_cnt;\n";
3331 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3332 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003333
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003334 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003335 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003336 Result += "\t0, 0, " + utostr(ClsDefCount)
3337 + ", " + utostr(CatDefCount) + "\n";
3338 for (int i = 0; i < ClsDefCount; i++) {
3339 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003340 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003341 Result += "\n";
3342 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003343
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003344 for (int i = 0; i < CatDefCount; i++) {
3345 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003346 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003347 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003348 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003349 Result += "\n";
3350 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003351
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003352 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003353
3354 // Write objc_module metadata
3355
3356 /*
3357 struct _objc_module {
3358 long version;
3359 long size;
3360 const char *name;
3361 struct _objc_symtab *symtab;
3362 }
3363 */
3364
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003365 Result += "\nstruct _objc_module {\n";
3366 Result += "\tlong version;\n";
3367 Result += "\tlong size;\n";
3368 Result += "\tconst char *name;\n";
3369 Result += "\tstruct _objc_symtab *symtab;\n";
3370 Result += "};\n\n";
3371 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003372 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003373 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3374 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003375 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003376
3377 if (LangOpts.Microsoft) {
3378 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003379 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003380 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3381 Result += "&_OBJC_MODULES;\n";
3382 Result += "#pragma data_seg(pop)\n\n";
3383 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003384}
Chris Lattner311ff022007-10-16 22:36:42 +00003385
Steve Naroff54055232008-10-27 17:20:55 +00003386std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3387 const char *funcName,
3388 std::string Tag) {
3389 const FunctionType *AFT = CE->getFunctionType();
3390 QualType RT = AFT->getResultType();
3391 std::string StructRef = "struct " + Tag;
3392 std::string S = "static " + RT.getAsString() + " __" +
3393 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003394
Steve Naroff54055232008-10-27 17:20:55 +00003395 BlockDecl *BD = CE->getBlockDecl();
3396
3397 if (isa<FunctionTypeNoProto>(AFT)) {
3398 S += "()";
3399 } else if (BD->param_empty()) {
3400 S += "(" + StructRef + " *__cself)";
3401 } else {
3402 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3403 assert(FT && "SynthesizeBlockFunc: No function proto");
3404 S += '(';
3405 // first add the implicit argument.
3406 S += StructRef + " *__cself, ";
3407 std::string ParamStr;
3408 for (BlockDecl::param_iterator AI = BD->param_begin(),
3409 E = BD->param_end(); AI != E; ++AI) {
3410 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003411 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003412 (*AI)->getType().getAsStringInternal(ParamStr);
3413 S += ParamStr;
3414 }
3415 if (FT->isVariadic()) {
3416 if (!BD->param_empty()) S += ", ";
3417 S += "...";
3418 }
3419 S += ')';
3420 }
3421 S += " {\n";
3422
3423 // Create local declarations to avoid rewriting all closure decl ref exprs.
3424 // First, emit a declaration for all "by ref" decls.
3425 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3426 E = BlockByRefDecls.end(); I != E; ++I) {
3427 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003428 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003429 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003430 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003431 }
3432 // Next, emit a declaration for all "by copy" declarations.
3433 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3434 E = BlockByCopyDecls.end(); I != E; ++I) {
3435 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003436 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003437 // Handle nested closure invocation. For example:
3438 //
3439 // void (^myImportedClosure)(void);
3440 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3441 //
3442 // void (^anotherClosure)(void);
3443 // anotherClosure = ^(void) {
3444 // myImportedClosure(); // import and invoke the closure
3445 // };
3446 //
3447 if (isBlockPointerType((*I)->getType()))
3448 S += "struct __block_impl *";
3449 else
3450 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003451 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003452 }
3453 std::string RewrittenStr = RewrittenBlockExprs[CE];
3454 const char *cstr = RewrittenStr.c_str();
3455 while (*cstr++ != '{') ;
3456 S += cstr;
3457 S += "\n";
3458 return S;
3459}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003460
Steve Naroff54055232008-10-27 17:20:55 +00003461std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3462 const char *funcName,
3463 std::string Tag) {
3464 std::string StructRef = "struct " + Tag;
3465 std::string S = "static void __";
3466
3467 S += funcName;
3468 S += "_block_copy_" + utostr(i);
3469 S += "(" + StructRef;
3470 S += "*dst, " + StructRef;
3471 S += "*src) {";
3472 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3473 E = ImportedBlockDecls.end(); I != E; ++I) {
3474 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003475 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003476 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003477 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003478 S += ");}";
3479 }
3480 S += "\nstatic void __";
3481 S += funcName;
3482 S += "_block_dispose_" + utostr(i);
3483 S += "(" + StructRef;
3484 S += "*src) {";
3485 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3486 E = ImportedBlockDecls.end(); I != E; ++I) {
3487 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003488 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003489 S += ");";
3490 }
3491 S += "}\n";
3492 return S;
3493}
3494
3495std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3496 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003497 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003498 std::string Constructor = " " + Tag;
3499
3500 S += " {\n struct __block_impl impl;\n";
3501
3502 if (hasCopyDisposeHelpers)
3503 S += " void *copy;\n void *dispose;\n";
3504
3505 Constructor += "(void *fp";
3506
3507 if (hasCopyDisposeHelpers)
3508 Constructor += ", void *copyHelp, void *disposeHelp";
3509
3510 if (BlockDeclRefs.size()) {
3511 // Output all "by copy" declarations.
3512 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3513 E = BlockByCopyDecls.end(); I != E; ++I) {
3514 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003515 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003516 std::string ArgName = "_" + FieldName;
3517 // Handle nested closure invocation. For example:
3518 //
3519 // void (^myImportedBlock)(void);
3520 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3521 //
3522 // void (^anotherBlock)(void);
3523 // anotherBlock = ^(void) {
3524 // myImportedBlock(); // import and invoke the closure
3525 // };
3526 //
3527 if (isBlockPointerType((*I)->getType())) {
3528 S += "struct __block_impl *";
3529 Constructor += ", void *" + ArgName;
3530 } else {
3531 (*I)->getType().getAsStringInternal(FieldName);
3532 (*I)->getType().getAsStringInternal(ArgName);
3533 Constructor += ", " + ArgName;
3534 }
3535 S += FieldName + ";\n";
3536 }
3537 // Output all "by ref" declarations.
3538 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3539 E = BlockByRefDecls.end(); I != E; ++I) {
3540 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003541 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003542 std::string ArgName = "_" + FieldName;
3543 // Handle nested closure invocation. For example:
3544 //
3545 // void (^myImportedBlock)(void);
3546 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3547 //
3548 // void (^anotherBlock)(void);
3549 // anotherBlock = ^(void) {
3550 // myImportedBlock(); // import and invoke the closure
3551 // };
3552 //
3553 if (isBlockPointerType((*I)->getType())) {
3554 S += "struct __block_impl *";
3555 Constructor += ", void *" + ArgName;
3556 } else {
3557 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3558 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3559 Constructor += ", " + ArgName;
3560 }
3561 S += FieldName + "; // by ref\n";
3562 }
3563 // Finish writing the constructor.
3564 // FIXME: handle NSConcreteGlobalBlock.
3565 Constructor += ", int flags=0) {\n";
3566 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3567 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3568
3569 if (hasCopyDisposeHelpers)
3570 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3571
3572 // Initialize all "by copy" arguments.
3573 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3574 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003575 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003576 Constructor += " ";
3577 if (isBlockPointerType((*I)->getType()))
3578 Constructor += Name + " = (struct __block_impl *)_";
3579 else
3580 Constructor += Name + " = _";
3581 Constructor += Name + ";\n";
3582 }
3583 // Initialize all "by ref" arguments.
3584 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3585 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003586 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003587 Constructor += " ";
3588 if (isBlockPointerType((*I)->getType()))
3589 Constructor += Name + " = (struct __block_impl *)_";
3590 else
3591 Constructor += Name + " = _";
3592 Constructor += Name + ";\n";
3593 }
3594 } else {
3595 // Finish writing the constructor.
3596 // FIXME: handle NSConcreteGlobalBlock.
3597 Constructor += ", int flags=0) {\n";
3598 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3599 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3600 if (hasCopyDisposeHelpers)
3601 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3602 }
3603 Constructor += " ";
3604 Constructor += "}\n";
3605 S += Constructor;
3606 S += "};\n";
3607 return S;
3608}
3609
3610void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3611 const char *FunName) {
3612 // Insert closures that were part of the function.
3613 for (unsigned i = 0; i < Blocks.size(); i++) {
3614
3615 CollectBlockDeclRefInfo(Blocks[i]);
3616
3617 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3618
3619 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3620 ImportedBlockDecls.size() > 0);
3621
3622 InsertText(FunLocStart, CI.c_str(), CI.size());
3623
3624 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3625
3626 InsertText(FunLocStart, CF.c_str(), CF.size());
3627
3628 if (ImportedBlockDecls.size()) {
3629 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3630 InsertText(FunLocStart, HF.c_str(), HF.size());
3631 }
3632
3633 BlockDeclRefs.clear();
3634 BlockByRefDecls.clear();
3635 BlockByCopyDecls.clear();
3636 BlockCallExprs.clear();
3637 ImportedBlockDecls.clear();
3638 }
3639 Blocks.clear();
3640 RewrittenBlockExprs.clear();
3641}
3642
3643void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3644 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003645 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003646
3647 SynthesizeBlockLiterals(FunLocStart, FuncName);
3648}
3649
3650void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003651 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3652 //SourceLocation FunLocStart = MD->getLocStart();
3653 // FIXME: This hack works around a bug in Rewrite.InsertText().
3654 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003655 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003656 // Convert colons to underscores.
3657 std::string::size_type loc = 0;
3658 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3659 FuncName.replace(loc, 1, "_");
3660
3661 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3662}
3663
3664void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3665 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3666 CI != E; ++CI)
3667 if (*CI) {
3668 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3669 GetBlockDeclRefExprs(CBE->getBody());
3670 else
3671 GetBlockDeclRefExprs(*CI);
3672 }
3673 // Handle specific things.
3674 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3675 // FIXME: Handle enums.
3676 if (!isa<FunctionDecl>(CDRE->getDecl()))
3677 BlockDeclRefs.push_back(CDRE);
3678 return;
3679}
3680
3681void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3682 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3683 CI != E; ++CI)
3684 if (*CI) {
3685 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3686 GetBlockCallExprs(CBE->getBody());
3687 else
3688 GetBlockCallExprs(*CI);
3689 }
3690
3691 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3692 if (CE->getCallee()->getType()->isBlockPointerType()) {
3693 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3694 }
3695 }
3696 return;
3697}
3698
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003699Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003700 // Navigate to relevant type information.
3701 const char *closureName = 0;
3702 const BlockPointerType *CPT = 0;
3703
3704 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003705 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003706 CPT = DRE->getType()->getAsBlockPointerType();
3707 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003708 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003709 CPT = CDRE->getType()->getAsBlockPointerType();
3710 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003711 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003712 CPT = MExpr->getType()->getAsBlockPointerType();
3713 } else {
3714 assert(1 && "RewriteBlockClass: Bad type");
3715 }
3716 assert(CPT && "RewriteBlockClass: Bad type");
3717 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3718 assert(FT && "RewriteBlockClass: Bad type");
3719 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3720 // FTP will be null for closures that don't take arguments.
3721
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003722 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3723 SourceLocation(),
3724 &Context->Idents.get("__block_impl"));
3725 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003726
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003727 // Generate a funky cast.
3728 llvm::SmallVector<QualType, 8> ArgTypes;
3729
3730 // Push the block argument type.
3731 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003732 if (FTP) {
3733 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003734 E = FTP->arg_type_end(); I && (I != E); ++I) {
3735 QualType t = *I;
3736 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3737 if (isBlockPointerType(t)) {
3738 const BlockPointerType *BPT = t->getAsBlockPointerType();
3739 t = Context->getPointerType(BPT->getPointeeType());
3740 }
3741 ArgTypes.push_back(t);
3742 }
Steve Naroff54055232008-10-27 17:20:55 +00003743 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003744 // Now do the pointer to function cast.
3745 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3746 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3747
3748 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003749
Steve Naroffb2f9e512008-11-03 23:29:32 +00003750 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003751 // Don't forget the parens to enforce the proper binding.
3752 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3753 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003754
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003755 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3756 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3757 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3758
Steve Naroffb2f9e512008-11-03 23:29:32 +00003759 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003760 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3761
3762 llvm::SmallVector<Expr*, 8> BlkExprs;
3763 // Add the implicit argument.
3764 BlkExprs.push_back(BlkCast);
3765 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003766 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3767 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003768 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003769 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003770 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3771 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003772}
3773
3774void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003775 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3776 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003777}
3778
3779void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3780 // FIXME: Add more elaborate code generation required by the ABI.
3781 InsertText(BDRE->getLocStart(), "*", 1);
3782}
3783
Steve Naroffb2f9e512008-11-03 23:29:32 +00003784void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3785 SourceLocation LocStart = CE->getLParenLoc();
3786 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003787
3788 // Need to avoid trying to rewrite synthesized casts.
3789 if (LocStart.isInvalid())
3790 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003791 // Need to avoid trying to rewrite casts contained in macros.
3792 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3793 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003794
Steve Naroff54055232008-10-27 17:20:55 +00003795 const char *startBuf = SM->getCharacterData(LocStart);
3796 const char *endBuf = SM->getCharacterData(LocEnd);
3797
3798 // advance the location to startArgList.
3799 const char *argPtr = startBuf;
3800
3801 while (*argPtr++ && (argPtr < endBuf)) {
3802 switch (*argPtr) {
3803 case '^':
3804 // Replace the '^' with '*'.
3805 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3806 ReplaceText(LocStart, 1, "*", 1);
3807 break;
3808 }
3809 }
3810 return;
3811}
3812
3813void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3814 SourceLocation DeclLoc = FD->getLocation();
3815 unsigned parenCount = 0;
3816
3817 // We have 1 or more arguments that have closure pointers.
3818 const char *startBuf = SM->getCharacterData(DeclLoc);
3819 const char *startArgList = strchr(startBuf, '(');
3820
3821 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3822
3823 parenCount++;
3824 // advance the location to startArgList.
3825 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3826 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3827
3828 const char *argPtr = startArgList;
3829
3830 while (*argPtr++ && parenCount) {
3831 switch (*argPtr) {
3832 case '^':
3833 // Replace the '^' with '*'.
3834 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3835 ReplaceText(DeclLoc, 1, "*", 1);
3836 break;
3837 case '(':
3838 parenCount++;
3839 break;
3840 case ')':
3841 parenCount--;
3842 break;
3843 }
3844 }
3845 return;
3846}
3847
3848bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3849 const FunctionTypeProto *FTP;
3850 const PointerType *PT = QT->getAsPointerType();
3851 if (PT) {
3852 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3853 } else {
3854 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3855 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3856 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3857 }
3858 if (FTP) {
3859 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3860 E = FTP->arg_type_end(); I != E; ++I)
3861 if (isBlockPointerType(*I))
3862 return true;
3863 }
3864 return false;
3865}
3866
3867void RewriteObjC::GetExtentOfArgList(const char *Name,
3868 const char *&LParen, const char *&RParen) {
3869 const char *argPtr = strchr(Name, '(');
3870 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3871
3872 LParen = argPtr; // output the start.
3873 argPtr++; // skip past the left paren.
3874 unsigned parenCount = 1;
3875
3876 while (*argPtr && parenCount) {
3877 switch (*argPtr) {
3878 case '(': parenCount++; break;
3879 case ')': parenCount--; break;
3880 default: break;
3881 }
3882 if (parenCount) argPtr++;
3883 }
3884 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3885 RParen = argPtr; // output the end
3886}
3887
3888void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3889 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3890 RewriteBlockPointerFunctionArgs(FD);
3891 return;
3892 }
3893 // Handle Variables and Typedefs.
3894 SourceLocation DeclLoc = ND->getLocation();
3895 QualType DeclT;
3896 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3897 DeclT = VD->getType();
3898 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3899 DeclT = TDD->getUnderlyingType();
3900 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3901 DeclT = FD->getType();
3902 else
3903 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3904
3905 const char *startBuf = SM->getCharacterData(DeclLoc);
3906 const char *endBuf = startBuf;
3907 // scan backward (from the decl location) for the end of the previous decl.
3908 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3909 startBuf--;
3910
3911 // *startBuf != '^' if we are dealing with a pointer to function that
3912 // may take block argument types (which will be handled below).
3913 if (*startBuf == '^') {
3914 // Replace the '^' with '*', computing a negative offset.
3915 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3916 ReplaceText(DeclLoc, 1, "*", 1);
3917 }
3918 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3919 // Replace the '^' with '*' for arguments.
3920 DeclLoc = ND->getLocation();
3921 startBuf = SM->getCharacterData(DeclLoc);
3922 const char *argListBegin, *argListEnd;
3923 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3924 while (argListBegin < argListEnd) {
3925 if (*argListBegin == '^') {
3926 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3927 ReplaceText(CaretLoc, 1, "*", 1);
3928 }
3929 argListBegin++;
3930 }
3931 }
3932 return;
3933}
3934
3935void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3936 // Add initializers for any closure decl refs.
3937 GetBlockDeclRefExprs(Exp->getBody());
3938 if (BlockDeclRefs.size()) {
3939 // Unique all "by copy" declarations.
3940 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3941 if (!BlockDeclRefs[i]->isByRef())
3942 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3943 // Unique all "by ref" declarations.
3944 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3945 if (BlockDeclRefs[i]->isByRef()) {
3946 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3947 }
3948 // Find any imported blocks...they will need special attention.
3949 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3950 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003951 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003952 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3953 }
3954 }
3955}
3956
Steve Narofffa15fd92008-10-28 20:29:00 +00003957FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3958 IdentifierInfo *ID = &Context->Idents.get(name);
3959 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3960 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3961 ID, FType, FunctionDecl::Extern, false, 0);
3962}
3963
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003964Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003965 Blocks.push_back(Exp);
3966
3967 CollectBlockDeclRefInfo(Exp);
3968 std::string FuncName;
3969
3970 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003971 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003972 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00003973 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003974 // Convert colons to underscores.
3975 std::string::size_type loc = 0;
3976 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3977 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003978 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003979 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00003980
3981 std::string BlockNumber = utostr(Blocks.size()-1);
3982
3983 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3984 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3985
3986 // Get a pointer to the function type so we can cast appropriately.
3987 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3988
3989 FunctionDecl *FD;
3990 Expr *NewRep;
3991
3992 // Simulate a contructor call...
3993 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3994 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3995
3996 llvm::SmallVector<Expr*, 4> InitExprs;
3997
Steve Narofffdc03722008-10-29 21:23:59 +00003998 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003999 FD = SynthBlockInitFunctionDecl(Func.c_str());
4000 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4001 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004002 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004003 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004004
4005 if (ImportedBlockDecls.size()) {
4006 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004007 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4008 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4009 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004010 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004011 InitExprs.push_back(castExpr);
4012
Steve Narofffa15fd92008-10-28 20:29:00 +00004013 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004014 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4015 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4016 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004017 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004018 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004019 }
4020 // Add initializers for any closure decl refs.
4021 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004022 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004023 // Output all "by copy" declarations.
4024 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4025 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004026 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004027 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004028 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004029 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004030 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004031 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004032 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4033 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004034 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004035 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004036 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004037 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004038 }
Steve Narofffdc03722008-10-29 21:23:59 +00004039 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004040 }
4041 // Output all "by ref" declarations.
4042 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4043 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004044 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004045 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4046 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
4047 Context->getPointerType(Exp->getType()),
4048 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004049 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004050 }
4051 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004052 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
4053 FType, SourceLocation());
4054 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
4055 Context->getPointerType(NewRep->getType()),
4056 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00004057 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004058 BlockDeclRefs.clear();
4059 BlockByRefDecls.clear();
4060 BlockByCopyDecls.clear();
4061 ImportedBlockDecls.clear();
4062 return NewRep;
4063}
4064
4065//===----------------------------------------------------------------------===//
4066// Function Body / Expression rewriting
4067//===----------------------------------------------------------------------===//
4068
Steve Naroffc77a6362008-12-04 16:24:46 +00004069// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4070// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4071// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4072// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4073// Since the rewriter isn't capable of rewriting rewritten code, it's important
4074// we get this right.
4075void RewriteObjC::CollectPropertySetters(Stmt *S) {
4076 // Perform a bottom up traversal of all children.
4077 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4078 CI != E; ++CI)
4079 if (*CI)
4080 CollectPropertySetters(*CI);
4081
4082 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4083 if (BinOp->isAssignmentOp()) {
4084 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4085 PropSetters[PRE] = BinOp;
4086 }
4087 }
4088}
4089
Steve Narofffa15fd92008-10-28 20:29:00 +00004090Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4091 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4092 isa<DoStmt>(S) || isa<ForStmt>(S))
4093 Stmts.push_back(S);
4094 else if (isa<ObjCForCollectionStmt>(S)) {
4095 Stmts.push_back(S);
4096 ObjCBcLabelNo.push_back(++BcLabelCount);
4097 }
4098
4099 SourceRange OrigStmtRange = S->getSourceRange();
4100
4101 // Perform a bottom up rewrite of all children.
4102 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4103 CI != E; ++CI)
4104 if (*CI) {
4105 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4106 if (newStmt)
4107 *CI = newStmt;
4108 }
4109
4110 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4111 // Rewrite the block body in place.
4112 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4113
4114 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004115 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4116 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004117
4118 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4119 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004120 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004121 return blockTranscribed;
4122 }
4123 // Handle specific things.
4124 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4125 return RewriteAtEncode(AtEncode);
4126
4127 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4128 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4129
Steve Naroffc77a6362008-12-04 16:24:46 +00004130 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4131 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4132 if (BinOp) {
4133 // Because the rewriter doesn't allow us to rewrite rewritten code,
4134 // we need to rewrite the right hand side prior to rewriting the setter.
4135 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff4c3580e2008-12-04 23:50:32 +00004136 //
4137 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4138 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4139 // to see the original expression). Consider this example:
4140 //
4141 // Foo *obj1, *obj2;
4142 //
4143 // obj1.i = [obj2 rrrr];
4144 //
4145 // 'BinOp' for the previous expression looks like:
4146 //
4147 // (BinaryOperator 0x231ccf0 'int' '='
4148 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4149 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4150 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4151 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4152 //
4153 // 'newStmt' represents the rewritten message expression. For example:
4154 //
4155 // (CallExpr 0x231d300 'id':'struct objc_object *'
4156 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4157 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4158 // (CStyleCastExpr 0x231d220 'void *'
4159 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4160 //
4161 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4162 // can be used as the setter argument. ReplaceStmt() will still 'see'
4163 // the original RHS (since we haven't altered BinOp).
4164 //
4165 // This implies the Rewrite* routines can no longer delete the original
4166 // node. As a result, we now leak the original AST nodes.
4167 //
Steve Naroffc77a6362008-12-04 16:24:46 +00004168 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt));
4169 } else {
4170 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004171 }
4172 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004173 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4174 return RewriteAtSelector(AtSelector);
4175
4176 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4177 return RewriteObjCStringLiteral(AtString);
4178
4179 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004180#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004181 // Before we rewrite it, put the original message expression in a comment.
4182 SourceLocation startLoc = MessExpr->getLocStart();
4183 SourceLocation endLoc = MessExpr->getLocEnd();
4184
4185 const char *startBuf = SM->getCharacterData(startLoc);
4186 const char *endBuf = SM->getCharacterData(endLoc);
4187
4188 std::string messString;
4189 messString += "// ";
4190 messString.append(startBuf, endBuf-startBuf+1);
4191 messString += "\n";
4192
4193 // FIXME: Missing definition of
4194 // InsertText(clang::SourceLocation, char const*, unsigned int).
4195 // InsertText(startLoc, messString.c_str(), messString.size());
4196 // Tried this, but it didn't work either...
4197 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004198#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004199 return RewriteMessageExpr(MessExpr);
4200 }
4201
4202 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4203 return RewriteObjCTryStmt(StmtTry);
4204
4205 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4206 return RewriteObjCSynchronizedStmt(StmtTry);
4207
4208 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4209 return RewriteObjCThrowStmt(StmtThrow);
4210
4211 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4212 return RewriteObjCProtocolExpr(ProtocolExp);
4213
4214 if (ObjCForCollectionStmt *StmtForCollection =
4215 dyn_cast<ObjCForCollectionStmt>(S))
4216 return RewriteObjCForCollectionStmt(StmtForCollection,
4217 OrigStmtRange.getEnd());
4218 if (BreakStmt *StmtBreakStmt =
4219 dyn_cast<BreakStmt>(S))
4220 return RewriteBreakStmt(StmtBreakStmt);
4221 if (ContinueStmt *StmtContinueStmt =
4222 dyn_cast<ContinueStmt>(S))
4223 return RewriteContinueStmt(StmtContinueStmt);
4224
4225 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4226 // and cast exprs.
4227 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4228 // FIXME: What we're doing here is modifying the type-specifier that
4229 // precedes the first Decl. In the future the DeclGroup should have
4230 // a separate type-specifier that we can rewrite.
4231 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4232
4233 // Blocks rewrite rules.
4234 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4235 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004236 ScopedDecl *SD = *DI;
4237 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4238 if (isBlockPointerType(ND->getType()))
4239 RewriteBlockPointerDecl(ND);
4240 else if (ND->getType()->isFunctionPointerType())
4241 CheckFunctionPointerDecl(ND->getType(), ND);
4242 }
4243 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4244 if (isBlockPointerType(TD->getUnderlyingType()))
4245 RewriteBlockPointerDecl(TD);
4246 else if (TD->getUnderlyingType()->isFunctionPointerType())
4247 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4248 }
4249 }
4250 }
4251
4252 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4253 RewriteObjCQualifiedInterfaceTypes(CE);
4254
4255 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4256 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4257 assert(!Stmts.empty() && "Statement stack is empty");
4258 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4259 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4260 && "Statement stack mismatch");
4261 Stmts.pop_back();
4262 }
4263 // Handle blocks rewriting.
4264 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4265 if (BDRE->isByRef())
4266 RewriteBlockDeclRefExpr(BDRE);
4267 }
4268 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004269 if (CE->getCallee()->getType()->isBlockPointerType()) {
4270 Stmt *BlockCall = SynthesizeBlockCall(CE);
4271 ReplaceStmt(S, BlockCall);
4272 return BlockCall;
4273 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004274 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004275 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004276 RewriteCastExpr(CE);
4277 }
4278#if 0
4279 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4280 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4281 // Get the new text.
4282 std::string SStr;
4283 llvm::raw_string_ostream Buf(SStr);
4284 Replacement->printPretty(Buf);
4285 const std::string &Str = Buf.str();
4286
4287 printf("CAST = %s\n", &Str[0]);
4288 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4289 delete S;
4290 return Replacement;
4291 }
4292#endif
4293 // Return this stmt unmodified.
4294 return S;
4295}
4296
4297/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4298/// main file of the input.
4299void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4300 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4301 // Since function prototypes don't have ParmDecl's, we check the function
4302 // prototype. This enables us to rewrite function declarations and
4303 // definitions using the same code.
4304 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4305
4306 if (Stmt *Body = FD->getBody()) {
4307 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004308 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004309 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004310 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004311 CurrentBody = 0;
4312 if (PropParentMap) {
4313 delete PropParentMap;
4314 PropParentMap = 0;
4315 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004316 // This synthesizes and inserts the block "impl" struct, invoke function,
4317 // and any copy/dispose helper functions.
4318 InsertBlockLiteralsWithinFunction(FD);
4319 CurFunctionDef = 0;
4320 }
4321 return;
4322 }
4323 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4324 if (Stmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004325 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004326 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004327 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004328 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004329 CurrentBody = 0;
4330 if (PropParentMap) {
4331 delete PropParentMap;
4332 PropParentMap = 0;
4333 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004334 InsertBlockLiteralsWithinMethod(MD);
4335 CurMethodDef = 0;
4336 }
4337 }
4338 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4339 ClassImplementation.push_back(CI);
4340 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4341 CategoryImplementation.push_back(CI);
4342 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4343 RewriteForwardClassDecl(CD);
4344 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4345 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004346 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004347 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004348 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004349 CheckFunctionPointerDecl(VD->getType(), VD);
4350 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004351 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004352 RewriteCastExpr(CE);
4353 }
4354 }
4355 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004356 if (VD->getInit()) {
4357 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004358 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004359 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004360 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004361 CurrentBody = 0;
4362 if (PropParentMap) {
4363 delete PropParentMap;
4364 PropParentMap = 0;
4365 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004366 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004367 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004368 GlobalVarDecl = 0;
4369
4370 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004371 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004372 RewriteCastExpr(CE);
4373 }
4374 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004375 return;
4376 }
4377 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4378 if (isBlockPointerType(TD->getUnderlyingType()))
4379 RewriteBlockPointerDecl(TD);
4380 else if (TD->getUnderlyingType()->isFunctionPointerType())
4381 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4382 return;
4383 }
4384 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4385 if (RD->isDefinition()) {
4386 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4387 e = RD->field_end(); i != e; ++i) {
4388 FieldDecl *FD = *i;
4389 if (isBlockPointerType(FD->getType()))
4390 RewriteBlockPointerDecl(FD);
4391 }
4392 }
4393 return;
4394 }
4395 // Nothing yet.
4396}
4397
4398void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4399 // Get the top-level buffer that this corresponds to.
4400
4401 // Rewrite tabs if we care.
4402 //RewriteTabs();
4403
4404 if (Diags.hasErrorOccurred())
4405 return;
4406
4407 // Create the output file.
4408
4409 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4410 llvm::raw_ostream *OutFile;
4411 if (OutFileName == "-") {
4412 OutFile = &llvm::outs();
4413 } else if (!OutFileName.empty()) {
4414 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004415 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004416 OwnedStream.reset(OutFile);
4417 } else if (InFileName == "-") {
4418 OutFile = &llvm::outs();
4419 } else {
4420 llvm::sys::Path Path(InFileName);
4421 Path.eraseSuffix();
4422 Path.appendSuffix("cpp");
4423 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004424 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004425 OwnedStream.reset(OutFile);
4426 }
4427
4428 RewriteInclude();
4429
4430 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4431 Preamble.c_str(), Preamble.size(), false);
4432
Steve Naroff0aab7962008-11-14 14:10:01 +00004433 if (ClassImplementation.size() || CategoryImplementation.size())
4434 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004435
4436 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4437 // we are done.
4438 if (const RewriteBuffer *RewriteBuf =
4439 Rewrite.getRewriteBufferFor(MainFileID)) {
4440 //printf("Changed:\n");
4441 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4442 } else {
4443 fprintf(stderr, "No changes\n");
4444 }
Steve Narofface66252008-11-13 20:07:04 +00004445
Steve Naroff0aab7962008-11-14 14:10:01 +00004446 if (ClassImplementation.size() || CategoryImplementation.size()) {
4447 // Rewrite Objective-c meta data*
4448 std::string ResultStr;
4449 SynthesizeMetaDataIntoBuffer(ResultStr);
4450 // Emit metadata.
4451 *OutFile << ResultStr;
4452 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004453 OutFile->flush();
4454}
4455