blob: e071cb904ed979689b6dc28069d63606b6030e25 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000019#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000020#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000021#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000022#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000023#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000024#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000025#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000026#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000027#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000028#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000029#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000031#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000032using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000033using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034
Steve Naroff0113c9d2008-01-28 21:34:52 +000035static llvm::cl::opt<bool>
36SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
37 llvm::cl::desc("Silence ObjC rewriting warnings"));
38
Chris Lattner77cd2a02007-10-11 00:43:27 +000039namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000040 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000041 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000042 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000043 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000044 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000045 unsigned TryFinallyContainsReturnDiag;
46
Chris Lattner01c57482007-10-17 22:35:30 +000047 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000048 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000049 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000050 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000051 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000052 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000053
Ted Kremeneka526c5c2008-01-07 19:49:32 +000054 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
55 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
56 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000057 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000058 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
59 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000060 llvm::SmallVector<Stmt *, 32> Stmts;
61 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000062
Steve Naroffd82a9ab2008-03-15 00:55:56 +000063 unsigned NumObjCStringLiterals;
64
Steve Naroffebf2b562007-10-23 23:50:29 +000065 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000066 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000067 FunctionDecl *MsgSendStretFunctionDecl;
68 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000069 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000070 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000071 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000072 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000073 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000074 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000075 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000076
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000078 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000079 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000080
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000081 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000082 int BcLabelCount;
83
Steve Naroff874e2322007-11-15 10:28:18 +000084 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000085 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000086 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000087 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000088
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000089 // Needed for header files being rewritten
90 bool IsHeader;
91
Steve Naroffa7b402d2008-03-28 22:26:09 +000092 std::string InFileName;
93 std::string OutFileName;
94
Steve Naroffba92b2e2008-03-27 22:29:16 +000095 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000096
97 // Block expressions.
98 llvm::SmallVector<BlockExpr *, 32> Blocks;
99 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
100 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +0000101
Steve Naroff54055232008-10-27 17:20:55 +0000102 // Block related declarations.
103 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
104 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
105 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
106
107 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
108
Steve Naroffc77a6362008-12-04 16:24:46 +0000109 // This maps a property to it's assignment statement.
110 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000111 // This maps a property to it's synthesied message expression.
112 // This allows us to rewrite chained getters (e.g. o.a.b.c).
113 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
114
Steve Naroff4c3580e2008-12-04 23:50:32 +0000115 // This maps an original source AST to it's rewritten form. This allows
116 // us to avoid rewriting the same node twice (which is very uncommon).
117 // This is needed to support some of the exotic property rewriting.
118 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000119
Steve Naroff54055232008-10-27 17:20:55 +0000120 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000121 VarDecl *GlobalVarDecl;
122
Steve Naroffb619d952008-12-09 12:56:34 +0000123 bool DisableReplaceStmt;
124
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000125 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000126 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000127 virtual void Initialize(ASTContext &context);
128
129 virtual void InitializeTU(TranslationUnit &TU) {
130 TU.SetOwnsDecls(false);
131 Initialize(TU.getContext());
132 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000133
Chris Lattner8a12c272007-10-11 18:38:32 +0000134
Chris Lattnerf04da132007-10-24 17:06:59 +0000135 // Top Level Driver code.
136 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000137 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000138 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000139 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000140
141 ~RewriteObjC() {}
142
143 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000144
145 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000146 Stmt *ReplacingStmt = ReplacedNodes[Old];
147
148 if (ReplacingStmt)
149 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000150
Steve Naroffb619d952008-12-09 12:56:34 +0000151 if (DisableReplaceStmt)
152 return; // Used when rewriting the assignment of a property setter.
153
Steve Naroff4c3580e2008-12-04 23:50:32 +0000154 // If replacement succeeded or warning disabled return with no warning.
155 if (!Rewrite.ReplaceStmt(Old, New)) {
156 ReplacedNodes[Old] = New;
157 return;
158 }
159 if (SilenceRewriteMacroWarning)
160 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000161 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
162 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000163 }
Steve Naroffb619d952008-12-09 12:56:34 +0000164
165 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
166 // Measaure the old text.
167 int Size = Rewrite.getRangeSize(SrcRange);
168 if (Size == -1) {
169 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
170 << Old->getSourceRange();
171 return;
172 }
173 // Get the new text.
174 std::string SStr;
175 llvm::raw_string_ostream S(SStr);
176 New->printPretty(S);
177 const std::string &Str = S.str();
178
179 // If replacement succeeded or warning disabled return with no warning.
180 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
188 }
189
Steve Naroffba92b2e2008-03-27 22:29:16 +0000190 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
191 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000192 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000193 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000194 SilenceRewriteMacroWarning)
195 return;
196
197 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
198 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000199
Chris Lattneraadaf782008-01-31 19:51:04 +0000200 void RemoveText(SourceLocation Loc, unsigned StrLen) {
201 // If removal succeeded or warning disabled return with no warning.
202 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
203 return;
204
205 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
206 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000207
Chris Lattneraadaf782008-01-31 19:51:04 +0000208 void ReplaceText(SourceLocation Start, unsigned OrigLength,
209 const char *NewStr, unsigned NewLength) {
210 // If removal succeeded or warning disabled return with no warning.
211 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
212 SilenceRewriteMacroWarning)
213 return;
214
215 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
216 }
217
Chris Lattnerf04da132007-10-24 17:06:59 +0000218 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000219 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000220 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000221 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000222 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000223 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
224 ObjCImplementationDecl *IMD,
225 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000227 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000228 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
229 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
230 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
231 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
232 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000233 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000234 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000235 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000236 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000237 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000238 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000239 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000240 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000241 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000242
Chris Lattnerf04da132007-10-24 17:06:59 +0000243 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000244 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000245 void CollectPropertySetters(Stmt *S);
246
Steve Naroff8599e7a2008-12-08 16:43:47 +0000247 Stmt *CurrentBody;
248 ParentMap *PropParentMap; // created lazily.
249
Chris Lattnere64b7772007-10-24 16:57:36 +0000250 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000251 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000252 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffb619d952008-12-09 12:56:34 +0000253 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
254 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000255 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000256 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000257 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000258 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000259 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000261 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000262 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
263 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
264 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000265 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
266 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000267 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
268 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000269 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000270 Stmt *RewriteBreakStmt(BreakStmt *S);
271 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000272 void SynthCountByEnumWithState(std::string &buf);
273
Steve Naroff09b266e2007-10-30 23:14:51 +0000274 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000275 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000276 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000277 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000278 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000279 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000280 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000281 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000282 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000283 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000284
Chris Lattnerf04da132007-10-24 17:06:59 +0000285 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000287 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000288
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000290 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000291
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000292 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
293 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000294 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000295 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000296 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000297 const char *ClassName,
298 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000299
Chris Lattner780f3292008-07-21 21:32:27 +0000300 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
301 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000302 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000303 const char *ClassName,
304 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000306 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
308 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000309 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000310 void RewriteImplementations();
311 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000312
313 // Block rewriting.
314 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
315 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
316
317 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
318 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
319
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000320 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000321 void RewriteBlockCall(CallExpr *Exp);
322 void RewriteBlockPointerDecl(NamedDecl *VD);
323 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
324 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
325
326 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
327 const char *funcName, std::string Tag);
328 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
329 const char *funcName, std::string Tag);
330 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
331 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000332 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000333 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
334 const char *FunName);
335
336 void CollectBlockDeclRefInfo(BlockExpr *Exp);
337 void GetBlockCallExprs(Stmt *S);
338 void GetBlockDeclRefExprs(Stmt *S);
339
340 // We avoid calling Type::isBlockPointerType(), since it operates on the
341 // canonical type. We only care if the top-level type is a closure pointer.
342 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
343
344 // FIXME: This predicate seems like it would be useful to add to ASTContext.
345 bool isObjCType(QualType T) {
346 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
347 return false;
348
349 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
350
351 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
352 OCT == Context->getCanonicalType(Context->getObjCClassType()))
353 return true;
354
355 if (const PointerType *PT = OCT->getAsPointerType()) {
356 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
357 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
358 return true;
359 }
360 return false;
361 }
362 bool PointerTypeTakesAnyBlockArguments(QualType QT);
363 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000364 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000365
366 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000367 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000368 };
369}
370
Steve Naroff54055232008-10-27 17:20:55 +0000371void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
372 NamedDecl *D) {
373 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
374 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
375 E = fproto->arg_type_end(); I && (I != E); ++I)
376 if (isBlockPointerType(*I)) {
377 // All the args are checked/rewritten. Don't call twice!
378 RewriteBlockPointerDecl(D);
379 break;
380 }
381 }
382}
383
384void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
385 const PointerType *PT = funcType->getAsPointerType();
386 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
387 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
388}
389
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000390static bool IsHeaderFile(const std::string &Filename) {
391 std::string::size_type DotPos = Filename.rfind('.');
392
393 if (DotPos == std::string::npos) {
394 // no file extension
395 return false;
396 }
397
398 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
399 // C header: .h
400 // C++ header: .hh or .H;
401 return Ext == "h" || Ext == "hh" || Ext == "H";
402}
403
Steve Naroffb29b4272008-04-14 22:03:09 +0000404RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000405 Diagnostic &D, const LangOptions &LOpts)
406 : Diags(D), LangOpts(LOpts) {
407 IsHeader = IsHeaderFile(inFile);
408 InFileName = inFile;
409 OutFileName = outFile;
410 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
411 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000412 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
413 "rewriter doesn't support user-specified control flow semantics for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000414}
415
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000416ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000417 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000418 Diagnostic &Diags,
419 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000420 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000421}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000422
Steve Naroffb29b4272008-04-14 22:03:09 +0000423void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000424 Context = &context;
425 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000426 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000427 MsgSendFunctionDecl = 0;
428 MsgSendSuperFunctionDecl = 0;
429 MsgSendStretFunctionDecl = 0;
430 MsgSendSuperStretFunctionDecl = 0;
431 MsgSendFpretFunctionDecl = 0;
432 GetClassFunctionDecl = 0;
433 GetMetaClassFunctionDecl = 0;
434 SelGetUidFunctionDecl = 0;
435 CFStringFunctionDecl = 0;
436 GetProtocolFunctionDecl = 0;
437 ConstantStringClassReference = 0;
438 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000439 CurMethodDef = 0;
440 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000441 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000442 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000443 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000444 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000445 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000446 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000447 PropParentMap = 0;
448 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000449 DisableReplaceStmt = false;
450
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000451 // Get the ID and start/end of the main file.
452 MainFileID = SM->getMainFileID();
453 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
454 MainFileStart = MainBuf->getBufferStart();
455 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000456
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000457 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000458
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000459 // declaring objc_selector outside the parameter list removes a silly
460 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000461 if (IsHeader)
462 Preamble = "#pragma once\n";
463 Preamble += "struct objc_selector; struct objc_class;\n";
464 Preamble += "#ifndef OBJC_SUPER\n";
465 Preamble += "struct objc_super { struct objc_object *object; ";
466 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000467 if (LangOpts.Microsoft) {
468 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000469 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
470 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000471 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000472 Preamble += "};\n";
473 Preamble += "#define OBJC_SUPER\n";
474 Preamble += "#endif\n";
475 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
476 Preamble += "typedef struct objc_object Protocol;\n";
477 Preamble += "#define _REWRITER_typedef_Protocol\n";
478 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000479 if (LangOpts.Microsoft) {
480 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
481 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
482 } else
483 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
484 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000485 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000486 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000487 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000488 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000489 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000490 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000491 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000492 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000493 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000494 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000495 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000496 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000497 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000498 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
499 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
500 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
501 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
502 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000503 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000504 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000505 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
506 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
507 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000508 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
509 Preamble += "struct __objcFastEnumerationState {\n\t";
510 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000511 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000512 Preamble += "unsigned long *mutationsPtr;\n\t";
513 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000514 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000515 Preamble += "#define __FASTENUMERATIONSTATE\n";
516 Preamble += "#endif\n";
517 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
518 Preamble += "struct __NSConstantStringImpl {\n";
519 Preamble += " int *isa;\n";
520 Preamble += " int flags;\n";
521 Preamble += " char *str;\n";
522 Preamble += " long length;\n";
523 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000524 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
525 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
526 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000527 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000528 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000529 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
530 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000531 // Blocks preamble.
532 Preamble += "#ifndef BLOCK_IMPL\n";
533 Preamble += "#define BLOCK_IMPL\n";
534 Preamble += "struct __block_impl {\n";
535 Preamble += " void *isa;\n";
536 Preamble += " int Flags;\n";
537 Preamble += " int Size;\n";
538 Preamble += " void *FuncPtr;\n";
539 Preamble += "};\n";
540 Preamble += "enum {\n";
541 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
542 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
543 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000544 Preamble += "// Runtime copy/destroy helper functions\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000545 Preamble += "__OBJC_RW_STATICIMPORT void _Block_copy_assign(void *, void *);\n";
546 Preamble += "__OBJC_RW_STATICIMPORT void _Block_byref_assign_copy(void *, void *);\n";
547 Preamble += "__OBJC_RW_STATICIMPORT void _Block_destroy(void *);\n";
548 Preamble += "__OBJC_RW_STATICIMPORT void _Block_byref_release(void *);\n";
549 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock;\n";
550 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000551 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000552 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000553 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
554 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000555 Preamble += "#define __attribute__(X)\n";
556 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000557}
558
559
Chris Lattnerf04da132007-10-24 17:06:59 +0000560//===----------------------------------------------------------------------===//
561// Top Level Driver Code
562//===----------------------------------------------------------------------===//
563
Steve Naroffb29b4272008-04-14 22:03:09 +0000564void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000565 // Two cases: either the decl could be in the main file, or it could be in a
566 // #included file. If the former, rewrite it now. If the later, check to see
567 // if we rewrote the #include/#import.
568 SourceLocation Loc = D->getLocation();
569 Loc = SM->getLogicalLoc(Loc);
570
571 // If this is for a builtin, ignore it.
572 if (Loc.isInvalid()) return;
573
Steve Naroffebf2b562007-10-23 23:50:29 +0000574 // Look for built-in declarations that we need to refer during the rewrite.
575 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000576 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000577 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000578 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000579 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000580 ConstantStringClassReference = FVD;
581 return;
582 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000583 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000584 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000585 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000586 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000587 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000588 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000589 } else if (ObjCForwardProtocolDecl *FP =
590 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000591 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000592 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000593 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000594 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000595 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000596}
597
Chris Lattnerf04da132007-10-24 17:06:59 +0000598//===----------------------------------------------------------------------===//
599// Syntactic (non-AST) Rewriting Code
600//===----------------------------------------------------------------------===//
601
Steve Naroffb29b4272008-04-14 22:03:09 +0000602void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000603 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
604 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
605 const char *MainBufStart = MainBuf.first;
606 const char *MainBufEnd = MainBuf.second;
607 size_t ImportLen = strlen("import");
608 size_t IncludeLen = strlen("include");
609
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000610 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000611 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
612 if (*BufPtr == '#') {
613 if (++BufPtr == MainBufEnd)
614 return;
615 while (*BufPtr == ' ' || *BufPtr == '\t')
616 if (++BufPtr == MainBufEnd)
617 return;
618 if (!strncmp(BufPtr, "import", ImportLen)) {
619 // replace import with include
620 SourceLocation ImportLoc =
621 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000622 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000623 BufPtr += ImportLen;
624 }
625 }
626 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000627}
628
Steve Naroffb29b4272008-04-14 22:03:09 +0000629void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000630 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
631 const char *MainBufStart = MainBuf.first;
632 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000633
Chris Lattnerf04da132007-10-24 17:06:59 +0000634 // Loop over the whole file, looking for tabs.
635 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
636 if (*BufPtr != '\t')
637 continue;
638
639 // Okay, we found a tab. This tab will turn into at least one character,
640 // but it depends on which 'virtual column' it is in. Compute that now.
641 unsigned VCol = 0;
642 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
643 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
644 ++VCol;
645
646 // Okay, now that we know the virtual column, we know how many spaces to
647 // insert. We assume 8-character tab-stops.
648 unsigned Spaces = 8-(VCol & 7);
649
650 // Get the location of the tab.
651 SourceLocation TabLoc =
652 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
653
654 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000655 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000656 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000657}
658
Steve Naroffeb0646c2008-12-02 15:48:25 +0000659static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
660 ObjCIvarDecl *OID) {
661 std::string S;
662 S = "((struct ";
663 S += ClassDecl->getIdentifier()->getName();
664 S += "_IMPL *)self)->";
665 S += OID->getNameAsCString();
666 return S;
667}
668
Steve Naroffa0876e82008-12-02 17:36:43 +0000669void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
670 ObjCImplementationDecl *IMD,
671 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000672 SourceLocation startLoc = PID->getLocStart();
673 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000674 const char *startBuf = SM->getCharacterData(startLoc);
675 assert((*startBuf == '@') && "bogus @synthesize location");
676 const char *semiBuf = strchr(startBuf, ';');
677 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
678 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
679
680 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
681 return; // FIXME: is this correct?
682
683 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000684 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000685 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000686 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000687
688 if (!OID)
689 return;
690
691 std::string Getr;
692 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
693 Getr += "{ ";
694 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000695 // FIXME: deal with code generation implications for various property
696 // attributes (copy, retain, nonatomic).
697 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000698 Getr += "return " + getIvarAccessString(ClassDecl, OID);
699 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000700 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000701
702 // Add the rewritten getter to trigger meta data generation. An alternate, and
703 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
704 // with properties explicitly. The following addInstanceMethod() required far
705 // less code change (and actually models what the rewriter is doing).
706 if (IMD)
707 IMD->addInstanceMethod(PD->getGetterMethodDecl());
708 else
709 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000710
711 if (PD->isReadOnly())
712 return;
713
714 // Generate the 'setter' function.
715 std::string Setr;
716 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000717 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000718 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000719 // FIXME: deal with code generation implications for various property
720 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000721 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000722 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000723 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000724 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000725 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000726
727 // Add the rewritten setter to trigger meta data generation.
728 if (IMD)
729 IMD->addInstanceMethod(PD->getSetterMethodDecl());
730 else
731 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000732}
Chris Lattner8a12c272007-10-11 18:38:32 +0000733
Steve Naroffb29b4272008-04-14 22:03:09 +0000734void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000735 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000736 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000737
738 // Get the start location and compute the semi location.
739 SourceLocation startLoc = ClassDecl->getLocation();
740 const char *startBuf = SM->getCharacterData(startLoc);
741 const char *semiPtr = strchr(startBuf, ';');
742
743 // Translate to typedef's that forward reference structs with the same name
744 // as the class. As a convenience, we include the original declaration
745 // as a comment.
746 std::string typedefString;
747 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000748 typedefString.append(startBuf, semiPtr-startBuf+1);
749 typedefString += "\n";
750 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000751 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000752 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000753 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000754 typedefString += "\n";
755 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000756 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000757 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000758 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000759 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000760 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000761 }
762
763 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000764 ReplaceText(startLoc, semiPtr-startBuf+1,
765 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000766}
767
Steve Naroffb29b4272008-04-14 22:03:09 +0000768void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000769 SourceLocation LocStart = Method->getLocStart();
770 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000771
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000772 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000773 InsertText(LocStart, "#if 0\n", 6);
774 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000775 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000776 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000777 }
778}
779
Steve Naroffb29b4272008-04-14 22:03:09 +0000780void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000781{
Chris Lattner55d13b42008-03-16 21:23:50 +0000782 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000783 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000784 SourceLocation Loc = Property->getLocation();
785
Chris Lattneraadaf782008-01-31 19:51:04 +0000786 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000787
788 // FIXME: handle properties that are declared across multiple lines.
789 }
790}
791
Steve Naroffb29b4272008-04-14 22:03:09 +0000792void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000793 SourceLocation LocStart = CatDecl->getLocStart();
794
795 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000796 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000797
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000798 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000799 E = CatDecl->instmeth_end(); I != E; ++I)
800 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000801 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000802 E = CatDecl->classmeth_end(); I != E; ++I)
803 RewriteMethodDeclaration(*I);
804
Steve Naroff423cb562007-10-30 13:30:57 +0000805 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000806 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000807}
808
Steve Naroffb29b4272008-04-14 22:03:09 +0000809void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000810 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000811
Steve Naroff752d6ef2007-10-30 16:42:30 +0000812 SourceLocation LocStart = PDecl->getLocStart();
813
814 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000815 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000816
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000817 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000818 E = PDecl->instmeth_end(); I != E; ++I)
819 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000820 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000821 E = PDecl->classmeth_end(); I != E; ++I)
822 RewriteMethodDeclaration(*I);
823
Steve Naroff752d6ef2007-10-30 16:42:30 +0000824 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000825 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000826 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000827
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000828 // Must comment out @optional/@required
829 const char *startBuf = SM->getCharacterData(LocStart);
830 const char *endBuf = SM->getCharacterData(LocEnd);
831 for (const char *p = startBuf; p < endBuf; p++) {
832 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
833 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000834 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000835 ReplaceText(OptionalLoc, strlen("@optional"),
836 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000837
838 }
839 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
840 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000841 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000842 ReplaceText(OptionalLoc, strlen("@required"),
843 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000844
845 }
846 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000847}
848
Steve Naroffb29b4272008-04-14 22:03:09 +0000849void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000850 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000851 if (LocStart.isInvalid())
852 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000853 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000854 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000855}
856
Steve Naroffb29b4272008-04-14 22:03:09 +0000857void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000858 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000859 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000860 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000861 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000862 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000863 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000864 else if (OMD->getResultType()->isFunctionPointerType() ||
865 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000866 // needs special handling, since pointer-to-functions have special
867 // syntax (where a decaration models use).
868 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000869 QualType PointeeTy;
870 if (const PointerType* PT = retType->getAsPointerType())
871 PointeeTy = PT->getPointeeType();
872 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
873 PointeeTy = BPT->getPointeeType();
874 if ((FPRetType = PointeeTy->getAsFunctionType())) {
875 ResultStr += FPRetType->getResultType().getAsString();
876 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000877 }
878 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000879 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000880 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000881
882 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000883 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000884
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000885 if (OMD->isInstance())
886 NameStr += "_I_";
887 else
888 NameStr += "_C_";
889
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000890 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000891 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000892
893 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000894 if (ObjCCategoryImplDecl *CID =
895 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000896 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000897 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000898 }
Steve Naroff563b8282008-04-04 22:23:44 +0000899 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000900 {
901 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000902 int len = selString.size();
903 for (int i = 0; i < len; i++)
904 if (selString[i] == ':')
905 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000906 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000907 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000908 // Remember this name for metadata emission
909 MethodInternalNames[OMD] = NameStr;
910 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000911
912 // Rewrite arguments
913 ResultStr += "(";
914
915 // invisible arguments
916 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000917 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000918 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000919 if (!LangOpts.Microsoft) {
920 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
921 ResultStr += "struct ";
922 }
923 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000924 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000925 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000926 }
927 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000928 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000929
930 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000931 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000932 ResultStr += " _cmd";
933
934 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000935 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000936 ParmVarDecl *PDecl = OMD->getParamDecl(i);
937 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000938 if (PDecl->getType()->isObjCQualifiedIdType()) {
939 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000940 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000941 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000942 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000943 if (isBlockPointerType(PDecl->getType())) {
944 // Make sure we convert "t (^)(...)" to "t (*)(...)".
945 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
946 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
947 } else
948 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000949 ResultStr += Name;
950 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000951 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000952 if (OMD->isVariadic())
953 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000954 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000955
Steve Naroff76e429d2008-07-16 14:40:40 +0000956 if (FPRetType) {
957 ResultStr += ")"; // close the precedence "scope" for "*".
958
959 // Now, emit the argument types (if any).
960 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
961 ResultStr += "(";
962 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
963 if (i) ResultStr += ", ";
964 std::string ParamStr = FT->getArgType(i).getAsString();
965 ResultStr += ParamStr;
966 }
967 if (FT->isVariadic()) {
968 if (FT->getNumArgs()) ResultStr += ", ";
969 ResultStr += "...";
970 }
971 ResultStr += ")";
972 } else {
973 ResultStr += "()";
974 }
975 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000976}
Steve Naroffb29b4272008-04-14 22:03:09 +0000977void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000978 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
979 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000980
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000981 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000982 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000983 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000984 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000985
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000986 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000987 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
988 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000989 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000990 ObjCMethodDecl *OMD = *I;
991 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000992 SourceLocation LocStart = OMD->getLocStart();
993 SourceLocation LocEnd = OMD->getBody()->getLocStart();
994
995 const char *startBuf = SM->getCharacterData(LocStart);
996 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000997 ReplaceText(LocStart, endBuf-startBuf,
998 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000999 }
1000
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001001 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001002 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1003 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001004 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 ObjCMethodDecl *OMD = *I;
1006 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001007 SourceLocation LocStart = OMD->getLocStart();
1008 SourceLocation LocEnd = OMD->getBody()->getLocStart();
1009
1010 const char *startBuf = SM->getCharacterData(LocStart);
1011 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001012 ReplaceText(LocStart, endBuf-startBuf,
1013 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001014 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001015 for (ObjCCategoryImplDecl::propimpl_iterator
1016 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1017 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001018 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001019 }
1020
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001021 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001022 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001023 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001024 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001025}
1026
Steve Naroffb29b4272008-04-14 22:03:09 +00001027void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001028 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001029 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001030 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001031 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001032 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001033 ResultStr += "\n";
1034 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001035 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001036 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001037 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001038 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001039 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001040 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001041 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001042 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001043 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001044
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001045 RewriteProperties(ClassDecl->getNumPropertyDecl(),
1046 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001047 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001048 E = ClassDecl->instmeth_end(); I != E; ++I)
1049 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001050 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001051 E = ClassDecl->classmeth_end(); I != E; ++I)
1052 RewriteMethodDeclaration(*I);
1053
Steve Naroff2feac5e2007-10-30 03:43:13 +00001054 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001055 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001056}
1057
Steve Naroffb619d952008-12-09 12:56:34 +00001058Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1059 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001060 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1061 // This allows us to reuse all the fun and games in SynthMessageExpr().
1062 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1063 ObjCMessageExpr *MsgExpr;
1064 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1065 llvm::SmallVector<Expr *, 1> ExprVec;
1066 ExprVec.push_back(newStmt);
1067
Steve Naroff8599e7a2008-12-08 16:43:47 +00001068 Stmt *Receiver = PropRefExpr->getBase();
1069 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1070 if (PRE && PropGetters[PRE]) {
1071 // This allows us to handle chain/nested property getters.
1072 Receiver = PropGetters[PRE];
1073 }
1074 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001075 PDecl->getSetterName(), PDecl->getType(),
1076 PDecl->getSetterMethodDecl(),
1077 SourceLocation(), SourceLocation(),
1078 &ExprVec[0], 1);
1079 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1080
1081 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001082 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001083 //delete BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00001084 delete MsgExpr;
1085 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001086}
1087
Steve Naroffc77a6362008-12-04 16:24:46 +00001088Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001089 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1090 // This allows us to reuse all the fun and games in SynthMessageExpr().
1091 ObjCMessageExpr *MsgExpr;
1092 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1093
Steve Naroff8599e7a2008-12-08 16:43:47 +00001094 Stmt *Receiver = PropRefExpr->getBase();
1095
1096 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1097 if (PRE && PropGetters[PRE]) {
1098 // This allows us to handle chain/nested property getters.
1099 Receiver = PropGetters[PRE];
1100 }
1101 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001102 PDecl->getGetterName(), PDecl->getType(),
1103 PDecl->getGetterMethodDecl(),
1104 SourceLocation(), SourceLocation(),
1105 0, 0);
1106
Steve Naroff4c3580e2008-12-04 23:50:32 +00001107 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001108
1109 if (!PropParentMap)
1110 PropParentMap = new ParentMap(CurrentBody);
1111
1112 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1113 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1114 // We stash away the ReplacingStmt since actually doing the
1115 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1116 PropGetters[PropRefExpr] = ReplacingStmt;
1117 delete MsgExpr;
1118 return PropRefExpr; // return the original...
1119 } else {
1120 ReplaceStmt(PropRefExpr, ReplacingStmt);
1121 // delete PropRefExpr; elsewhere...
1122 delete MsgExpr;
1123 return ReplacingStmt;
1124 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001125}
1126
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001127Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1128 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001129 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001130 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001131 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001132 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1133 // lookup which class implements the instance variable.
1134 ObjCInterfaceDecl *clsDeclared = 0;
1135 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1136 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1137
1138 // Synthesize an explicit cast to gain access to the ivar.
1139 std::string RecName = clsDeclared->getIdentifier()->getName();
1140 RecName += "_IMPL";
1141 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001142 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001143 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001144 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1145 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001146 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001147 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001148 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001149 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1150 IV->getBase()->getLocEnd(),
1151 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001152 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001153 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001154 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1155 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001156 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001157 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001158 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001159 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001160
1161 ReplaceStmt(IV->getBase(), PE);
1162 // Cannot delete IV->getBase(), since PE points to it.
1163 // Replace the old base with the cast. This is important when doing
1164 // embedded rewrites. For example, [newInv->_container addObject:0].
1165 IV->setBase(PE);
1166 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001167 }
Steve Naroff84472a82008-04-18 21:55:08 +00001168 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001169 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1170
1171 // Explicit ivar refs need to have a cast inserted.
1172 // FIXME: consider sharing some of this code with the code above.
1173 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001174 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001175 // lookup which class implements the instance variable.
1176 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001177 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001178 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1179
1180 // Synthesize an explicit cast to gain access to the ivar.
1181 std::string RecName = clsDeclared->getIdentifier()->getName();
1182 RecName += "_IMPL";
1183 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001184 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001185 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001186 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1187 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001188 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001189 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001190 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001191 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1192 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001193 ReplaceStmt(IV->getBase(), PE);
1194 // Cannot delete IV->getBase(), since PE points to it.
1195 // Replace the old base with the cast. This is important when doing
1196 // embedded rewrites. For example, [newInv->_container addObject:0].
1197 IV->setBase(PE);
1198 return IV;
1199 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001200 }
Steve Naroff84472a82008-04-18 21:55:08 +00001201 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001202}
1203
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001204/// SynthCountByEnumWithState - To print:
1205/// ((unsigned int (*)
1206/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1207/// (void *)objc_msgSend)((id)l_collection,
1208/// sel_registerName(
1209/// "countByEnumeratingWithState:objects:count:"),
1210/// &enumState,
1211/// (id *)items, (unsigned int)16)
1212///
Steve Naroffb29b4272008-04-14 22:03:09 +00001213void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001214 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1215 "id *, unsigned int))(void *)objc_msgSend)";
1216 buf += "\n\t\t";
1217 buf += "((id)l_collection,\n\t\t";
1218 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1219 buf += "\n\t\t";
1220 buf += "&enumState, "
1221 "(id *)items, (unsigned int)16)";
1222}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001223
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001224/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1225/// statement to exit to its outer synthesized loop.
1226///
Steve Naroffb29b4272008-04-14 22:03:09 +00001227Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001228 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1229 return S;
1230 // replace break with goto __break_label
1231 std::string buf;
1232
1233 SourceLocation startLoc = S->getLocStart();
1234 buf = "goto __break_label_";
1235 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001236 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001237
1238 return 0;
1239}
1240
1241/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1242/// statement to continue with its inner synthesized loop.
1243///
Steve Naroffb29b4272008-04-14 22:03:09 +00001244Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001245 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1246 return S;
1247 // replace continue with goto __continue_label
1248 std::string buf;
1249
1250 SourceLocation startLoc = S->getLocStart();
1251 buf = "goto __continue_label_";
1252 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001253 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001254
1255 return 0;
1256}
1257
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001258/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001259/// It rewrites:
1260/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001261
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001262/// Into:
1263/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001264/// type elem;
1265/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001266/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001267/// id l_collection = (id)collection;
1268/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1269/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001270/// if (limit) {
1271/// unsigned long startMutations = *enumState.mutationsPtr;
1272/// do {
1273/// unsigned long counter = 0;
1274/// do {
1275/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001276/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001277/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001278/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001279/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001280/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001281/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1282/// objects:items count:16]);
1283/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001284/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001285/// }
1286/// else
1287/// elem = nil;
1288/// }
1289///
Steve Naroffb29b4272008-04-14 22:03:09 +00001290Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001291 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001292 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1293 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1294 "ObjCForCollectionStmt Statement stack mismatch");
1295 assert(!ObjCBcLabelNo.empty() &&
1296 "ObjCForCollectionStmt - Label No stack empty");
1297
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001298 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001299 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001300 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001301 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001302 std::string buf;
1303 buf = "\n{\n\t";
1304 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1305 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001306 ScopedDecl* D = DS->getSolitaryDecl();
1307 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001308 elementTypeAsString = ElementType.getAsString();
1309 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001310 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001311 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001312 buf += elementName;
1313 buf += ";\n\t";
1314 }
Chris Lattner06767512008-04-08 05:52:18 +00001315 else {
1316 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001317 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001318 elementTypeAsString
1319 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001320 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001321
1322 // struct __objcFastEnumerationState enumState = { 0 };
1323 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1324 // id items[16];
1325 buf += "id items[16];\n\t";
1326 // id l_collection = (id)
1327 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001328 // Find start location of 'collection' the hard way!
1329 const char *startCollectionBuf = startBuf;
1330 startCollectionBuf += 3; // skip 'for'
1331 startCollectionBuf = strchr(startCollectionBuf, '(');
1332 startCollectionBuf++; // skip '('
1333 // find 'in' and skip it.
1334 while (*startCollectionBuf != ' ' ||
1335 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1336 (*(startCollectionBuf+3) != ' ' &&
1337 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1338 startCollectionBuf++;
1339 startCollectionBuf += 3;
1340
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001341 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001342 ReplaceText(startLoc, startCollectionBuf - startBuf,
1343 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001344 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001345 SourceLocation rightParenLoc = S->getRParenLoc();
1346 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1347 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001348 buf = ";\n\t";
1349
1350 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1351 // objects:items count:16];
1352 // which is synthesized into:
1353 // unsigned int limit =
1354 // ((unsigned int (*)
1355 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1356 // (void *)objc_msgSend)((id)l_collection,
1357 // sel_registerName(
1358 // "countByEnumeratingWithState:objects:count:"),
1359 // (struct __objcFastEnumerationState *)&state,
1360 // (id *)items, (unsigned int)16);
1361 buf += "unsigned long limit =\n\t\t";
1362 SynthCountByEnumWithState(buf);
1363 buf += ";\n\t";
1364 /// if (limit) {
1365 /// unsigned long startMutations = *enumState.mutationsPtr;
1366 /// do {
1367 /// unsigned long counter = 0;
1368 /// do {
1369 /// if (startMutations != *enumState.mutationsPtr)
1370 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001371 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001372 buf += "if (limit) {\n\t";
1373 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1374 buf += "do {\n\t\t";
1375 buf += "unsigned long counter = 0;\n\t\t";
1376 buf += "do {\n\t\t\t";
1377 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1378 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1379 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001380 buf += " = (";
1381 buf += elementTypeAsString;
1382 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001383 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001384 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001385
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001386 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001387 /// } while (counter < limit);
1388 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1389 /// objects:items count:16]);
1390 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001391 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001392 /// }
1393 /// else
1394 /// elem = nil;
1395 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001396 ///
1397 buf = ";\n\t";
1398 buf += "__continue_label_";
1399 buf += utostr(ObjCBcLabelNo.back());
1400 buf += ": ;";
1401 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001402 buf += "} while (counter < limit);\n\t";
1403 buf += "} while (limit = ";
1404 SynthCountByEnumWithState(buf);
1405 buf += ");\n\t";
1406 buf += elementName;
1407 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001408 buf += "__break_label_";
1409 buf += utostr(ObjCBcLabelNo.back());
1410 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001411 buf += "}\n\t";
1412 buf += "else\n\t\t";
1413 buf += elementName;
1414 buf += " = nil;\n";
1415 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001416
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001417 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001418 if (isa<CompoundStmt>(S->getBody())) {
1419 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1420 InsertText(endBodyLoc, buf.c_str(), buf.size());
1421 } else {
1422 /* Need to treat single statements specially. For example:
1423 *
1424 * for (A *a in b) if (stuff()) break;
1425 * for (A *a in b) xxxyy;
1426 *
1427 * The following code simply scans ahead to the semi to find the actual end.
1428 */
1429 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1430 const char *semiBuf = strchr(stmtBuf, ';');
1431 assert(semiBuf && "Can't find ';'");
1432 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1433 InsertText(endBodyLoc, buf.c_str(), buf.size());
1434 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001435 Stmts.pop_back();
1436 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001437 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001438}
1439
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001440/// RewriteObjCSynchronizedStmt -
1441/// This routine rewrites @synchronized(expr) stmt;
1442/// into:
1443/// objc_sync_enter(expr);
1444/// @try stmt @finally { objc_sync_exit(expr); }
1445///
Steve Naroffb29b4272008-04-14 22:03:09 +00001446Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001447 // Get the start location and compute the semi location.
1448 SourceLocation startLoc = S->getLocStart();
1449 const char *startBuf = SM->getCharacterData(startLoc);
1450
1451 assert((*startBuf == '@') && "bogus @synchronized location");
1452
1453 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001454 buf = "objc_sync_enter((id)";
1455 const char *lparenBuf = startBuf;
1456 while (*lparenBuf != '(') lparenBuf++;
1457 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001458 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1459 // the sync expression is typically a message expression that's already
1460 // been rewritten! (which implies the SourceLocation's are invalid).
1461 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001462 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001463 while (*endBuf != ')') endBuf--;
1464 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001465 buf = ");\n";
1466 // declare a new scope with two variables, _stack and _rethrow.
1467 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1468 buf += "int buf[18/*32-bit i386*/];\n";
1469 buf += "char *pointers[4];} _stack;\n";
1470 buf += "id volatile _rethrow = 0;\n";
1471 buf += "objc_exception_try_enter(&_stack);\n";
1472 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001473 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001474 startLoc = S->getSynchBody()->getLocEnd();
1475 startBuf = SM->getCharacterData(startLoc);
1476
Steve Naroffc7089f12008-08-19 13:04:19 +00001477 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001478 SourceLocation lastCurlyLoc = startLoc;
1479 buf = "}\nelse {\n";
1480 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1481 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001482 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001483 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001484 S->getSynchExpr(),
1485 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001486 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001487 std::string syncExprBufS;
1488 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001489 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001490 buf += syncExprBuf.str();
1491 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001492 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1493 buf += "}\n";
1494 buf += "}";
1495
Chris Lattneraadaf782008-01-31 19:51:04 +00001496 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001497 return 0;
1498}
1499
Steve Naroff8c565152008-12-05 17:03:39 +00001500void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1501 // Perform a bottom up traversal of all children.
1502 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1503 CI != E; ++CI)
1504 if (*CI)
1505 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1506
1507 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1508 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1509 Diags.Report(Context->getFullLoc(S->getLocStart()),
1510 TryFinallyContainsReturnDiag);
1511 }
1512 return;
1513}
1514
Steve Naroffb29b4272008-04-14 22:03:09 +00001515Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001516 // Get the start location and compute the semi location.
1517 SourceLocation startLoc = S->getLocStart();
1518 const char *startBuf = SM->getCharacterData(startLoc);
1519
1520 assert((*startBuf == '@') && "bogus @try location");
1521
1522 std::string buf;
1523 // declare a new scope with two variables, _stack and _rethrow.
1524 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1525 buf += "int buf[18/*32-bit i386*/];\n";
1526 buf += "char *pointers[4];} _stack;\n";
1527 buf += "id volatile _rethrow = 0;\n";
1528 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001529 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001530
Chris Lattneraadaf782008-01-31 19:51:04 +00001531 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001532
1533 startLoc = S->getTryBody()->getLocEnd();
1534 startBuf = SM->getCharacterData(startLoc);
1535
1536 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001537
Steve Naroff75730982007-11-07 04:08:17 +00001538 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001539 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1540 if (catchList) {
1541 startLoc = startLoc.getFileLocWithOffset(1);
1542 buf = " /* @catch begin */ else {\n";
1543 buf += " id _caught = objc_exception_extract(&_stack);\n";
1544 buf += " objc_exception_try_enter (&_stack);\n";
1545 buf += " if (_setjmp(_stack.buf))\n";
1546 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1547 buf += " else { /* @catch continue */";
1548
1549 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001550 } else { /* no catch list */
1551 buf = "}\nelse {\n";
1552 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1553 buf += "}";
1554 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001555 }
Steve Naroff75730982007-11-07 04:08:17 +00001556 bool sawIdTypedCatch = false;
1557 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001558 while (catchList) {
1559 Stmt *catchStmt = catchList->getCatchParamStmt();
1560
1561 if (catchList == S->getCatchStmts())
1562 buf = "if ("; // we are generating code for the first catch clause
1563 else
1564 buf = "else if (";
1565 startLoc = catchList->getLocStart();
1566 startBuf = SM->getCharacterData(startLoc);
1567
1568 assert((*startBuf == '@') && "bogus @catch location");
1569
1570 const char *lParenLoc = strchr(startBuf, '(');
1571
Steve Naroffbe4b3332008-02-01 22:08:12 +00001572 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001573 // Now rewrite the body...
1574 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001575 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1576 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001577 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1578 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001579 assert((*bodyBuf == '{') && "bogus @catch body location");
1580
1581 buf += "1) { id _tmp = _caught;";
1582 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1583 buf.c_str(), buf.size());
1584 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001585 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001586 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001587 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001588 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001589 sawIdTypedCatch = true;
1590 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001591 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001592
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001593 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001594 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001595 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001596 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001597 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001598 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001599 }
1600 }
1601 // Now rewrite the body...
1602 lastCatchBody = catchList->getCatchBody();
1603 SourceLocation rParenLoc = catchList->getRParenLoc();
1604 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1605 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1606 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1607 assert((*rParenBuf == ')') && "bogus @catch paren location");
1608 assert((*bodyBuf == '{') && "bogus @catch body location");
1609
1610 buf = " = _caught;";
1611 // Here we replace ") {" with "= _caught;" (which initializes and
1612 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001613 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001614 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001615 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001616 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001617 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001618 catchList = catchList->getNextCatchStmt();
1619 }
1620 // Complete the catch list...
1621 if (lastCatchBody) {
1622 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001623 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1624 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001625
Steve Naroff378f47a2008-09-11 15:29:03 +00001626 // Insert the last (implicit) else clause *before* the right curly brace.
1627 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1628 buf = "} /* last catch end */\n";
1629 buf += "else {\n";
1630 buf += " _rethrow = _caught;\n";
1631 buf += " objc_exception_try_exit(&_stack);\n";
1632 buf += "} } /* @catch end */\n";
1633 if (!S->getFinallyStmt())
1634 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001635 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001636
1637 // Set lastCurlyLoc
1638 lastCurlyLoc = lastCatchBody->getLocEnd();
1639 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001640 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001641 startLoc = finalStmt->getLocStart();
1642 startBuf = SM->getCharacterData(startLoc);
1643 assert((*startBuf == '@') && "bogus @finally start");
1644
1645 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001646 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001647
1648 Stmt *body = finalStmt->getFinallyBody();
1649 SourceLocation startLoc = body->getLocStart();
1650 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001651 assert(*SM->getCharacterData(startLoc) == '{' &&
1652 "bogus @finally body location");
1653 assert(*SM->getCharacterData(endLoc) == '}' &&
1654 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001655
1656 startLoc = startLoc.getFileLocWithOffset(1);
1657 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001658 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001659 endLoc = endLoc.getFileLocWithOffset(-1);
1660 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001661 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001662
1663 // Set lastCurlyLoc
1664 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001665
1666 // Now check for any return/continue/go statements within the @try.
1667 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001668 } else { /* no finally clause - make sure we synthesize an implicit one */
1669 buf = "{ /* implicit finally clause */\n";
1670 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1671 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1672 buf += "}";
1673 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001674 }
1675 // Now emit the final closing curly brace...
1676 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1677 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001678 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001679 return 0;
1680}
1681
Steve Naroffb29b4272008-04-14 22:03:09 +00001682Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001683 return 0;
1684}
1685
Steve Naroffb29b4272008-04-14 22:03:09 +00001686Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001687 return 0;
1688}
1689
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001690// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001691// the throw expression is typically a message expression that's already
1692// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001693Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001694 // Get the start location and compute the semi location.
1695 SourceLocation startLoc = S->getLocStart();
1696 const char *startBuf = SM->getCharacterData(startLoc);
1697
1698 assert((*startBuf == '@') && "bogus @throw location");
1699
1700 std::string buf;
1701 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001702 if (S->getThrowExpr())
1703 buf = "objc_exception_throw(";
1704 else // add an implicit argument
1705 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001706
1707 // handle "@ throw" correctly.
1708 const char *wBuf = strchr(startBuf, 'w');
1709 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1710 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1711
Steve Naroff2bd03922007-11-07 15:32:26 +00001712 const char *semiBuf = strchr(startBuf, ';');
1713 assert((*semiBuf == ';') && "@throw: can't find ';'");
1714 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1715 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001716 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001717 return 0;
1718}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001719
Steve Naroffb29b4272008-04-14 22:03:09 +00001720Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001721 // Create a new string expression.
1722 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001723 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001724 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001725 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1726 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001727 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001728 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001729
Chris Lattner07506182007-11-30 22:53:43 +00001730 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001731 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001732 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001733}
1734
Steve Naroffb29b4272008-04-14 22:03:09 +00001735Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001736 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1737 // Create a call to sel_registerName("selName").
1738 llvm::SmallVector<Expr*, 8> SelExprs;
1739 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001740 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1741 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001742 false, argType, SourceLocation(),
1743 SourceLocation()));
1744 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1745 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001746 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001747 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001748 return SelExp;
1749}
1750
Steve Naroffb29b4272008-04-14 22:03:09 +00001751CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001752 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001753 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001754 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001755
1756 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001757 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001758
1759 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001760 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001761 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1762 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001763
1764 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001765
Steve Naroff934f2762007-10-24 22:48:43 +00001766 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1767}
1768
Steve Naroffd5255f52007-11-01 13:24:47 +00001769static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1770 const char *&startRef, const char *&endRef) {
1771 while (startBuf < endBuf) {
1772 if (*startBuf == '<')
1773 startRef = startBuf; // mark the start.
1774 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001775 if (startRef && *startRef == '<') {
1776 endRef = startBuf; // mark the end.
1777 return true;
1778 }
1779 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001780 }
1781 startBuf++;
1782 }
1783 return false;
1784}
1785
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001786static void scanToNextArgument(const char *&argRef) {
1787 int angle = 0;
1788 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1789 if (*argRef == '<')
1790 angle++;
1791 else if (*argRef == '>')
1792 angle--;
1793 argRef++;
1794 }
1795 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1796}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001797
Steve Naroffb29b4272008-04-14 22:03:09 +00001798bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001799
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001800 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001801 return true;
1802
Steve Naroffd5255f52007-11-01 13:24:47 +00001803 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001804 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001805 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001806 return true; // we have "Class <Protocol> *".
1807 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001808 return false;
1809}
1810
Steve Naroff4f95b752008-07-29 18:15:38 +00001811void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1812 QualType Type = E->getType();
1813 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001814 SourceLocation Loc, EndLoc;
1815
1816 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1817 Loc = ECE->getLParenLoc();
1818 EndLoc = ECE->getRParenLoc();
1819 } else {
1820 Loc = E->getLocStart();
1821 EndLoc = E->getLocEnd();
1822 }
1823 // This will defend against trying to rewrite synthesized expressions.
1824 if (Loc.isInvalid() || EndLoc.isInvalid())
1825 return;
1826
Steve Naroff4f95b752008-07-29 18:15:38 +00001827 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001828 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001829 const char *startRef = 0, *endRef = 0;
1830 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1831 // Get the locations of the startRef, endRef.
1832 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1833 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1834 // Comment out the protocol references.
1835 InsertText(LessLoc, "/*", 2);
1836 InsertText(GreaterLoc, "*/", 2);
1837 }
1838 }
1839}
1840
Steve Naroffb29b4272008-04-14 22:03:09 +00001841void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001842 SourceLocation Loc;
1843 QualType Type;
1844 const FunctionTypeProto *proto = 0;
1845 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1846 Loc = VD->getLocation();
1847 Type = VD->getType();
1848 }
1849 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1850 Loc = FD->getLocation();
1851 // Check for ObjC 'id' and class types that have been adorned with protocol
1852 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1853 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1854 assert(funcType && "missing function type");
1855 proto = dyn_cast<FunctionTypeProto>(funcType);
1856 if (!proto)
1857 return;
1858 Type = proto->getResultType();
1859 }
1860 else
1861 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001862
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001863 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001864 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001865
1866 const char *endBuf = SM->getCharacterData(Loc);
1867 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001868 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001869 startBuf--; // scan backward (from the decl location) for return type.
1870 const char *startRef = 0, *endRef = 0;
1871 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1872 // Get the locations of the startRef, endRef.
1873 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1874 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1875 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001876 InsertText(LessLoc, "/*", 2);
1877 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001878 }
1879 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001880 if (!proto)
1881 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001882 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001883 const char *startBuf = SM->getCharacterData(Loc);
1884 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001885 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1886 if (needToScanForQualifiers(proto->getArgType(i))) {
1887 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001888
Steve Naroffd5255f52007-11-01 13:24:47 +00001889 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001890 // scan forward (from the decl location) for argument types.
1891 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001892 const char *startRef = 0, *endRef = 0;
1893 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1894 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001895 SourceLocation LessLoc =
1896 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1897 SourceLocation GreaterLoc =
1898 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001899 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001900 InsertText(LessLoc, "/*", 2);
1901 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001902 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001903 startBuf = ++endBuf;
1904 }
1905 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001906 // If the function name is derived from a macro expansion, then the
1907 // argument buffer will not follow the name. Need to speak with Chris.
1908 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001909 startBuf++; // scan forward (from the decl location) for argument types.
1910 startBuf++;
1911 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001912 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001913}
1914
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001915// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001916void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001917 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1918 llvm::SmallVector<QualType, 16> ArgTys;
1919 ArgTys.push_back(Context->getPointerType(
1920 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001921 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001922 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001923 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001924 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001925 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001926 SelGetUidIdent, getFuncType,
1927 FunctionDecl::Extern, false, 0);
1928}
1929
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001930// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001931void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001932 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1933 llvm::SmallVector<QualType, 16> ArgTys;
1934 ArgTys.push_back(Context->getPointerType(
1935 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001936 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001937 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001938 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001939 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001940 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001941 SelGetProtoIdent, getFuncType,
1942 FunctionDecl::Extern, false, 0);
1943}
1944
Steve Naroffb29b4272008-04-14 22:03:09 +00001945void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001946 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001947 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001948 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001949 return;
1950 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001951 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001952}
1953
Steve Naroffc0a123c2008-03-11 17:37:02 +00001954// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001955void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001956 if (SuperContructorFunctionDecl)
1957 return;
1958 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1959 llvm::SmallVector<QualType, 16> ArgTys;
1960 QualType argT = Context->getObjCIdType();
1961 assert(!argT.isNull() && "Can't find 'id' type");
1962 ArgTys.push_back(argT);
1963 ArgTys.push_back(argT);
1964 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1965 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001966 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001967 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001968 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001969 msgSendIdent, msgSendType,
1970 FunctionDecl::Extern, false, 0);
1971}
1972
Steve Naroff09b266e2007-10-30 23:14:51 +00001973// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001974void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001975 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1976 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001977 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001978 assert(!argT.isNull() && "Can't find 'id' type");
1979 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001980 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001981 assert(!argT.isNull() && "Can't find 'SEL' type");
1982 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001983 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001984 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001985 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001986 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001987 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001988 msgSendIdent, msgSendType,
1989 FunctionDecl::Extern, false, 0);
1990}
1991
Steve Naroff874e2322007-11-15 10:28:18 +00001992// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001993void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001994 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1995 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001996 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001997 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001998 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001999 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2000 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2001 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002002 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002003 assert(!argT.isNull() && "Can't find 'SEL' type");
2004 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002005 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002006 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002007 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002008 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002009 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002010 msgSendIdent, msgSendType,
2011 FunctionDecl::Extern, false, 0);
2012}
2013
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002014// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002015void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002016 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2017 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002018 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002019 assert(!argT.isNull() && "Can't find 'id' type");
2020 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002021 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002022 assert(!argT.isNull() && "Can't find 'SEL' type");
2023 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002024 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002025 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002026 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002027 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002028 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002029 msgSendIdent, msgSendType,
2030 FunctionDecl::Extern, false, 0);
2031}
2032
2033// SynthMsgSendSuperStretFunctionDecl -
2034// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002035void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002036 IdentifierInfo *msgSendIdent =
2037 &Context->Idents.get("objc_msgSendSuper_stret");
2038 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002039 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002040 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002041 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002042 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2043 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2044 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002045 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002046 assert(!argT.isNull() && "Can't find 'SEL' type");
2047 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002048 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002049 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002050 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002051 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002052 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002053 msgSendIdent, msgSendType,
2054 FunctionDecl::Extern, false, 0);
2055}
2056
Steve Naroff1284db82008-05-08 22:02:18 +00002057// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002058void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002059 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2060 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002061 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002062 assert(!argT.isNull() && "Can't find 'id' type");
2063 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002064 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002065 assert(!argT.isNull() && "Can't find 'SEL' type");
2066 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002067 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002068 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002069 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002070 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002071 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002072 msgSendIdent, msgSendType,
2073 FunctionDecl::Extern, false, 0);
2074}
2075
Steve Naroff09b266e2007-10-30 23:14:51 +00002076// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002077void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002078 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2079 llvm::SmallVector<QualType, 16> ArgTys;
2080 ArgTys.push_back(Context->getPointerType(
2081 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002082 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002083 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002084 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002085 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002086 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002087 getClassIdent, getClassType,
2088 FunctionDecl::Extern, false, 0);
2089}
2090
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002091// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002092void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002093 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2094 llvm::SmallVector<QualType, 16> ArgTys;
2095 ArgTys.push_back(Context->getPointerType(
2096 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002097 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002098 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002099 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002100 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002101 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002102 getClassIdent, getClassType,
2103 FunctionDecl::Extern, false, 0);
2104}
2105
Steve Naroffb29b4272008-04-14 22:03:09 +00002106Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002107 QualType strType = getConstantStringStructType();
2108
2109 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002110
2111 std::string tmpName = InFileName;
2112 unsigned i;
2113 for (i=0; i < tmpName.length(); i++) {
2114 char c = tmpName.at(i);
2115 // replace any non alphanumeric characters with '_'.
2116 if (!isalpha(c) && (c < '0' || c > '9'))
2117 tmpName[i] = '_';
2118 }
2119 S += tmpName;
2120 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002121 S += utostr(NumObjCStringLiterals++);
2122
Steve Naroffba92b2e2008-03-27 22:29:16 +00002123 Preamble += "static __NSConstantStringImpl " + S;
2124 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2125 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002126 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002127 std::string prettyBufS;
2128 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002129 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002130 Preamble += prettyBuf.str();
2131 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002132 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002133 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002134
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002135 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002136 &Context->Idents.get(S.c_str()), strType,
2137 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002138 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2139 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2140 Context->getPointerType(DRE->getType()),
2141 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002142 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002143 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002144 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002145 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002146 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002147 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002148}
2149
Steve Naroffb29b4272008-04-14 22:03:09 +00002150ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002151 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002152 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002153
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002154 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2155 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002156 assert(PT);
2157 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2158 return IT->getDecl();
2159 }
2160 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002161}
2162
2163// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002164QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002165 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002166 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002167 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002168 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002169 QualType FieldTypes[2];
2170
2171 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002172 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002173 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002174 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002175
Steve Naroff874e2322007-11-15 10:28:18 +00002176 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002177 for (unsigned i = 0; i < 2; ++i) {
2178 SuperStructDecl->addDecl(*Context,
2179 FieldDecl::Create(*Context, SuperStructDecl,
2180 SourceLocation(), 0,
2181 FieldTypes[i], /*BitWidth=*/0,
2182 /*Mutable=*/false, 0),
2183 true);
2184 }
Steve Naroff874e2322007-11-15 10:28:18 +00002185
Douglas Gregor44b43212008-12-11 16:49:14 +00002186 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002187 }
2188 return Context->getTagDeclType(SuperStructDecl);
2189}
2190
Steve Naroffb29b4272008-04-14 22:03:09 +00002191QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002192 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002193 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002194 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002195 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002196 QualType FieldTypes[4];
2197
2198 // struct objc_object *receiver;
2199 FieldTypes[0] = Context->getObjCIdType();
2200 // int flags;
2201 FieldTypes[1] = Context->IntTy;
2202 // char *str;
2203 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2204 // long length;
2205 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002206
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002207 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002208 for (unsigned i = 0; i < 4; ++i) {
2209 ConstantStringDecl->addDecl(*Context,
2210 FieldDecl::Create(*Context,
2211 ConstantStringDecl,
2212 SourceLocation(), 0,
2213 FieldTypes[i],
2214 /*BitWidth=*/0,
2215 /*Mutable=*/true, 0),
2216 true);
2217 }
2218
2219 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002220 }
2221 return Context->getTagDeclType(ConstantStringDecl);
2222}
2223
Steve Naroffb29b4272008-04-14 22:03:09 +00002224Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002225 if (!SelGetUidFunctionDecl)
2226 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002227 if (!MsgSendFunctionDecl)
2228 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002229 if (!MsgSendSuperFunctionDecl)
2230 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002231 if (!MsgSendStretFunctionDecl)
2232 SynthMsgSendStretFunctionDecl();
2233 if (!MsgSendSuperStretFunctionDecl)
2234 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002235 if (!MsgSendFpretFunctionDecl)
2236 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002237 if (!GetClassFunctionDecl)
2238 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002239 if (!GetMetaClassFunctionDecl)
2240 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002241
Steve Naroff874e2322007-11-15 10:28:18 +00002242 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002243 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2244 // May need to use objc_msgSend_stret() as well.
2245 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002246 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002247 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002248 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002249 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002250 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002251 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002252 }
Steve Naroff874e2322007-11-15 10:28:18 +00002253
Steve Naroff934f2762007-10-24 22:48:43 +00002254 // Synthesize a call to objc_msgSend().
2255 llvm::SmallVector<Expr*, 8> MsgExprs;
2256 IdentifierInfo *clsName = Exp->getClassName();
2257
2258 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2259 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002260 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2261 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002262 if (!strcmp(clsName->getName(), "super")) {
2263 MsgSendFlavor = MsgSendSuperFunctionDecl;
2264 if (MsgSendStretFlavor)
2265 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2266 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2267
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002268 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002269 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002270
2271 llvm::SmallVector<Expr*, 4> InitExprs;
2272
2273 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002274 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002275 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002276 Context->getObjCIdType(),
2277 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002278 llvm::SmallVector<Expr*, 8> ClsExprs;
2279 QualType argType = Context->getPointerType(Context->CharTy);
2280 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2281 SuperDecl->getIdentifier()->getLength(),
2282 false, argType, SourceLocation(),
2283 SourceLocation()));
2284 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2285 &ClsExprs[0],
2286 ClsExprs.size());
2287 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002288 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002289 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002290 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002291 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002292 // struct objc_super
2293 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002294 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002295
Steve Naroff23f41272008-03-11 18:14:26 +00002296 if (LangOpts.Microsoft) {
2297 SynthSuperContructorFunctionDecl();
2298 // Simulate a contructor call...
2299 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2300 superType, SourceLocation());
2301 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2302 superType, SourceLocation());
2303 } else {
2304 // (struct objc_super) { <exprs from above> }
2305 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2306 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002307 SourceLocation(), false);
2308 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2309 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002310 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002311 // struct objc_super *
2312 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2313 Context->getPointerType(SuperRep->getType()),
2314 SourceLocation());
2315 MsgExprs.push_back(Unop);
2316 } else {
2317 llvm::SmallVector<Expr*, 8> ClsExprs;
2318 QualType argType = Context->getPointerType(Context->CharTy);
2319 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2320 clsName->getLength(),
2321 false, argType, SourceLocation(),
2322 SourceLocation()));
2323 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2324 &ClsExprs[0],
2325 ClsExprs.size());
2326 MsgExprs.push_back(Cls);
2327 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002328 } else { // instance message.
2329 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002330
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002331 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002332 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002333 if (MsgSendStretFlavor)
2334 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002335 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2336
2337 llvm::SmallVector<Expr*, 4> InitExprs;
2338
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002339 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002340 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002341 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002342 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002343 SourceLocation()),
2344 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002345 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002346
2347 llvm::SmallVector<Expr*, 8> ClsExprs;
2348 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002349 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2350 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002351 false, argType, SourceLocation(),
2352 SourceLocation()));
2353 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002354 &ClsExprs[0],
2355 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002356 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002357 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002358 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002359 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002360 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002361 // struct objc_super
2362 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002363 Expr *SuperRep;
2364
2365 if (LangOpts.Microsoft) {
2366 SynthSuperContructorFunctionDecl();
2367 // Simulate a contructor call...
2368 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2369 superType, SourceLocation());
2370 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2371 superType, SourceLocation());
2372 } else {
2373 // (struct objc_super) { <exprs from above> }
2374 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2375 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002376 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002377 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2378 }
Steve Naroff874e2322007-11-15 10:28:18 +00002379 // struct objc_super *
2380 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2381 Context->getPointerType(SuperRep->getType()),
2382 SourceLocation());
2383 MsgExprs.push_back(Unop);
2384 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002385 // Remove all type-casts because it may contain objc-style types; e.g.
2386 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002387 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002388 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002389 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002390 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002391 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002392 MsgExprs.push_back(recExpr);
2393 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002394 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002395 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002396 llvm::SmallVector<Expr*, 8> SelExprs;
2397 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002398 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2399 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002400 false, argType, SourceLocation(),
2401 SourceLocation()));
2402 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2403 &SelExprs[0], SelExprs.size());
2404 MsgExprs.push_back(SelExp);
2405
2406 // Now push any user supplied arguments.
2407 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002408 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002409 // Make all implicit casts explicit...ICE comes in handy:-)
2410 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2411 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002412 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002413 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002414 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002415 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002416 }
2417 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002418 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002419 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002420 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002421 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002422 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002423 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002424 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002425 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002426 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002427 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002428 // We've transferred the ownership to MsgExprs. Null out the argument in
2429 // the original expression, since we will delete it below.
2430 Exp->setArg(i, 0);
2431 }
Steve Naroffab972d32007-11-04 22:37:50 +00002432 // Generate the funky cast.
2433 CastExpr *cast;
2434 llvm::SmallVector<QualType, 8> ArgTypes;
2435 QualType returnType;
2436
2437 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002438 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2439 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2440 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002441 ArgTypes.push_back(Context->getObjCIdType());
2442 ArgTypes.push_back(Context->getObjCSelType());
2443 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002444 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002445 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002446 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2447 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002448 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002449 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2450 if (isBlockPointerType(t)) {
2451 const BlockPointerType *BPT = t->getAsBlockPointerType();
2452 t = Context->getPointerType(BPT->getPointeeType());
2453 }
Steve Naroff352336b2007-11-05 14:36:37 +00002454 ArgTypes.push_back(t);
2455 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002456 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2457 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002458 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002459 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002460 }
2461 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002462 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002463
2464 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002465 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2466 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002467
2468 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2469 // If we don't do this cast, we get the following bizarre warning/note:
2470 // xx.m:13: warning: function called through a non-compatible type
2471 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002472 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002473 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002474 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002475
Steve Naroffab972d32007-11-04 22:37:50 +00002476 // Now do the "normal" pointer to function cast.
2477 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002478 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002479 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002480 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002481 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002482 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002483
2484 // Don't forget the parens to enforce the proper binding.
2485 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2486
2487 const FunctionType *FT = msgSendType->getAsFunctionType();
2488 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2489 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002490 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002491 if (MsgSendStretFlavor) {
2492 // We have the method which returns a struct/union. Must also generate
2493 // call to objc_msgSend_stret and hang both varieties on a conditional
2494 // expression which dictate which one to envoke depending on size of
2495 // method's return type.
2496
2497 // Create a reference to the objc_msgSend_stret() declaration.
2498 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2499 SourceLocation());
2500 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002501 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002502 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002503 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002504 // Now do the "normal" pointer to function cast.
2505 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002506 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002507 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002508 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002509 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002510
2511 // Don't forget the parens to enforce the proper binding.
2512 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2513
2514 FT = msgSendType->getAsFunctionType();
2515 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2516 FT->getResultType(), SourceLocation());
2517
2518 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002519 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2520 returnType.getAsOpaquePtr(),
2521 Context->getSizeType(),
2522 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002523 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2524 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2525 // For X86 it is more complicated and some kind of target specific routine
2526 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002527 unsigned IntSize =
2528 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002529 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2530 Context->IntTy,
2531 SourceLocation());
2532 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2533 BinaryOperator::LE,
2534 Context->IntTy,
2535 SourceLocation());
2536 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2537 ConditionalOperator *CondExpr =
2538 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002539 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002540 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002541 return ReplacingStmt;
2542}
2543
Steve Naroffb29b4272008-04-14 22:03:09 +00002544Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002545 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002546
Steve Naroffc77a6362008-12-04 16:24:46 +00002547 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002548 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002549 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002550
Steve Naroff4c3580e2008-12-04 23:50:32 +00002551 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002552 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002553}
2554
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002555/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2556/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002557Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002558 if (!GetProtocolFunctionDecl)
2559 SynthGetProtocolFunctionDecl();
2560 // Create a call to objc_getProtocol("ProtocolName").
2561 llvm::SmallVector<Expr*, 8> ProtoExprs;
2562 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002563 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2564 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002565 false, argType, SourceLocation(),
2566 SourceLocation()));
2567 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2568 &ProtoExprs[0],
2569 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002570 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002571 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002572 return ProtoExp;
2573
2574}
2575
Steve Naroffbaf58c32008-05-31 14:15:04 +00002576bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2577 const char *endBuf) {
2578 while (startBuf < endBuf) {
2579 if (*startBuf == '#') {
2580 // Skip whitespace.
2581 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2582 ;
2583 if (!strncmp(startBuf, "if", strlen("if")) ||
2584 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2585 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2586 !strncmp(startBuf, "define", strlen("define")) ||
2587 !strncmp(startBuf, "undef", strlen("undef")) ||
2588 !strncmp(startBuf, "else", strlen("else")) ||
2589 !strncmp(startBuf, "elif", strlen("elif")) ||
2590 !strncmp(startBuf, "endif", strlen("endif")) ||
2591 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2592 !strncmp(startBuf, "include", strlen("include")) ||
2593 !strncmp(startBuf, "import", strlen("import")) ||
2594 !strncmp(startBuf, "include_next", strlen("include_next")))
2595 return true;
2596 }
2597 startBuf++;
2598 }
2599 return false;
2600}
2601
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002602/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002603/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002604void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002605 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002606 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002607 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002608 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002609 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002610 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002611 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002612 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002613 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002614 SourceLocation LocStart = CDecl->getLocStart();
2615 SourceLocation LocEnd = CDecl->getLocEnd();
2616
2617 const char *startBuf = SM->getCharacterData(LocStart);
2618 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002619
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002620 // If no ivars and no root or if its root, directly or indirectly,
2621 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002622 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2623 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002624 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002625 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002626 return;
2627 }
2628
2629 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002630 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002631 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002632 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002633 if (LangOpts.Microsoft)
2634 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002635
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002636 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002637 const char *cursor = strchr(startBuf, '{');
2638 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002639 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002640 // If the buffer contains preprocessor directives, we do more fine-grained
2641 // rewrites. This is intended to fix code that looks like (which occurs in
2642 // NSURL.h, for example):
2643 //
2644 // #ifdef XYZ
2645 // @interface Foo : NSObject
2646 // #else
2647 // @interface FooBar : NSObject
2648 // #endif
2649 // {
2650 // int i;
2651 // }
2652 // @end
2653 //
2654 // This clause is segregated to avoid breaking the common case.
2655 if (BufferContainsPPDirectives(startBuf, cursor)) {
2656 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2657 CDecl->getClassLoc();
2658 const char *endHeader = SM->getCharacterData(L);
2659 endHeader += Lexer::MeasureTokenLength(L, *SM);
2660
Chris Lattner3db6cae2008-07-21 18:19:38 +00002661 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002662 // advance to the end of the referenced protocols.
2663 while (endHeader < cursor && *endHeader != '>') endHeader++;
2664 endHeader++;
2665 }
2666 // rewrite the original header
2667 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2668 } else {
2669 // rewrite the original header *without* disturbing the '{'
2670 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2671 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002672 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002673 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";
Steve Narofffea763e82007-11-14 19:25:57 +00002678
2679 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002680 SourceLocation OnePastCurly =
2681 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2682 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002683 }
2684 cursor++; // past '{'
2685
2686 // Now comment out any visibility specifiers.
2687 while (cursor < endBuf) {
2688 if (*cursor == '@') {
2689 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002690 // Skip whitespace.
2691 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2692 /*scan*/;
2693
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002694 // FIXME: presence of @public, etc. inside comment results in
2695 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002696 if (!strncmp(cursor, "public", strlen("public")) ||
2697 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002698 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002699 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002700 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002701 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002702 // FIXME: If there are cases where '<' is used in ivar declaration part
2703 // of user code, then scan the ivar list and use needToScanForQualifiers
2704 // for type checking.
2705 else if (*cursor == '<') {
2706 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002707 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002708 cursor = strchr(cursor, '>');
2709 cursor++;
2710 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002711 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002712 } else if (*cursor == '^') { // rewrite block specifier.
2713 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2714 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002715 }
Steve Narofffea763e82007-11-14 19:25:57 +00002716 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002717 }
Steve Narofffea763e82007-11-14 19:25:57 +00002718 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002719 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002720 } else { // we don't have any instance variables - insert super struct.
2721 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2722 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002723 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002724 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002725 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002726 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002727 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002728 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002729 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002730 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002731 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002732}
2733
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002734// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002735/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002736void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002737 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002738 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002739 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002740 const char *ClassName,
2741 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002742 if (MethodBegin == MethodEnd) return;
2743
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002744 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002745 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002746 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002747 SEL _cmd;
2748 char *method_types;
2749 void *_imp;
2750 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002751 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002752 Result += "\nstruct _objc_method {\n";
2753 Result += "\tSEL _cmd;\n";
2754 Result += "\tchar *method_types;\n";
2755 Result += "\tvoid *_imp;\n";
2756 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002757
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002758 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002759 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002760
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002761 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002762
2763 /* struct {
2764 struct _objc_method_list *next_method;
2765 int method_count;
2766 struct _objc_method method_list[];
2767 }
2768 */
2769 Result += "\nstatic struct {\n";
2770 Result += "\tstruct _objc_method_list *next_method;\n";
2771 Result += "\tint method_count;\n";
2772 Result += "\tstruct _objc_method method_list[";
2773 Result += utostr(MethodEnd-MethodBegin);
2774 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002775 Result += prefix;
2776 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2777 Result += "_METHODS_";
2778 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002779 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002780 Result += IsInstanceMethod ? "inst" : "cls";
2781 Result += "_meth\")))= ";
2782 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002783
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002784 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002785 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002786 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002787 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002788 Result += "\", \"";
2789 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002790 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002791 Result += MethodInternalNames[*MethodBegin];
2792 Result += "}\n";
2793 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2794 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002795 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002796 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002797 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002798 Result += "\", \"";
2799 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002800 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002801 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002802 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002803 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002804 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002805}
2806
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002807/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002808void RewriteObjC::
2809RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2810 const char *prefix,
2811 const char *ClassName,
2812 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002813 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002814 if (Protocols.empty()) return;
2815
2816 for (unsigned i = 0; i != Protocols.size(); i++) {
2817 ObjCProtocolDecl *PDecl = Protocols[i];
2818 // Output struct protocol_methods holder of method selector and type.
2819 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2820 /* struct protocol_methods {
2821 SEL _cmd;
2822 char *method_types;
2823 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002824 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002825 Result += "\nstruct protocol_methods {\n";
2826 Result += "\tSEL _cmd;\n";
2827 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002828 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002829
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002830 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002831 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002832 // Do not synthesize the protocol more than once.
2833 if (ObjCSynthesizedProtocols.count(PDecl))
2834 continue;
2835
2836 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2837 unsigned NumMethods = PDecl->getNumInstanceMethods();
2838 /* struct _objc_protocol_method_list {
2839 int protocol_method_count;
2840 struct protocol_methods protocols[];
2841 }
2842 */
2843 Result += "\nstatic struct {\n";
2844 Result += "\tint protocol_method_count;\n";
2845 Result += "\tstruct protocol_methods protocols[";
2846 Result += utostr(NumMethods);
2847 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002848 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002849 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2850 "{\n\t" + utostr(NumMethods) + "\n";
2851
2852 // Output instance methods declared in this protocol.
2853 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2854 E = PDecl->instmeth_end(); I != E; ++I) {
2855 if (I == PDecl->instmeth_begin())
2856 Result += "\t ,{{(SEL)\"";
2857 else
2858 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002859 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002860 std::string MethodTypeString;
2861 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2862 Result += "\", \"";
2863 Result += MethodTypeString;
2864 Result += "\"}\n";
2865 }
2866 Result += "\t }\n};\n";
2867 }
2868
2869 // Output class methods declared in this protocol.
2870 int NumMethods = PDecl->getNumClassMethods();
2871 if (NumMethods > 0) {
2872 /* struct _objc_protocol_method_list {
2873 int protocol_method_count;
2874 struct protocol_methods protocols[];
2875 }
2876 */
2877 Result += "\nstatic struct {\n";
2878 Result += "\tint protocol_method_count;\n";
2879 Result += "\tstruct protocol_methods protocols[";
2880 Result += utostr(NumMethods);
2881 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002882 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002883 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2884 "{\n\t";
2885 Result += utostr(NumMethods);
2886 Result += "\n";
2887
2888 // Output instance methods declared in this protocol.
2889 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2890 E = PDecl->classmeth_end(); I != E; ++I) {
2891 if (I == PDecl->classmeth_begin())
2892 Result += "\t ,{{(SEL)\"";
2893 else
2894 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002895 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002896 std::string MethodTypeString;
2897 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2898 Result += "\", \"";
2899 Result += MethodTypeString;
2900 Result += "\"}\n";
2901 }
2902 Result += "\t }\n};\n";
2903 }
2904
2905 // Output:
2906 /* struct _objc_protocol {
2907 // Objective-C 1.0 extensions
2908 struct _objc_protocol_extension *isa;
2909 char *protocol_name;
2910 struct _objc_protocol **protocol_list;
2911 struct _objc_protocol_method_list *instance_methods;
2912 struct _objc_protocol_method_list *class_methods;
2913 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002914 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002915 static bool objc_protocol = false;
2916 if (!objc_protocol) {
2917 Result += "\nstruct _objc_protocol {\n";
2918 Result += "\tstruct _objc_protocol_extension *isa;\n";
2919 Result += "\tchar *protocol_name;\n";
2920 Result += "\tstruct _objc_protocol **protocol_list;\n";
2921 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2922 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2923 Result += "};\n";
2924
2925 objc_protocol = true;
2926 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002927
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002928 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002929 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002930 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2931 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002932 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002933 Result += "\", 0, ";
2934 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2935 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002936 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002937 Result += ", ";
2938 }
2939 else
2940 Result += "0, ";
2941 if (PDecl->getNumClassMethods() > 0) {
2942 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002943 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002944 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002945 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002946 else
2947 Result += "0\n";
2948 Result += "};\n";
2949
2950 // Mark this protocol as having been generated.
2951 if (!ObjCSynthesizedProtocols.insert(PDecl))
2952 assert(false && "protocol already synthesized");
2953 }
2954 // Output the top lovel protocol meta-data for the class.
2955 /* struct _objc_protocol_list {
2956 struct _objc_protocol_list *next;
2957 int protocol_count;
2958 struct _objc_protocol *class_protocols[];
2959 }
2960 */
2961 Result += "\nstatic struct {\n";
2962 Result += "\tstruct _objc_protocol_list *next;\n";
2963 Result += "\tint protocol_count;\n";
2964 Result += "\tstruct _objc_protocol *class_protocols[";
2965 Result += utostr(Protocols.size());
2966 Result += "];\n} _OBJC_";
2967 Result += prefix;
2968 Result += "_PROTOCOLS_";
2969 Result += ClassName;
2970 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2971 "{\n\t0, ";
2972 Result += utostr(Protocols.size());
2973 Result += "\n";
2974
2975 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002976 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002977 Result += " \n";
2978
2979 for (unsigned i = 1; i != Protocols.size(); i++) {
2980 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002981 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002982 Result += "\n";
2983 }
2984 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002985}
2986
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002987/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002988/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002989void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002990 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002991 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002992 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002993 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002994 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2995 CDecl = CDecl->getNextClassCategory())
2996 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2997 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002998
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002999 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003000 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003001 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003002
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003003 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003004 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003005 true, "CATEGORY_", FullCategoryName.c_str(),
3006 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003007
3008 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003009 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003010 false, "CATEGORY_", FullCategoryName.c_str(),
3011 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003012
3013 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003014 // Null CDecl is case of a category implementation with no category interface
3015 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003016 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003017 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003018
3019 /* struct _objc_category {
3020 char *category_name;
3021 char *class_name;
3022 struct _objc_method_list *instance_methods;
3023 struct _objc_method_list *class_methods;
3024 struct _objc_protocol_list *protocols;
3025 // Objective-C 1.0 extensions
3026 uint32_t size; // sizeof (struct _objc_category)
3027 struct _objc_property_list *instance_properties; // category's own
3028 // @property decl.
3029 };
3030 */
3031
3032 static bool objc_category = false;
3033 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003034 Result += "\nstruct _objc_category {\n";
3035 Result += "\tchar *category_name;\n";
3036 Result += "\tchar *class_name;\n";
3037 Result += "\tstruct _objc_method_list *instance_methods;\n";
3038 Result += "\tstruct _objc_method_list *class_methods;\n";
3039 Result += "\tstruct _objc_protocol_list *protocols;\n";
3040 Result += "\tunsigned int size;\n";
3041 Result += "\tstruct _objc_property_list *instance_properties;\n";
3042 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003043 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003044 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003045 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3046 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003047 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003048 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003049 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003050 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003051 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003052
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003053 if (IDecl->getNumInstanceMethods() > 0) {
3054 Result += "\t, (struct _objc_method_list *)"
3055 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3056 Result += FullCategoryName;
3057 Result += "\n";
3058 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003059 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003060 Result += "\t, 0\n";
3061 if (IDecl->getNumClassMethods() > 0) {
3062 Result += "\t, (struct _objc_method_list *)"
3063 "&_OBJC_CATEGORY_CLASS_METHODS_";
3064 Result += FullCategoryName;
3065 Result += "\n";
3066 }
3067 else
3068 Result += "\t, 0\n";
3069
Chris Lattner780f3292008-07-21 21:32:27 +00003070 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003071 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3072 Result += FullCategoryName;
3073 Result += "\n";
3074 }
3075 else
3076 Result += "\t, 0\n";
3077 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003078}
3079
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003080/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3081/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003082void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003083 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003084 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003085 if (ivar->isBitField()) {
3086 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3087 // place all bitfields at offset 0.
3088 Result += "0";
3089 } else {
3090 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003091 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003092 if (LangOpts.Microsoft)
3093 Result += "_IMPL";
3094 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003095 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003096 Result += ")";
3097 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003098}
3099
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003100//===----------------------------------------------------------------------===//
3101// Meta Data Emission
3102//===----------------------------------------------------------------------===//
3103
Steve Naroffb29b4272008-04-14 22:03:09 +00003104void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003105 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003106 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003107
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003108 // Explictly declared @interface's are already synthesized.
3109 if (CDecl->ImplicitInterfaceDecl()) {
3110 // FIXME: Implementation of a class with no @interface (legacy) doese not
3111 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003112 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003113 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003114
Chris Lattnerbe6df082007-12-12 07:56:42 +00003115 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003116 unsigned NumIvars = !IDecl->ivar_empty()
3117 ? IDecl->ivar_size()
3118 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003119 if (NumIvars > 0) {
3120 static bool objc_ivar = false;
3121 if (!objc_ivar) {
3122 /* struct _objc_ivar {
3123 char *ivar_name;
3124 char *ivar_type;
3125 int ivar_offset;
3126 };
3127 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003128 Result += "\nstruct _objc_ivar {\n";
3129 Result += "\tchar *ivar_name;\n";
3130 Result += "\tchar *ivar_type;\n";
3131 Result += "\tint ivar_offset;\n";
3132 Result += "};\n";
3133
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003134 objc_ivar = true;
3135 }
3136
Steve Naroff946a6932008-03-11 00:12:29 +00003137 /* struct {
3138 int ivar_count;
3139 struct _objc_ivar ivar_list[nIvars];
3140 };
3141 */
3142 Result += "\nstatic struct {\n";
3143 Result += "\tint ivar_count;\n";
3144 Result += "\tstruct _objc_ivar ivar_list[";
3145 Result += utostr(NumIvars);
3146 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003147 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003148 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003149 "{\n\t";
3150 Result += utostr(NumIvars);
3151 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003152
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003153 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003154 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003155 IVI = IDecl->ivar_begin();
3156 IVE = IDecl->ivar_end();
3157 } else {
3158 IVI = CDecl->ivar_begin();
3159 IVE = CDecl->ivar_end();
3160 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003161 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003162 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003163 Result += "\", \"";
3164 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003165 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003166 Result += StrEncoding;
3167 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003168 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003169 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003170 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003171 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003172 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003173 Result += "\", \"";
3174 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003175 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003176 Result += StrEncoding;
3177 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003178 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003179 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003180 }
3181
3182 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003183 }
3184
3185 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003186 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003187 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003188
3189 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003190 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003191 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003192
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003193 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003194 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003195 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003196
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003197
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003198 // Declaration of class/meta-class metadata
3199 /* struct _objc_class {
3200 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003201 const char *super_class_name;
3202 char *name;
3203 long version;
3204 long info;
3205 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003206 struct _objc_ivar_list *ivars;
3207 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003208 struct objc_cache *cache;
3209 struct objc_protocol_list *protocols;
3210 const char *ivar_layout;
3211 struct _objc_class_ext *ext;
3212 };
3213 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003214 static bool objc_class = false;
3215 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003216 Result += "\nstruct _objc_class {\n";
3217 Result += "\tstruct _objc_class *isa;\n";
3218 Result += "\tconst char *super_class_name;\n";
3219 Result += "\tchar *name;\n";
3220 Result += "\tlong version;\n";
3221 Result += "\tlong info;\n";
3222 Result += "\tlong instance_size;\n";
3223 Result += "\tstruct _objc_ivar_list *ivars;\n";
3224 Result += "\tstruct _objc_method_list *methods;\n";
3225 Result += "\tstruct objc_cache *cache;\n";
3226 Result += "\tstruct _objc_protocol_list *protocols;\n";
3227 Result += "\tconst char *ivar_layout;\n";
3228 Result += "\tstruct _objc_class_ext *ext;\n";
3229 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003230 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003231 }
3232
3233 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003234 ObjCInterfaceDecl *RootClass = 0;
3235 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003236 while (SuperClass) {
3237 RootClass = SuperClass;
3238 SuperClass = SuperClass->getSuperClass();
3239 }
3240 SuperClass = CDecl->getSuperClass();
3241
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003242 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003243 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003244 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003245 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003246 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003247 Result += "\"";
3248
3249 if (SuperClass) {
3250 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003251 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003252 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003253 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003254 Result += "\"";
3255 }
3256 else {
3257 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003258 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003259 Result += "\"";
3260 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003261 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003262 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003263 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003264 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003265 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003266 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003267 Result += "\n";
3268 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003269 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003270 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003271 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003272 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003273 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003274 Result += ",0,0\n";
3275 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003276 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003277 Result += "\t,0,0,0,0\n";
3278 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003279
3280 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003281 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003282 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003283 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003284 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003285 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003286 if (SuperClass) {
3287 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003288 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003289 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003290 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003291 Result += "\"";
3292 }
3293 else {
3294 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003295 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003296 Result += "\"";
3297 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003298 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003299 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003300 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003301 Result += ",0";
3302 else {
3303 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003304 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003305 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003306 if (LangOpts.Microsoft)
3307 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003308 Result += ")";
3309 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003310 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003311 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003312 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003313 Result += "\n\t";
3314 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003315 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003316 Result += ",0";
3317 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003318 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003319 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003320 Result += ", 0\n\t";
3321 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003322 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003323 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003324 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003325 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003326 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003327 Result += ", 0,0\n";
3328 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003329 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003330 Result += ",0,0,0\n";
3331 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003332}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003333
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003334/// RewriteImplementations - This routine rewrites all method implementations
3335/// and emits meta-data.
3336
Steve Narofface66252008-11-13 20:07:04 +00003337void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003338 int ClsDefCount = ClassImplementation.size();
3339 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003340
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003341 // Rewrite implemented methods
3342 for (int i = 0; i < ClsDefCount; i++)
3343 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003344
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003345 for (int i = 0; i < CatDefCount; i++)
3346 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003347}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003348
Steve Narofface66252008-11-13 20:07:04 +00003349void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3350 int ClsDefCount = ClassImplementation.size();
3351 int CatDefCount = CategoryImplementation.size();
3352
Steve Naroff5df5b762008-05-07 21:23:49 +00003353 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003354 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003355 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003356 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003357 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003358
3359 // For each implemented category, write out all its meta data.
3360 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003361 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003362
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003363 // Write objc_symtab metadata
3364 /*
3365 struct _objc_symtab
3366 {
3367 long sel_ref_cnt;
3368 SEL *refs;
3369 short cls_def_cnt;
3370 short cat_def_cnt;
3371 void *defs[cls_def_cnt + cat_def_cnt];
3372 };
3373 */
3374
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003375 Result += "\nstruct _objc_symtab {\n";
3376 Result += "\tlong sel_ref_cnt;\n";
3377 Result += "\tSEL *refs;\n";
3378 Result += "\tshort cls_def_cnt;\n";
3379 Result += "\tshort cat_def_cnt;\n";
3380 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3381 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003382
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003383 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003384 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003385 Result += "\t0, 0, " + utostr(ClsDefCount)
3386 + ", " + utostr(CatDefCount) + "\n";
3387 for (int i = 0; i < ClsDefCount; i++) {
3388 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003389 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003390 Result += "\n";
3391 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003392
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003393 for (int i = 0; i < CatDefCount; i++) {
3394 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003395 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003396 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003397 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003398 Result += "\n";
3399 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003400
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003401 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003402
3403 // Write objc_module metadata
3404
3405 /*
3406 struct _objc_module {
3407 long version;
3408 long size;
3409 const char *name;
3410 struct _objc_symtab *symtab;
3411 }
3412 */
3413
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003414 Result += "\nstruct _objc_module {\n";
3415 Result += "\tlong version;\n";
3416 Result += "\tlong size;\n";
3417 Result += "\tconst char *name;\n";
3418 Result += "\tstruct _objc_symtab *symtab;\n";
3419 Result += "};\n\n";
3420 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003421 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003422 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3423 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003424 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003425
3426 if (LangOpts.Microsoft) {
3427 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003428 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003429 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3430 Result += "&_OBJC_MODULES;\n";
3431 Result += "#pragma data_seg(pop)\n\n";
3432 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003433}
Chris Lattner311ff022007-10-16 22:36:42 +00003434
Steve Naroff54055232008-10-27 17:20:55 +00003435std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3436 const char *funcName,
3437 std::string Tag) {
3438 const FunctionType *AFT = CE->getFunctionType();
3439 QualType RT = AFT->getResultType();
3440 std::string StructRef = "struct " + Tag;
3441 std::string S = "static " + RT.getAsString() + " __" +
3442 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003443
Steve Naroff54055232008-10-27 17:20:55 +00003444 BlockDecl *BD = CE->getBlockDecl();
3445
3446 if (isa<FunctionTypeNoProto>(AFT)) {
3447 S += "()";
3448 } else if (BD->param_empty()) {
3449 S += "(" + StructRef + " *__cself)";
3450 } else {
3451 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3452 assert(FT && "SynthesizeBlockFunc: No function proto");
3453 S += '(';
3454 // first add the implicit argument.
3455 S += StructRef + " *__cself, ";
3456 std::string ParamStr;
3457 for (BlockDecl::param_iterator AI = BD->param_begin(),
3458 E = BD->param_end(); AI != E; ++AI) {
3459 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003460 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003461 (*AI)->getType().getAsStringInternal(ParamStr);
3462 S += ParamStr;
3463 }
3464 if (FT->isVariadic()) {
3465 if (!BD->param_empty()) S += ", ";
3466 S += "...";
3467 }
3468 S += ')';
3469 }
3470 S += " {\n";
3471
3472 // Create local declarations to avoid rewriting all closure decl ref exprs.
3473 // First, emit a declaration for all "by ref" decls.
3474 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3475 E = BlockByRefDecls.end(); I != E; ++I) {
3476 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003477 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003478 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003479 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003480 }
3481 // Next, emit a declaration for all "by copy" declarations.
3482 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3483 E = BlockByCopyDecls.end(); I != E; ++I) {
3484 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003485 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003486 // Handle nested closure invocation. For example:
3487 //
3488 // void (^myImportedClosure)(void);
3489 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3490 //
3491 // void (^anotherClosure)(void);
3492 // anotherClosure = ^(void) {
3493 // myImportedClosure(); // import and invoke the closure
3494 // };
3495 //
3496 if (isBlockPointerType((*I)->getType()))
3497 S += "struct __block_impl *";
3498 else
3499 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003500 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003501 }
3502 std::string RewrittenStr = RewrittenBlockExprs[CE];
3503 const char *cstr = RewrittenStr.c_str();
3504 while (*cstr++ != '{') ;
3505 S += cstr;
3506 S += "\n";
3507 return S;
3508}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003509
Steve Naroff54055232008-10-27 17:20:55 +00003510std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3511 const char *funcName,
3512 std::string Tag) {
3513 std::string StructRef = "struct " + Tag;
3514 std::string S = "static void __";
3515
3516 S += funcName;
3517 S += "_block_copy_" + utostr(i);
3518 S += "(" + StructRef;
3519 S += "*dst, " + StructRef;
3520 S += "*src) {";
3521 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3522 E = ImportedBlockDecls.end(); I != E; ++I) {
3523 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003524 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003525 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003526 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003527 S += ");}";
3528 }
3529 S += "\nstatic void __";
3530 S += funcName;
3531 S += "_block_dispose_" + utostr(i);
3532 S += "(" + StructRef;
3533 S += "*src) {";
3534 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3535 E = ImportedBlockDecls.end(); I != E; ++I) {
3536 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003537 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003538 S += ");";
3539 }
3540 S += "}\n";
3541 return S;
3542}
3543
3544std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3545 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003546 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003547 std::string Constructor = " " + Tag;
3548
3549 S += " {\n struct __block_impl impl;\n";
3550
3551 if (hasCopyDisposeHelpers)
3552 S += " void *copy;\n void *dispose;\n";
3553
3554 Constructor += "(void *fp";
3555
3556 if (hasCopyDisposeHelpers)
3557 Constructor += ", void *copyHelp, void *disposeHelp";
3558
3559 if (BlockDeclRefs.size()) {
3560 // Output all "by copy" declarations.
3561 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3562 E = BlockByCopyDecls.end(); I != E; ++I) {
3563 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003564 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003565 std::string ArgName = "_" + FieldName;
3566 // Handle nested closure invocation. For example:
3567 //
3568 // void (^myImportedBlock)(void);
3569 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3570 //
3571 // void (^anotherBlock)(void);
3572 // anotherBlock = ^(void) {
3573 // myImportedBlock(); // import and invoke the closure
3574 // };
3575 //
3576 if (isBlockPointerType((*I)->getType())) {
3577 S += "struct __block_impl *";
3578 Constructor += ", void *" + ArgName;
3579 } else {
3580 (*I)->getType().getAsStringInternal(FieldName);
3581 (*I)->getType().getAsStringInternal(ArgName);
3582 Constructor += ", " + ArgName;
3583 }
3584 S += FieldName + ";\n";
3585 }
3586 // Output all "by ref" declarations.
3587 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3588 E = BlockByRefDecls.end(); I != E; ++I) {
3589 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003590 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003591 std::string ArgName = "_" + FieldName;
3592 // Handle nested closure invocation. For example:
3593 //
3594 // void (^myImportedBlock)(void);
3595 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3596 //
3597 // void (^anotherBlock)(void);
3598 // anotherBlock = ^(void) {
3599 // myImportedBlock(); // import and invoke the closure
3600 // };
3601 //
3602 if (isBlockPointerType((*I)->getType())) {
3603 S += "struct __block_impl *";
3604 Constructor += ", void *" + ArgName;
3605 } else {
3606 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3607 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3608 Constructor += ", " + ArgName;
3609 }
3610 S += FieldName + "; // by ref\n";
3611 }
3612 // Finish writing the constructor.
3613 // FIXME: handle NSConcreteGlobalBlock.
3614 Constructor += ", int flags=0) {\n";
3615 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3616 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3617
3618 if (hasCopyDisposeHelpers)
3619 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3620
3621 // Initialize all "by copy" arguments.
3622 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3623 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003624 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003625 Constructor += " ";
3626 if (isBlockPointerType((*I)->getType()))
3627 Constructor += Name + " = (struct __block_impl *)_";
3628 else
3629 Constructor += Name + " = _";
3630 Constructor += Name + ";\n";
3631 }
3632 // Initialize all "by ref" arguments.
3633 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3634 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003635 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003636 Constructor += " ";
3637 if (isBlockPointerType((*I)->getType()))
3638 Constructor += Name + " = (struct __block_impl *)_";
3639 else
3640 Constructor += Name + " = _";
3641 Constructor += Name + ";\n";
3642 }
3643 } else {
3644 // Finish writing the constructor.
3645 // FIXME: handle NSConcreteGlobalBlock.
3646 Constructor += ", int flags=0) {\n";
3647 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3648 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3649 if (hasCopyDisposeHelpers)
3650 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3651 }
3652 Constructor += " ";
3653 Constructor += "}\n";
3654 S += Constructor;
3655 S += "};\n";
3656 return S;
3657}
3658
3659void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3660 const char *FunName) {
3661 // Insert closures that were part of the function.
3662 for (unsigned i = 0; i < Blocks.size(); i++) {
3663
3664 CollectBlockDeclRefInfo(Blocks[i]);
3665
3666 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3667
3668 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3669 ImportedBlockDecls.size() > 0);
3670
3671 InsertText(FunLocStart, CI.c_str(), CI.size());
3672
3673 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3674
3675 InsertText(FunLocStart, CF.c_str(), CF.size());
3676
3677 if (ImportedBlockDecls.size()) {
3678 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3679 InsertText(FunLocStart, HF.c_str(), HF.size());
3680 }
3681
3682 BlockDeclRefs.clear();
3683 BlockByRefDecls.clear();
3684 BlockByCopyDecls.clear();
3685 BlockCallExprs.clear();
3686 ImportedBlockDecls.clear();
3687 }
3688 Blocks.clear();
3689 RewrittenBlockExprs.clear();
3690}
3691
3692void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3693 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003694 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003695
3696 SynthesizeBlockLiterals(FunLocStart, FuncName);
3697}
3698
3699void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003700 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3701 //SourceLocation FunLocStart = MD->getLocStart();
3702 // FIXME: This hack works around a bug in Rewrite.InsertText().
3703 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003704 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003705 // Convert colons to underscores.
3706 std::string::size_type loc = 0;
3707 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3708 FuncName.replace(loc, 1, "_");
3709
3710 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3711}
3712
3713void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3714 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3715 CI != E; ++CI)
3716 if (*CI) {
3717 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3718 GetBlockDeclRefExprs(CBE->getBody());
3719 else
3720 GetBlockDeclRefExprs(*CI);
3721 }
3722 // Handle specific things.
3723 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3724 // FIXME: Handle enums.
3725 if (!isa<FunctionDecl>(CDRE->getDecl()))
3726 BlockDeclRefs.push_back(CDRE);
3727 return;
3728}
3729
3730void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3731 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3732 CI != E; ++CI)
3733 if (*CI) {
3734 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3735 GetBlockCallExprs(CBE->getBody());
3736 else
3737 GetBlockCallExprs(*CI);
3738 }
3739
3740 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3741 if (CE->getCallee()->getType()->isBlockPointerType()) {
3742 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3743 }
3744 }
3745 return;
3746}
3747
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003748Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003749 // Navigate to relevant type information.
3750 const char *closureName = 0;
3751 const BlockPointerType *CPT = 0;
3752
3753 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003754 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003755 CPT = DRE->getType()->getAsBlockPointerType();
3756 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003757 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003758 CPT = CDRE->getType()->getAsBlockPointerType();
3759 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003760 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003761 CPT = MExpr->getType()->getAsBlockPointerType();
3762 } else {
3763 assert(1 && "RewriteBlockClass: Bad type");
3764 }
3765 assert(CPT && "RewriteBlockClass: Bad type");
3766 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3767 assert(FT && "RewriteBlockClass: Bad type");
3768 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3769 // FTP will be null for closures that don't take arguments.
3770
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003771 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3772 SourceLocation(),
3773 &Context->Idents.get("__block_impl"));
3774 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003775
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003776 // Generate a funky cast.
3777 llvm::SmallVector<QualType, 8> ArgTypes;
3778
3779 // Push the block argument type.
3780 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003781 if (FTP) {
3782 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003783 E = FTP->arg_type_end(); I && (I != E); ++I) {
3784 QualType t = *I;
3785 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3786 if (isBlockPointerType(t)) {
3787 const BlockPointerType *BPT = t->getAsBlockPointerType();
3788 t = Context->getPointerType(BPT->getPointeeType());
3789 }
3790 ArgTypes.push_back(t);
3791 }
Steve Naroff54055232008-10-27 17:20:55 +00003792 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003793 // Now do the pointer to function cast.
3794 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3795 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3796
3797 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003798
Steve Naroffb2f9e512008-11-03 23:29:32 +00003799 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003800 // Don't forget the parens to enforce the proper binding.
3801 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3802 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003803
Douglas Gregor44b43212008-12-11 16:49:14 +00003804 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3805 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
3806 /*BitWidth=*/0, /*Mutable=*/true, 0);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003807 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3808
Steve Naroffb2f9e512008-11-03 23:29:32 +00003809 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003810 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3811
3812 llvm::SmallVector<Expr*, 8> BlkExprs;
3813 // Add the implicit argument.
3814 BlkExprs.push_back(BlkCast);
3815 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003816 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3817 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003818 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003819 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003820 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3821 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003822}
3823
3824void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003825 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3826 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003827}
3828
3829void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3830 // FIXME: Add more elaborate code generation required by the ABI.
3831 InsertText(BDRE->getLocStart(), "*", 1);
3832}
3833
Steve Naroffb2f9e512008-11-03 23:29:32 +00003834void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3835 SourceLocation LocStart = CE->getLParenLoc();
3836 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003837
3838 // Need to avoid trying to rewrite synthesized casts.
3839 if (LocStart.isInvalid())
3840 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003841 // Need to avoid trying to rewrite casts contained in macros.
3842 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3843 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003844
Steve Naroff54055232008-10-27 17:20:55 +00003845 const char *startBuf = SM->getCharacterData(LocStart);
3846 const char *endBuf = SM->getCharacterData(LocEnd);
3847
3848 // advance the location to startArgList.
3849 const char *argPtr = startBuf;
3850
3851 while (*argPtr++ && (argPtr < endBuf)) {
3852 switch (*argPtr) {
3853 case '^':
3854 // Replace the '^' with '*'.
3855 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3856 ReplaceText(LocStart, 1, "*", 1);
3857 break;
3858 }
3859 }
3860 return;
3861}
3862
3863void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3864 SourceLocation DeclLoc = FD->getLocation();
3865 unsigned parenCount = 0;
3866
3867 // We have 1 or more arguments that have closure pointers.
3868 const char *startBuf = SM->getCharacterData(DeclLoc);
3869 const char *startArgList = strchr(startBuf, '(');
3870
3871 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3872
3873 parenCount++;
3874 // advance the location to startArgList.
3875 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3876 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3877
3878 const char *argPtr = startArgList;
3879
3880 while (*argPtr++ && parenCount) {
3881 switch (*argPtr) {
3882 case '^':
3883 // Replace the '^' with '*'.
3884 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3885 ReplaceText(DeclLoc, 1, "*", 1);
3886 break;
3887 case '(':
3888 parenCount++;
3889 break;
3890 case ')':
3891 parenCount--;
3892 break;
3893 }
3894 }
3895 return;
3896}
3897
3898bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3899 const FunctionTypeProto *FTP;
3900 const PointerType *PT = QT->getAsPointerType();
3901 if (PT) {
3902 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3903 } else {
3904 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3905 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3906 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3907 }
3908 if (FTP) {
3909 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3910 E = FTP->arg_type_end(); I != E; ++I)
3911 if (isBlockPointerType(*I))
3912 return true;
3913 }
3914 return false;
3915}
3916
3917void RewriteObjC::GetExtentOfArgList(const char *Name,
3918 const char *&LParen, const char *&RParen) {
3919 const char *argPtr = strchr(Name, '(');
3920 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3921
3922 LParen = argPtr; // output the start.
3923 argPtr++; // skip past the left paren.
3924 unsigned parenCount = 1;
3925
3926 while (*argPtr && parenCount) {
3927 switch (*argPtr) {
3928 case '(': parenCount++; break;
3929 case ')': parenCount--; break;
3930 default: break;
3931 }
3932 if (parenCount) argPtr++;
3933 }
3934 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3935 RParen = argPtr; // output the end
3936}
3937
3938void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3939 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3940 RewriteBlockPointerFunctionArgs(FD);
3941 return;
3942 }
3943 // Handle Variables and Typedefs.
3944 SourceLocation DeclLoc = ND->getLocation();
3945 QualType DeclT;
3946 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3947 DeclT = VD->getType();
3948 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3949 DeclT = TDD->getUnderlyingType();
3950 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3951 DeclT = FD->getType();
3952 else
3953 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3954
3955 const char *startBuf = SM->getCharacterData(DeclLoc);
3956 const char *endBuf = startBuf;
3957 // scan backward (from the decl location) for the end of the previous decl.
3958 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3959 startBuf--;
3960
3961 // *startBuf != '^' if we are dealing with a pointer to function that
3962 // may take block argument types (which will be handled below).
3963 if (*startBuf == '^') {
3964 // Replace the '^' with '*', computing a negative offset.
3965 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3966 ReplaceText(DeclLoc, 1, "*", 1);
3967 }
3968 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3969 // Replace the '^' with '*' for arguments.
3970 DeclLoc = ND->getLocation();
3971 startBuf = SM->getCharacterData(DeclLoc);
3972 const char *argListBegin, *argListEnd;
3973 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3974 while (argListBegin < argListEnd) {
3975 if (*argListBegin == '^') {
3976 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3977 ReplaceText(CaretLoc, 1, "*", 1);
3978 }
3979 argListBegin++;
3980 }
3981 }
3982 return;
3983}
3984
3985void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3986 // Add initializers for any closure decl refs.
3987 GetBlockDeclRefExprs(Exp->getBody());
3988 if (BlockDeclRefs.size()) {
3989 // Unique all "by copy" declarations.
3990 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3991 if (!BlockDeclRefs[i]->isByRef())
3992 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3993 // Unique all "by ref" declarations.
3994 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3995 if (BlockDeclRefs[i]->isByRef()) {
3996 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3997 }
3998 // Find any imported blocks...they will need special attention.
3999 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4000 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00004001 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004002 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4003 }
4004 }
4005}
4006
Steve Narofffa15fd92008-10-28 20:29:00 +00004007FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4008 IdentifierInfo *ID = &Context->Idents.get(name);
4009 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
4010 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
4011 ID, FType, FunctionDecl::Extern, false, 0);
4012}
4013
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004014Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004015 Blocks.push_back(Exp);
4016
4017 CollectBlockDeclRefInfo(Exp);
4018 std::string FuncName;
4019
4020 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004021 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004022 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004023 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004024 // Convert colons to underscores.
4025 std::string::size_type loc = 0;
4026 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4027 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004028 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004029 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004030
4031 std::string BlockNumber = utostr(Blocks.size()-1);
4032
4033 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4034 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4035
4036 // Get a pointer to the function type so we can cast appropriately.
4037 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4038
4039 FunctionDecl *FD;
4040 Expr *NewRep;
4041
4042 // Simulate a contructor call...
4043 FD = SynthBlockInitFunctionDecl(Tag.c_str());
4044 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
4045
4046 llvm::SmallVector<Expr*, 4> InitExprs;
4047
Steve Narofffdc03722008-10-29 21:23:59 +00004048 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004049 FD = SynthBlockInitFunctionDecl(Func.c_str());
4050 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4051 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004052 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004053 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004054
4055 if (ImportedBlockDecls.size()) {
4056 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004057 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4058 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4059 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004060 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004061 InitExprs.push_back(castExpr);
4062
Steve Narofffa15fd92008-10-28 20:29:00 +00004063 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004064 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4065 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4066 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004067 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004068 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004069 }
4070 // Add initializers for any closure decl refs.
4071 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004072 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004073 // Output all "by copy" declarations.
4074 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4075 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004076 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004077 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004078 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004079 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004080 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004081 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004082 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4083 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004084 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004085 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004086 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004087 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004088 }
Steve Narofffdc03722008-10-29 21:23:59 +00004089 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004090 }
4091 // Output all "by ref" declarations.
4092 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4093 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004094 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004095 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4096 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
4097 Context->getPointerType(Exp->getType()),
4098 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004099 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004100 }
4101 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004102 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
4103 FType, SourceLocation());
4104 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
4105 Context->getPointerType(NewRep->getType()),
4106 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00004107 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004108 BlockDeclRefs.clear();
4109 BlockByRefDecls.clear();
4110 BlockByCopyDecls.clear();
4111 ImportedBlockDecls.clear();
4112 return NewRep;
4113}
4114
4115//===----------------------------------------------------------------------===//
4116// Function Body / Expression rewriting
4117//===----------------------------------------------------------------------===//
4118
Steve Naroffc77a6362008-12-04 16:24:46 +00004119// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4120// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4121// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4122// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4123// Since the rewriter isn't capable of rewriting rewritten code, it's important
4124// we get this right.
4125void RewriteObjC::CollectPropertySetters(Stmt *S) {
4126 // Perform a bottom up traversal of all children.
4127 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4128 CI != E; ++CI)
4129 if (*CI)
4130 CollectPropertySetters(*CI);
4131
4132 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4133 if (BinOp->isAssignmentOp()) {
4134 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4135 PropSetters[PRE] = BinOp;
4136 }
4137 }
4138}
4139
Steve Narofffa15fd92008-10-28 20:29:00 +00004140Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4141 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4142 isa<DoStmt>(S) || isa<ForStmt>(S))
4143 Stmts.push_back(S);
4144 else if (isa<ObjCForCollectionStmt>(S)) {
4145 Stmts.push_back(S);
4146 ObjCBcLabelNo.push_back(++BcLabelCount);
4147 }
4148
4149 SourceRange OrigStmtRange = S->getSourceRange();
4150
4151 // Perform a bottom up rewrite of all children.
4152 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4153 CI != E; ++CI)
4154 if (*CI) {
4155 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4156 if (newStmt)
4157 *CI = newStmt;
4158 }
4159
4160 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4161 // Rewrite the block body in place.
4162 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4163
4164 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004165 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4166 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004167
4168 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4169 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004170 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004171 return blockTranscribed;
4172 }
4173 // Handle specific things.
4174 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4175 return RewriteAtEncode(AtEncode);
4176
4177 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4178 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4179
Steve Naroffc77a6362008-12-04 16:24:46 +00004180 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4181 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4182 if (BinOp) {
4183 // Because the rewriter doesn't allow us to rewrite rewritten code,
4184 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004185 DisableReplaceStmt = true;
4186 // Save the source range. Even if we disable the replacement, the
4187 // rewritten node will have been inserted into the tree. If the synthesized
4188 // node is at the 'end', the rewriter will fail. Consider this:
4189 // self.errorHandler = handler ? handler :
4190 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4191 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004192 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004193 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004194 //
4195 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4196 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4197 // to see the original expression). Consider this example:
4198 //
4199 // Foo *obj1, *obj2;
4200 //
4201 // obj1.i = [obj2 rrrr];
4202 //
4203 // 'BinOp' for the previous expression looks like:
4204 //
4205 // (BinaryOperator 0x231ccf0 'int' '='
4206 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4207 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4208 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4209 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4210 //
4211 // 'newStmt' represents the rewritten message expression. For example:
4212 //
4213 // (CallExpr 0x231d300 'id':'struct objc_object *'
4214 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4215 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4216 // (CStyleCastExpr 0x231d220 'void *'
4217 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4218 //
4219 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4220 // can be used as the setter argument. ReplaceStmt() will still 'see'
4221 // the original RHS (since we haven't altered BinOp).
4222 //
4223 // This implies the Rewrite* routines can no longer delete the original
4224 // node. As a result, we now leak the original AST nodes.
4225 //
Steve Naroffb619d952008-12-09 12:56:34 +00004226 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004227 } else {
4228 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004229 }
4230 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004231 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4232 return RewriteAtSelector(AtSelector);
4233
4234 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4235 return RewriteObjCStringLiteral(AtString);
4236
4237 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004238#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004239 // Before we rewrite it, put the original message expression in a comment.
4240 SourceLocation startLoc = MessExpr->getLocStart();
4241 SourceLocation endLoc = MessExpr->getLocEnd();
4242
4243 const char *startBuf = SM->getCharacterData(startLoc);
4244 const char *endBuf = SM->getCharacterData(endLoc);
4245
4246 std::string messString;
4247 messString += "// ";
4248 messString.append(startBuf, endBuf-startBuf+1);
4249 messString += "\n";
4250
4251 // FIXME: Missing definition of
4252 // InsertText(clang::SourceLocation, char const*, unsigned int).
4253 // InsertText(startLoc, messString.c_str(), messString.size());
4254 // Tried this, but it didn't work either...
4255 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004256#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004257 return RewriteMessageExpr(MessExpr);
4258 }
4259
4260 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4261 return RewriteObjCTryStmt(StmtTry);
4262
4263 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4264 return RewriteObjCSynchronizedStmt(StmtTry);
4265
4266 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4267 return RewriteObjCThrowStmt(StmtThrow);
4268
4269 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4270 return RewriteObjCProtocolExpr(ProtocolExp);
4271
4272 if (ObjCForCollectionStmt *StmtForCollection =
4273 dyn_cast<ObjCForCollectionStmt>(S))
4274 return RewriteObjCForCollectionStmt(StmtForCollection,
4275 OrigStmtRange.getEnd());
4276 if (BreakStmt *StmtBreakStmt =
4277 dyn_cast<BreakStmt>(S))
4278 return RewriteBreakStmt(StmtBreakStmt);
4279 if (ContinueStmt *StmtContinueStmt =
4280 dyn_cast<ContinueStmt>(S))
4281 return RewriteContinueStmt(StmtContinueStmt);
4282
4283 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4284 // and cast exprs.
4285 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4286 // FIXME: What we're doing here is modifying the type-specifier that
4287 // precedes the first Decl. In the future the DeclGroup should have
4288 // a separate type-specifier that we can rewrite.
4289 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4290
4291 // Blocks rewrite rules.
4292 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4293 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004294 ScopedDecl *SD = *DI;
4295 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4296 if (isBlockPointerType(ND->getType()))
4297 RewriteBlockPointerDecl(ND);
4298 else if (ND->getType()->isFunctionPointerType())
4299 CheckFunctionPointerDecl(ND->getType(), ND);
4300 }
4301 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4302 if (isBlockPointerType(TD->getUnderlyingType()))
4303 RewriteBlockPointerDecl(TD);
4304 else if (TD->getUnderlyingType()->isFunctionPointerType())
4305 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4306 }
4307 }
4308 }
4309
4310 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4311 RewriteObjCQualifiedInterfaceTypes(CE);
4312
4313 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4314 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4315 assert(!Stmts.empty() && "Statement stack is empty");
4316 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4317 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4318 && "Statement stack mismatch");
4319 Stmts.pop_back();
4320 }
4321 // Handle blocks rewriting.
4322 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4323 if (BDRE->isByRef())
4324 RewriteBlockDeclRefExpr(BDRE);
4325 }
4326 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004327 if (CE->getCallee()->getType()->isBlockPointerType()) {
4328 Stmt *BlockCall = SynthesizeBlockCall(CE);
4329 ReplaceStmt(S, BlockCall);
4330 return BlockCall;
4331 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004332 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004333 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004334 RewriteCastExpr(CE);
4335 }
4336#if 0
4337 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4338 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4339 // Get the new text.
4340 std::string SStr;
4341 llvm::raw_string_ostream Buf(SStr);
4342 Replacement->printPretty(Buf);
4343 const std::string &Str = Buf.str();
4344
4345 printf("CAST = %s\n", &Str[0]);
4346 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4347 delete S;
4348 return Replacement;
4349 }
4350#endif
4351 // Return this stmt unmodified.
4352 return S;
4353}
4354
4355/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4356/// main file of the input.
4357void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4358 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4359 // Since function prototypes don't have ParmDecl's, we check the function
4360 // prototype. This enables us to rewrite function declarations and
4361 // definitions using the same code.
4362 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4363
4364 if (Stmt *Body = FD->getBody()) {
4365 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004366 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004367 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004368 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004369 CurrentBody = 0;
4370 if (PropParentMap) {
4371 delete PropParentMap;
4372 PropParentMap = 0;
4373 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004374 // This synthesizes and inserts the block "impl" struct, invoke function,
4375 // and any copy/dispose helper functions.
4376 InsertBlockLiteralsWithinFunction(FD);
4377 CurFunctionDef = 0;
4378 }
4379 return;
4380 }
4381 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4382 if (Stmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004383 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004384 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004385 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004386 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004387 CurrentBody = 0;
4388 if (PropParentMap) {
4389 delete PropParentMap;
4390 PropParentMap = 0;
4391 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004392 InsertBlockLiteralsWithinMethod(MD);
4393 CurMethodDef = 0;
4394 }
4395 }
4396 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4397 ClassImplementation.push_back(CI);
4398 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4399 CategoryImplementation.push_back(CI);
4400 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4401 RewriteForwardClassDecl(CD);
4402 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4403 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004404 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004405 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004406 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004407 CheckFunctionPointerDecl(VD->getType(), VD);
4408 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004409 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004410 RewriteCastExpr(CE);
4411 }
4412 }
4413 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004414 if (VD->getInit()) {
4415 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004416 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004417 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004418 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004419 CurrentBody = 0;
4420 if (PropParentMap) {
4421 delete PropParentMap;
4422 PropParentMap = 0;
4423 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004424 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004425 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004426 GlobalVarDecl = 0;
4427
4428 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004429 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004430 RewriteCastExpr(CE);
4431 }
4432 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004433 return;
4434 }
4435 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4436 if (isBlockPointerType(TD->getUnderlyingType()))
4437 RewriteBlockPointerDecl(TD);
4438 else if (TD->getUnderlyingType()->isFunctionPointerType())
4439 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4440 return;
4441 }
4442 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4443 if (RD->isDefinition()) {
Douglas Gregora4c46df2008-12-11 17:59:21 +00004444 for (RecordDecl::field_iterator i = RD->field_begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004445 e = RD->field_end(); i != e; ++i) {
4446 FieldDecl *FD = *i;
4447 if (isBlockPointerType(FD->getType()))
4448 RewriteBlockPointerDecl(FD);
4449 }
4450 }
4451 return;
4452 }
4453 // Nothing yet.
4454}
4455
4456void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4457 // Get the top-level buffer that this corresponds to.
4458
4459 // Rewrite tabs if we care.
4460 //RewriteTabs();
4461
4462 if (Diags.hasErrorOccurred())
4463 return;
4464
4465 // Create the output file.
4466
4467 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4468 llvm::raw_ostream *OutFile;
4469 if (OutFileName == "-") {
4470 OutFile = &llvm::outs();
4471 } else if (!OutFileName.empty()) {
4472 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004473 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004474 OwnedStream.reset(OutFile);
4475 } else if (InFileName == "-") {
4476 OutFile = &llvm::outs();
4477 } else {
4478 llvm::sys::Path Path(InFileName);
4479 Path.eraseSuffix();
4480 Path.appendSuffix("cpp");
4481 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004482 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004483 OwnedStream.reset(OutFile);
4484 }
4485
4486 RewriteInclude();
4487
4488 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4489 Preamble.c_str(), Preamble.size(), false);
4490
Steve Naroff0aab7962008-11-14 14:10:01 +00004491 if (ClassImplementation.size() || CategoryImplementation.size())
4492 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004493
4494 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4495 // we are done.
4496 if (const RewriteBuffer *RewriteBuf =
4497 Rewrite.getRewriteBufferFor(MainFileID)) {
4498 //printf("Changed:\n");
4499 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4500 } else {
4501 fprintf(stderr, "No changes\n");
4502 }
Steve Narofface66252008-11-13 20:07:04 +00004503
Steve Naroff0aab7962008-11-14 14:10:01 +00004504 if (ClassImplementation.size() || CategoryImplementation.size()) {
4505 // Rewrite Objective-c meta data*
4506 std::string ResultStr;
4507 SynthesizeMetaDataIntoBuffer(ResultStr);
4508 // Emit metadata.
4509 *OutFile << ResultStr;
4510 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004511 OutFile->flush();
4512}
4513