blob: 6fc4a83fcf064aee4b6cdf143b4cf01485024372 [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"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Steve Naroff0113c9d2008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattner77cd2a02007-10-11 00:43:27 +000038namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattner01c57482007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000046 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000051
Ted Kremeneka526c5c2008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000083 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +000099
Steve Naroff54055232008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
Steve Naroffc77a6362008-12-04 16:24:46 +0000107 // This maps a property to it's assignment statement.
108 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff4c3580e2008-12-04 23:50:32 +0000109 // This maps an original source AST to it's rewritten form. This allows
110 // us to avoid rewriting the same node twice (which is very uncommon).
111 // This is needed to support some of the exotic property rewriting.
112 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000113
Steve Naroff54055232008-10-27 17:20:55 +0000114 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000115 VarDecl *GlobalVarDecl;
116
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000117 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000118 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000119 virtual void Initialize(ASTContext &context);
120
121 virtual void InitializeTU(TranslationUnit &TU) {
122 TU.SetOwnsDecls(false);
123 Initialize(TU.getContext());
124 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000125
Chris Lattner8a12c272007-10-11 18:38:32 +0000126
Chris Lattnerf04da132007-10-24 17:06:59 +0000127 // Top Level Driver code.
128 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000129 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000130 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000131 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000132
133 ~RewriteObjC() {}
134
135 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000136
137 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000138 Stmt *ReplacingStmt = ReplacedNodes[Old];
139
140 if (ReplacingStmt)
141 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000142
Steve Naroff4c3580e2008-12-04 23:50:32 +0000143 // If replacement succeeded or warning disabled return with no warning.
144 if (!Rewrite.ReplaceStmt(Old, New)) {
145 ReplacedNodes[Old] = New;
146 return;
147 }
148 if (SilenceRewriteMacroWarning)
149 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000150 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
151 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000152 }
153
Steve Naroffba92b2e2008-03-27 22:29:16 +0000154 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
155 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000156 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000157 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000158 SilenceRewriteMacroWarning)
159 return;
160
161 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
162 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000163
Chris Lattneraadaf782008-01-31 19:51:04 +0000164 void RemoveText(SourceLocation Loc, unsigned StrLen) {
165 // If removal succeeded or warning disabled return with no warning.
166 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
167 return;
168
169 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
170 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000171
Chris Lattneraadaf782008-01-31 19:51:04 +0000172 void ReplaceText(SourceLocation Start, unsigned OrigLength,
173 const char *NewStr, unsigned NewLength) {
174 // If removal succeeded or warning disabled return with no warning.
175 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
176 SilenceRewriteMacroWarning)
177 return;
178
179 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
180 }
181
Chris Lattnerf04da132007-10-24 17:06:59 +0000182 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000183 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000184 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000185 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000186 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000187 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
188 ObjCImplementationDecl *IMD,
189 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000190 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000191 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000192 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
193 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
194 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
195 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
196 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000197 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000198 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000199 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000200 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000201 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000202 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000203 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000204 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000205 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000206
Chris Lattnerf04da132007-10-24 17:06:59 +0000207 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000208 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000209 void CollectPropertySetters(Stmt *S);
210
Chris Lattnere64b7772007-10-24 16:57:36 +0000211 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000212 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000213 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
214 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt);
Steve Naroffb42f8412007-11-05 14:50:49 +0000215 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000216 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000217 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000218 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000219 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000220 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000221 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
222 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
223 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000224 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
225 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000226 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
227 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000228 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000229 Stmt *RewriteBreakStmt(BreakStmt *S);
230 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000231 void SynthCountByEnumWithState(std::string &buf);
232
Steve Naroff09b266e2007-10-30 23:14:51 +0000233 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000234 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000235 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000236 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000237 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000238 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000239 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000240 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000241 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000242 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000243
Chris Lattnerf04da132007-10-24 17:06:59 +0000244 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000245 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000246 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000247
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000248 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000249 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000250
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000251 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
252 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000253 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000254 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000255 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000256 const char *ClassName,
257 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000258
Chris Lattner780f3292008-07-21 21:32:27 +0000259 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
260 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000261 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000262 const char *ClassName,
263 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000264 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000265 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000266 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
267 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000268 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000269 void RewriteImplementations();
270 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000271
272 // Block rewriting.
273 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
274 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
275
276 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
277 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
278
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000279 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000280 void RewriteBlockCall(CallExpr *Exp);
281 void RewriteBlockPointerDecl(NamedDecl *VD);
282 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
283 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
284
285 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
286 const char *funcName, std::string Tag);
287 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
288 const char *funcName, std::string Tag);
289 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
290 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000291 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000292 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
293 const char *FunName);
294
295 void CollectBlockDeclRefInfo(BlockExpr *Exp);
296 void GetBlockCallExprs(Stmt *S);
297 void GetBlockDeclRefExprs(Stmt *S);
298
299 // We avoid calling Type::isBlockPointerType(), since it operates on the
300 // canonical type. We only care if the top-level type is a closure pointer.
301 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
302
303 // FIXME: This predicate seems like it would be useful to add to ASTContext.
304 bool isObjCType(QualType T) {
305 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
306 return false;
307
308 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
309
310 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
311 OCT == Context->getCanonicalType(Context->getObjCClassType()))
312 return true;
313
314 if (const PointerType *PT = OCT->getAsPointerType()) {
315 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
316 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
317 return true;
318 }
319 return false;
320 }
321 bool PointerTypeTakesAnyBlockArguments(QualType QT);
322 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000323 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000324
325 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000326 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000327 };
328}
329
Steve Naroff54055232008-10-27 17:20:55 +0000330void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
331 NamedDecl *D) {
332 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
333 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
334 E = fproto->arg_type_end(); I && (I != E); ++I)
335 if (isBlockPointerType(*I)) {
336 // All the args are checked/rewritten. Don't call twice!
337 RewriteBlockPointerDecl(D);
338 break;
339 }
340 }
341}
342
343void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
344 const PointerType *PT = funcType->getAsPointerType();
345 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
346 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
347}
348
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000349static bool IsHeaderFile(const std::string &Filename) {
350 std::string::size_type DotPos = Filename.rfind('.');
351
352 if (DotPos == std::string::npos) {
353 // no file extension
354 return false;
355 }
356
357 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
358 // C header: .h
359 // C++ header: .hh or .H;
360 return Ext == "h" || Ext == "hh" || Ext == "H";
361}
362
Steve Naroffb29b4272008-04-14 22:03:09 +0000363RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000364 Diagnostic &D, const LangOptions &LOpts)
365 : Diags(D), LangOpts(LOpts) {
366 IsHeader = IsHeaderFile(inFile);
367 InFileName = inFile;
368 OutFileName = outFile;
369 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
370 "rewriting sub-expression within a macro (may not be correct)");
371}
372
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000373ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000374 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000375 Diagnostic &Diags,
376 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000377 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000378}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000379
Steve Naroffb29b4272008-04-14 22:03:09 +0000380void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000381 Context = &context;
382 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000383 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000384 MsgSendFunctionDecl = 0;
385 MsgSendSuperFunctionDecl = 0;
386 MsgSendStretFunctionDecl = 0;
387 MsgSendSuperStretFunctionDecl = 0;
388 MsgSendFpretFunctionDecl = 0;
389 GetClassFunctionDecl = 0;
390 GetMetaClassFunctionDecl = 0;
391 SelGetUidFunctionDecl = 0;
392 CFStringFunctionDecl = 0;
393 GetProtocolFunctionDecl = 0;
394 ConstantStringClassReference = 0;
395 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000396 CurMethodDef = 0;
397 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000398 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000399 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000400 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000401 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000402 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000403
404 // Get the ID and start/end of the main file.
405 MainFileID = SM->getMainFileID();
406 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
407 MainFileStart = MainBuf->getBufferStart();
408 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000409
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000410 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000411
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000412 // declaring objc_selector outside the parameter list removes a silly
413 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000414 if (IsHeader)
415 Preamble = "#pragma once\n";
416 Preamble += "struct objc_selector; struct objc_class;\n";
417 Preamble += "#ifndef OBJC_SUPER\n";
418 Preamble += "struct objc_super { struct objc_object *object; ";
419 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000420 if (LangOpts.Microsoft) {
421 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000422 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
423 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000424 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000425 Preamble += "};\n";
426 Preamble += "#define OBJC_SUPER\n";
427 Preamble += "#endif\n";
428 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
429 Preamble += "typedef struct objc_object Protocol;\n";
430 Preamble += "#define _REWRITER_typedef_Protocol\n";
431 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000432 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000433 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
434 else
435 Preamble += "#define __OBJC_RW_EXTERN extern\n";
436 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000437 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000438 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000439 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000440 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000441 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000442 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000443 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000444 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000445 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000446 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000447 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000448 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000449 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000450 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
451 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
452 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
453 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
454 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000455 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000456 // @synchronized hooks.
457 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
458 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000459 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000460 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
461 Preamble += "struct __objcFastEnumerationState {\n\t";
462 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000463 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000464 Preamble += "unsigned long *mutationsPtr;\n\t";
465 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000466 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000467 Preamble += "#define __FASTENUMERATIONSTATE\n";
468 Preamble += "#endif\n";
469 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
470 Preamble += "struct __NSConstantStringImpl {\n";
471 Preamble += " int *isa;\n";
472 Preamble += " int flags;\n";
473 Preamble += " char *str;\n";
474 Preamble += " long length;\n";
475 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000476 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
477 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
478 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000479 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000480 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000481 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
482 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000483 // Blocks preamble.
484 Preamble += "#ifndef BLOCK_IMPL\n";
485 Preamble += "#define BLOCK_IMPL\n";
486 Preamble += "struct __block_impl {\n";
487 Preamble += " void *isa;\n";
488 Preamble += " int Flags;\n";
489 Preamble += " int Size;\n";
490 Preamble += " void *FuncPtr;\n";
491 Preamble += "};\n";
492 Preamble += "enum {\n";
493 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
494 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
495 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000496 Preamble += "// Runtime copy/destroy helper functions\n";
497 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
498 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
499 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
500 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
501 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
502 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
503 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000504 if (LangOpts.Microsoft) {
505 Preamble += "#undef __OBJC_RW_EXTERN\n";
506 Preamble += "#define __attribute__(X)\n";
507 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000508}
509
510
Chris Lattnerf04da132007-10-24 17:06:59 +0000511//===----------------------------------------------------------------------===//
512// Top Level Driver Code
513//===----------------------------------------------------------------------===//
514
Steve Naroffb29b4272008-04-14 22:03:09 +0000515void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000516 // Two cases: either the decl could be in the main file, or it could be in a
517 // #included file. If the former, rewrite it now. If the later, check to see
518 // if we rewrote the #include/#import.
519 SourceLocation Loc = D->getLocation();
520 Loc = SM->getLogicalLoc(Loc);
521
522 // If this is for a builtin, ignore it.
523 if (Loc.isInvalid()) return;
524
Steve Naroffebf2b562007-10-23 23:50:29 +0000525 // Look for built-in declarations that we need to refer during the rewrite.
526 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000527 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000528 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000529 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000530 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000531 ConstantStringClassReference = FVD;
532 return;
533 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000534 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000535 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000536 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000537 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000538 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000539 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000540 } else if (ObjCForwardProtocolDecl *FP =
541 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000542 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000543 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000544 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000545 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000546 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000547}
548
Chris Lattnerf04da132007-10-24 17:06:59 +0000549//===----------------------------------------------------------------------===//
550// Syntactic (non-AST) Rewriting Code
551//===----------------------------------------------------------------------===//
552
Steve Naroffb29b4272008-04-14 22:03:09 +0000553void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000554 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
555 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
556 const char *MainBufStart = MainBuf.first;
557 const char *MainBufEnd = MainBuf.second;
558 size_t ImportLen = strlen("import");
559 size_t IncludeLen = strlen("include");
560
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000561 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000562 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
563 if (*BufPtr == '#') {
564 if (++BufPtr == MainBufEnd)
565 return;
566 while (*BufPtr == ' ' || *BufPtr == '\t')
567 if (++BufPtr == MainBufEnd)
568 return;
569 if (!strncmp(BufPtr, "import", ImportLen)) {
570 // replace import with include
571 SourceLocation ImportLoc =
572 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000573 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000574 BufPtr += ImportLen;
575 }
576 }
577 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000578}
579
Steve Naroffb29b4272008-04-14 22:03:09 +0000580void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000581 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
582 const char *MainBufStart = MainBuf.first;
583 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000584
Chris Lattnerf04da132007-10-24 17:06:59 +0000585 // Loop over the whole file, looking for tabs.
586 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
587 if (*BufPtr != '\t')
588 continue;
589
590 // Okay, we found a tab. This tab will turn into at least one character,
591 // but it depends on which 'virtual column' it is in. Compute that now.
592 unsigned VCol = 0;
593 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
594 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
595 ++VCol;
596
597 // Okay, now that we know the virtual column, we know how many spaces to
598 // insert. We assume 8-character tab-stops.
599 unsigned Spaces = 8-(VCol & 7);
600
601 // Get the location of the tab.
602 SourceLocation TabLoc =
603 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
604
605 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000606 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000607 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000608}
609
Steve Naroffeb0646c2008-12-02 15:48:25 +0000610static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
611 ObjCIvarDecl *OID) {
612 std::string S;
613 S = "((struct ";
614 S += ClassDecl->getIdentifier()->getName();
615 S += "_IMPL *)self)->";
616 S += OID->getNameAsCString();
617 return S;
618}
619
Steve Naroffa0876e82008-12-02 17:36:43 +0000620void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
621 ObjCImplementationDecl *IMD,
622 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000623 SourceLocation startLoc = PID->getLocStart();
624 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000625 const char *startBuf = SM->getCharacterData(startLoc);
626 assert((*startBuf == '@') && "bogus @synthesize location");
627 const char *semiBuf = strchr(startBuf, ';');
628 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
629 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
630
631 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
632 return; // FIXME: is this correct?
633
634 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000635 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000636 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000637 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000638
639 if (!OID)
640 return;
641
642 std::string Getr;
643 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
644 Getr += "{ ";
645 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000646 // FIXME: deal with code generation implications for various property
647 // attributes (copy, retain, nonatomic).
648 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000649 Getr += "return " + getIvarAccessString(ClassDecl, OID);
650 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000651 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000652
653 // Add the rewritten getter to trigger meta data generation. An alternate, and
654 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
655 // with properties explicitly. The following addInstanceMethod() required far
656 // less code change (and actually models what the rewriter is doing).
657 if (IMD)
658 IMD->addInstanceMethod(PD->getGetterMethodDecl());
659 else
660 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000661
662 if (PD->isReadOnly())
663 return;
664
665 // Generate the 'setter' function.
666 std::string Setr;
667 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000668 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000669 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000670 // FIXME: deal with code generation implications for various property
671 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000672 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000673 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
674 Setr += OID->getNameAsCString();
675 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000676 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000677
678 // Add the rewritten setter to trigger meta data generation.
679 if (IMD)
680 IMD->addInstanceMethod(PD->getSetterMethodDecl());
681 else
682 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000683}
Chris Lattner8a12c272007-10-11 18:38:32 +0000684
Steve Naroffb29b4272008-04-14 22:03:09 +0000685void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000686 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000687 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000688
689 // Get the start location and compute the semi location.
690 SourceLocation startLoc = ClassDecl->getLocation();
691 const char *startBuf = SM->getCharacterData(startLoc);
692 const char *semiPtr = strchr(startBuf, ';');
693
694 // Translate to typedef's that forward reference structs with the same name
695 // as the class. As a convenience, we include the original declaration
696 // as a comment.
697 std::string typedefString;
698 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000699 typedefString.append(startBuf, semiPtr-startBuf+1);
700 typedefString += "\n";
701 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000702 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000703 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000704 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000705 typedefString += "\n";
706 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000707 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000708 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000709 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000710 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000711 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000712 }
713
714 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000715 ReplaceText(startLoc, semiPtr-startBuf+1,
716 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000717}
718
Steve Naroffb29b4272008-04-14 22:03:09 +0000719void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000720 SourceLocation LocStart = Method->getLocStart();
721 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000722
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000723 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000724 InsertText(LocStart, "#if 0\n", 6);
725 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000726 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000727 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000728 }
729}
730
Steve Naroffb29b4272008-04-14 22:03:09 +0000731void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000732{
Chris Lattner55d13b42008-03-16 21:23:50 +0000733 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000734 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000735 SourceLocation Loc = Property->getLocation();
736
Chris Lattneraadaf782008-01-31 19:51:04 +0000737 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000738
739 // FIXME: handle properties that are declared across multiple lines.
740 }
741}
742
Steve Naroffb29b4272008-04-14 22:03:09 +0000743void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000744 SourceLocation LocStart = CatDecl->getLocStart();
745
746 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000747 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000748
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000749 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000750 E = CatDecl->instmeth_end(); I != E; ++I)
751 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000752 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000753 E = CatDecl->classmeth_end(); I != E; ++I)
754 RewriteMethodDeclaration(*I);
755
Steve Naroff423cb562007-10-30 13:30:57 +0000756 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000757 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000758}
759
Steve Naroffb29b4272008-04-14 22:03:09 +0000760void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000761 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000762
Steve Naroff752d6ef2007-10-30 16:42:30 +0000763 SourceLocation LocStart = PDecl->getLocStart();
764
765 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000766 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000767
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000768 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000769 E = PDecl->instmeth_end(); I != E; ++I)
770 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000771 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000772 E = PDecl->classmeth_end(); I != E; ++I)
773 RewriteMethodDeclaration(*I);
774
Steve Naroff752d6ef2007-10-30 16:42:30 +0000775 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000776 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000777 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000778
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000779 // Must comment out @optional/@required
780 const char *startBuf = SM->getCharacterData(LocStart);
781 const char *endBuf = SM->getCharacterData(LocEnd);
782 for (const char *p = startBuf; p < endBuf; p++) {
783 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
784 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000785 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000786 ReplaceText(OptionalLoc, strlen("@optional"),
787 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000788
789 }
790 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
791 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000792 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000793 ReplaceText(OptionalLoc, strlen("@required"),
794 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000795
796 }
797 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000798}
799
Steve Naroffb29b4272008-04-14 22:03:09 +0000800void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000801 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000802 if (LocStart.isInvalid())
803 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000804 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000805 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000806}
807
Steve Naroffb29b4272008-04-14 22:03:09 +0000808void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000809 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000810 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000811 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000812 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000813 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000814 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000815 else if (OMD->getResultType()->isFunctionPointerType()) {
816 // needs special handling, since pointer-to-functions have special
817 // syntax (where a decaration models use).
818 QualType retType = OMD->getResultType();
819 if (const PointerType* PT = retType->getAsPointerType()) {
820 QualType PointeeTy = PT->getPointeeType();
821 if ((FPRetType = PointeeTy->getAsFunctionType())) {
822 ResultStr += FPRetType->getResultType().getAsString();
823 ResultStr += "(*";
824 }
825 }
826 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000827 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000828 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000829
830 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000831 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000832
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000833 if (OMD->isInstance())
834 NameStr += "_I_";
835 else
836 NameStr += "_C_";
837
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000838 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000839 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000840
841 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000842 if (ObjCCategoryImplDecl *CID =
843 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000844 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000845 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000846 }
Steve Naroff563b8282008-04-04 22:23:44 +0000847 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000848 {
849 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000850 int len = selString.size();
851 for (int i = 0; i < len; i++)
852 if (selString[i] == ':')
853 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000854 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000855 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000856 // Remember this name for metadata emission
857 MethodInternalNames[OMD] = NameStr;
858 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000859
860 // Rewrite arguments
861 ResultStr += "(";
862
863 // invisible arguments
864 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000865 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000866 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000867 if (!LangOpts.Microsoft) {
868 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
869 ResultStr += "struct ";
870 }
871 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000872 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000873 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000874 }
875 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000876 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000877
878 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000879 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000880 ResultStr += " _cmd";
881
882 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000883 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000884 ParmVarDecl *PDecl = OMD->getParamDecl(i);
885 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000886 if (PDecl->getType()->isObjCQualifiedIdType()) {
887 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000888 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000889 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000890 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000891 if (isBlockPointerType(PDecl->getType())) {
892 // Make sure we convert "t (^)(...)" to "t (*)(...)".
893 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
894 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
895 } else
896 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000897 ResultStr += Name;
898 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000899 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000900 if (OMD->isVariadic())
901 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000902 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000903
Steve Naroff76e429d2008-07-16 14:40:40 +0000904 if (FPRetType) {
905 ResultStr += ")"; // close the precedence "scope" for "*".
906
907 // Now, emit the argument types (if any).
908 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
909 ResultStr += "(";
910 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
911 if (i) ResultStr += ", ";
912 std::string ParamStr = FT->getArgType(i).getAsString();
913 ResultStr += ParamStr;
914 }
915 if (FT->isVariadic()) {
916 if (FT->getNumArgs()) ResultStr += ", ";
917 ResultStr += "...";
918 }
919 ResultStr += ")";
920 } else {
921 ResultStr += "()";
922 }
923 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000924}
Steve Naroffb29b4272008-04-14 22:03:09 +0000925void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000926 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
927 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000928
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000929 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000930 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000931 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000932 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000933
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000934 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000935 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
936 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000937 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000938 ObjCMethodDecl *OMD = *I;
939 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000940 SourceLocation LocStart = OMD->getLocStart();
941 SourceLocation LocEnd = OMD->getBody()->getLocStart();
942
943 const char *startBuf = SM->getCharacterData(LocStart);
944 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000945 ReplaceText(LocStart, endBuf-startBuf,
946 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000947 }
948
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000949 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000950 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
951 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000952 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000953 ObjCMethodDecl *OMD = *I;
954 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000955 SourceLocation LocStart = OMD->getLocStart();
956 SourceLocation LocEnd = OMD->getBody()->getLocStart();
957
958 const char *startBuf = SM->getCharacterData(LocStart);
959 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000960 ReplaceText(LocStart, endBuf-startBuf,
961 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000962 }
Steve Naroffd40910b2008-12-01 20:33:01 +0000963 for (ObjCCategoryImplDecl::propimpl_iterator
964 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
965 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +0000966 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +0000967 }
968
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000969 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000970 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000971 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000972 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000973}
974
Steve Naroffb29b4272008-04-14 22:03:09 +0000975void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000976 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000977 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000978 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000979 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000980 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000981 ResultStr += "\n";
982 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000983 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000984 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000985 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000986 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000987 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000988 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000989 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000990 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000991 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000992
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000993 RewriteProperties(ClassDecl->getNumPropertyDecl(),
994 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000995 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000996 E = ClassDecl->instmeth_end(); I != E; ++I)
997 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000998 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000999 E = ClassDecl->classmeth_end(); I != E; ++I)
1000 RewriteMethodDeclaration(*I);
1001
Steve Naroff2feac5e2007-10-30 03:43:13 +00001002 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001003 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001004}
1005
Steve Naroffc77a6362008-12-04 16:24:46 +00001006Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt) {
1007 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1008 // This allows us to reuse all the fun and games in SynthMessageExpr().
1009 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1010 ObjCMessageExpr *MsgExpr;
1011 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1012 llvm::SmallVector<Expr *, 1> ExprVec;
1013 ExprVec.push_back(newStmt);
1014
1015 MsgExpr = new ObjCMessageExpr(PropRefExpr->getBase(),
1016 PDecl->getSetterName(), PDecl->getType(),
1017 PDecl->getSetterMethodDecl(),
1018 SourceLocation(), SourceLocation(),
1019 &ExprVec[0], 1);
1020 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1021
1022 // Now do the actual rewrite.
1023 ReplaceStmt(BinOp, ReplacingStmt);
1024 delete BinOp;
1025 delete MsgExpr;
1026 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001027}
1028
Steve Naroffc77a6362008-12-04 16:24:46 +00001029Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001030 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1031 // This allows us to reuse all the fun and games in SynthMessageExpr().
1032 ObjCMessageExpr *MsgExpr;
1033 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1034
1035 MsgExpr = new ObjCMessageExpr(PropRefExpr->getBase(),
1036 PDecl->getGetterName(), PDecl->getType(),
1037 PDecl->getGetterMethodDecl(),
1038 SourceLocation(), SourceLocation(),
1039 0, 0);
1040
Steve Naroff4c3580e2008-12-04 23:50:32 +00001041 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001042
Steve Naroff15f081d2008-12-03 00:56:33 +00001043 ReplaceStmt(PropRefExpr, ReplacingStmt);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001044
Steve Naroff15f081d2008-12-03 00:56:33 +00001045 // delete PropRefExpr; elsewhere...
1046 delete MsgExpr;
1047 return ReplacingStmt;
1048}
1049
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001050Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1051 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001052 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001053 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001054 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001055 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1056 // lookup which class implements the instance variable.
1057 ObjCInterfaceDecl *clsDeclared = 0;
1058 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1059 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1060
1061 // Synthesize an explicit cast to gain access to the ivar.
1062 std::string RecName = clsDeclared->getIdentifier()->getName();
1063 RecName += "_IMPL";
1064 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001065 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001066 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001067 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1068 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001069 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001070 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001071 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001072 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1073 IV->getBase()->getLocEnd(),
1074 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001075 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001076 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001077 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1078 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001079 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001080 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001081 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001082 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001083
1084 ReplaceStmt(IV->getBase(), PE);
1085 // Cannot delete IV->getBase(), since PE points to it.
1086 // Replace the old base with the cast. This is important when doing
1087 // embedded rewrites. For example, [newInv->_container addObject:0].
1088 IV->setBase(PE);
1089 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001090 }
Steve Naroff84472a82008-04-18 21:55:08 +00001091 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001092 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1093
1094 // Explicit ivar refs need to have a cast inserted.
1095 // FIXME: consider sharing some of this code with the code above.
1096 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001097 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001098 // lookup which class implements the instance variable.
1099 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001100 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001101 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1102
1103 // Synthesize an explicit cast to gain access to the ivar.
1104 std::string RecName = clsDeclared->getIdentifier()->getName();
1105 RecName += "_IMPL";
1106 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001107 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001108 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001109 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1110 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001111 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001112 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001113 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001114 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1115 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001116 ReplaceStmt(IV->getBase(), PE);
1117 // Cannot delete IV->getBase(), since PE points to it.
1118 // Replace the old base with the cast. This is important when doing
1119 // embedded rewrites. For example, [newInv->_container addObject:0].
1120 IV->setBase(PE);
1121 return IV;
1122 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001123 }
Steve Naroff84472a82008-04-18 21:55:08 +00001124 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001125}
1126
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001127/// SynthCountByEnumWithState - To print:
1128/// ((unsigned int (*)
1129/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1130/// (void *)objc_msgSend)((id)l_collection,
1131/// sel_registerName(
1132/// "countByEnumeratingWithState:objects:count:"),
1133/// &enumState,
1134/// (id *)items, (unsigned int)16)
1135///
Steve Naroffb29b4272008-04-14 22:03:09 +00001136void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001137 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1138 "id *, unsigned int))(void *)objc_msgSend)";
1139 buf += "\n\t\t";
1140 buf += "((id)l_collection,\n\t\t";
1141 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1142 buf += "\n\t\t";
1143 buf += "&enumState, "
1144 "(id *)items, (unsigned int)16)";
1145}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001146
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001147/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1148/// statement to exit to its outer synthesized loop.
1149///
Steve Naroffb29b4272008-04-14 22:03:09 +00001150Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001151 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1152 return S;
1153 // replace break with goto __break_label
1154 std::string buf;
1155
1156 SourceLocation startLoc = S->getLocStart();
1157 buf = "goto __break_label_";
1158 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001159 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001160
1161 return 0;
1162}
1163
1164/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1165/// statement to continue with its inner synthesized loop.
1166///
Steve Naroffb29b4272008-04-14 22:03:09 +00001167Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001168 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1169 return S;
1170 // replace continue with goto __continue_label
1171 std::string buf;
1172
1173 SourceLocation startLoc = S->getLocStart();
1174 buf = "goto __continue_label_";
1175 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001176 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001177
1178 return 0;
1179}
1180
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001181/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001182/// It rewrites:
1183/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001184
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001185/// Into:
1186/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001187/// type elem;
1188/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001189/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001190/// id l_collection = (id)collection;
1191/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1192/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001193/// if (limit) {
1194/// unsigned long startMutations = *enumState.mutationsPtr;
1195/// do {
1196/// unsigned long counter = 0;
1197/// do {
1198/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001199/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001200/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001201/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001202/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001203/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001204/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1205/// objects:items count:16]);
1206/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001207/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001208/// }
1209/// else
1210/// elem = nil;
1211/// }
1212///
Steve Naroffb29b4272008-04-14 22:03:09 +00001213Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001214 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001215 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1216 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1217 "ObjCForCollectionStmt Statement stack mismatch");
1218 assert(!ObjCBcLabelNo.empty() &&
1219 "ObjCForCollectionStmt - Label No stack empty");
1220
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001221 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001222 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001223 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001224 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001225 std::string buf;
1226 buf = "\n{\n\t";
1227 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1228 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001229 ScopedDecl* D = DS->getSolitaryDecl();
1230 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001231 elementTypeAsString = ElementType.getAsString();
1232 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001233 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001234 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001235 buf += elementName;
1236 buf += ";\n\t";
1237 }
Chris Lattner06767512008-04-08 05:52:18 +00001238 else {
1239 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001240 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001241 elementTypeAsString
1242 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001243 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001244
1245 // struct __objcFastEnumerationState enumState = { 0 };
1246 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1247 // id items[16];
1248 buf += "id items[16];\n\t";
1249 // id l_collection = (id)
1250 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001251 // Find start location of 'collection' the hard way!
1252 const char *startCollectionBuf = startBuf;
1253 startCollectionBuf += 3; // skip 'for'
1254 startCollectionBuf = strchr(startCollectionBuf, '(');
1255 startCollectionBuf++; // skip '('
1256 // find 'in' and skip it.
1257 while (*startCollectionBuf != ' ' ||
1258 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1259 (*(startCollectionBuf+3) != ' ' &&
1260 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1261 startCollectionBuf++;
1262 startCollectionBuf += 3;
1263
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001264 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001265 ReplaceText(startLoc, startCollectionBuf - startBuf,
1266 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001267 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001268 SourceLocation rightParenLoc = S->getRParenLoc();
1269 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1270 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001271 buf = ";\n\t";
1272
1273 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1274 // objects:items count:16];
1275 // which is synthesized into:
1276 // unsigned int limit =
1277 // ((unsigned int (*)
1278 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1279 // (void *)objc_msgSend)((id)l_collection,
1280 // sel_registerName(
1281 // "countByEnumeratingWithState:objects:count:"),
1282 // (struct __objcFastEnumerationState *)&state,
1283 // (id *)items, (unsigned int)16);
1284 buf += "unsigned long limit =\n\t\t";
1285 SynthCountByEnumWithState(buf);
1286 buf += ";\n\t";
1287 /// if (limit) {
1288 /// unsigned long startMutations = *enumState.mutationsPtr;
1289 /// do {
1290 /// unsigned long counter = 0;
1291 /// do {
1292 /// if (startMutations != *enumState.mutationsPtr)
1293 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001294 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001295 buf += "if (limit) {\n\t";
1296 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1297 buf += "do {\n\t\t";
1298 buf += "unsigned long counter = 0;\n\t\t";
1299 buf += "do {\n\t\t\t";
1300 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1301 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1302 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001303 buf += " = (";
1304 buf += elementTypeAsString;
1305 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001306 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001307 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001308
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001309 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001310 /// } while (counter < limit);
1311 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1312 /// objects:items count:16]);
1313 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001314 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001315 /// }
1316 /// else
1317 /// elem = nil;
1318 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001319 ///
1320 buf = ";\n\t";
1321 buf += "__continue_label_";
1322 buf += utostr(ObjCBcLabelNo.back());
1323 buf += ": ;";
1324 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001325 buf += "} while (counter < limit);\n\t";
1326 buf += "} while (limit = ";
1327 SynthCountByEnumWithState(buf);
1328 buf += ");\n\t";
1329 buf += elementName;
1330 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001331 buf += "__break_label_";
1332 buf += utostr(ObjCBcLabelNo.back());
1333 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001334 buf += "}\n\t";
1335 buf += "else\n\t\t";
1336 buf += elementName;
1337 buf += " = nil;\n";
1338 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001339
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001340 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001341 if (isa<CompoundStmt>(S->getBody())) {
1342 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1343 InsertText(endBodyLoc, buf.c_str(), buf.size());
1344 } else {
1345 /* Need to treat single statements specially. For example:
1346 *
1347 * for (A *a in b) if (stuff()) break;
1348 * for (A *a in b) xxxyy;
1349 *
1350 * The following code simply scans ahead to the semi to find the actual end.
1351 */
1352 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1353 const char *semiBuf = strchr(stmtBuf, ';');
1354 assert(semiBuf && "Can't find ';'");
1355 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1356 InsertText(endBodyLoc, buf.c_str(), buf.size());
1357 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001358 Stmts.pop_back();
1359 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001360 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001361}
1362
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001363/// RewriteObjCSynchronizedStmt -
1364/// This routine rewrites @synchronized(expr) stmt;
1365/// into:
1366/// objc_sync_enter(expr);
1367/// @try stmt @finally { objc_sync_exit(expr); }
1368///
Steve Naroffb29b4272008-04-14 22:03:09 +00001369Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001370 // Get the start location and compute the semi location.
1371 SourceLocation startLoc = S->getLocStart();
1372 const char *startBuf = SM->getCharacterData(startLoc);
1373
1374 assert((*startBuf == '@') && "bogus @synchronized location");
1375
1376 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001377 buf = "objc_sync_enter((id)";
1378 const char *lparenBuf = startBuf;
1379 while (*lparenBuf != '(') lparenBuf++;
1380 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001381 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1382 // the sync expression is typically a message expression that's already
1383 // been rewritten! (which implies the SourceLocation's are invalid).
1384 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001385 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001386 while (*endBuf != ')') endBuf--;
1387 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001388 buf = ");\n";
1389 // declare a new scope with two variables, _stack and _rethrow.
1390 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1391 buf += "int buf[18/*32-bit i386*/];\n";
1392 buf += "char *pointers[4];} _stack;\n";
1393 buf += "id volatile _rethrow = 0;\n";
1394 buf += "objc_exception_try_enter(&_stack);\n";
1395 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001396 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001397 startLoc = S->getSynchBody()->getLocEnd();
1398 startBuf = SM->getCharacterData(startLoc);
1399
Steve Naroffc7089f12008-08-19 13:04:19 +00001400 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001401 SourceLocation lastCurlyLoc = startLoc;
1402 buf = "}\nelse {\n";
1403 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1404 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001405 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001406 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001407 S->getSynchExpr(),
1408 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001409 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001410 std::string syncExprBufS;
1411 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001412 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001413 buf += syncExprBuf.str();
1414 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001415 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1416 buf += "}\n";
1417 buf += "}";
1418
Chris Lattneraadaf782008-01-31 19:51:04 +00001419 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001420 return 0;
1421}
1422
Steve Naroffb29b4272008-04-14 22:03:09 +00001423Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001424 // Get the start location and compute the semi location.
1425 SourceLocation startLoc = S->getLocStart();
1426 const char *startBuf = SM->getCharacterData(startLoc);
1427
1428 assert((*startBuf == '@') && "bogus @try location");
1429
1430 std::string buf;
1431 // declare a new scope with two variables, _stack and _rethrow.
1432 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1433 buf += "int buf[18/*32-bit i386*/];\n";
1434 buf += "char *pointers[4];} _stack;\n";
1435 buf += "id volatile _rethrow = 0;\n";
1436 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001437 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001438
Chris Lattneraadaf782008-01-31 19:51:04 +00001439 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001440
1441 startLoc = S->getTryBody()->getLocEnd();
1442 startBuf = SM->getCharacterData(startLoc);
1443
1444 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001445
Steve Naroff75730982007-11-07 04:08:17 +00001446 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001447 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1448 if (catchList) {
1449 startLoc = startLoc.getFileLocWithOffset(1);
1450 buf = " /* @catch begin */ else {\n";
1451 buf += " id _caught = objc_exception_extract(&_stack);\n";
1452 buf += " objc_exception_try_enter (&_stack);\n";
1453 buf += " if (_setjmp(_stack.buf))\n";
1454 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1455 buf += " else { /* @catch continue */";
1456
1457 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001458 } else { /* no catch list */
1459 buf = "}\nelse {\n";
1460 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1461 buf += "}";
1462 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001463 }
Steve Naroff75730982007-11-07 04:08:17 +00001464 bool sawIdTypedCatch = false;
1465 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001466 while (catchList) {
1467 Stmt *catchStmt = catchList->getCatchParamStmt();
1468
1469 if (catchList == S->getCatchStmts())
1470 buf = "if ("; // we are generating code for the first catch clause
1471 else
1472 buf = "else if (";
1473 startLoc = catchList->getLocStart();
1474 startBuf = SM->getCharacterData(startLoc);
1475
1476 assert((*startBuf == '@') && "bogus @catch location");
1477
1478 const char *lParenLoc = strchr(startBuf, '(');
1479
Steve Naroffbe4b3332008-02-01 22:08:12 +00001480 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001481 // Now rewrite the body...
1482 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001483 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1484 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001485 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1486 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001487 assert((*bodyBuf == '{') && "bogus @catch body location");
1488
1489 buf += "1) { id _tmp = _caught;";
1490 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1491 buf.c_str(), buf.size());
1492 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001493 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001494 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001495 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001496 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001497 sawIdTypedCatch = true;
1498 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001499 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001500
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001501 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001502 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001503 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001504 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001505 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001506 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001507 }
1508 }
1509 // Now rewrite the body...
1510 lastCatchBody = catchList->getCatchBody();
1511 SourceLocation rParenLoc = catchList->getRParenLoc();
1512 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1513 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1514 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1515 assert((*rParenBuf == ')') && "bogus @catch paren location");
1516 assert((*bodyBuf == '{') && "bogus @catch body location");
1517
1518 buf = " = _caught;";
1519 // Here we replace ") {" with "= _caught;" (which initializes and
1520 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001521 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001522 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001523 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001524 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001525 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001526 catchList = catchList->getNextCatchStmt();
1527 }
1528 // Complete the catch list...
1529 if (lastCatchBody) {
1530 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001531 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1532 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001533
Steve Naroff378f47a2008-09-11 15:29:03 +00001534 // Insert the last (implicit) else clause *before* the right curly brace.
1535 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1536 buf = "} /* last catch end */\n";
1537 buf += "else {\n";
1538 buf += " _rethrow = _caught;\n";
1539 buf += " objc_exception_try_exit(&_stack);\n";
1540 buf += "} } /* @catch end */\n";
1541 if (!S->getFinallyStmt())
1542 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001543 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001544
1545 // Set lastCurlyLoc
1546 lastCurlyLoc = lastCatchBody->getLocEnd();
1547 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001548 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001549 startLoc = finalStmt->getLocStart();
1550 startBuf = SM->getCharacterData(startLoc);
1551 assert((*startBuf == '@') && "bogus @finally start");
1552
1553 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001554 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001555
1556 Stmt *body = finalStmt->getFinallyBody();
1557 SourceLocation startLoc = body->getLocStart();
1558 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001559 assert(*SM->getCharacterData(startLoc) == '{' &&
1560 "bogus @finally body location");
1561 assert(*SM->getCharacterData(endLoc) == '}' &&
1562 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001563
1564 startLoc = startLoc.getFileLocWithOffset(1);
1565 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001566 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001567 endLoc = endLoc.getFileLocWithOffset(-1);
1568 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001569 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001570
1571 // Set lastCurlyLoc
1572 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001573 } else { /* no finally clause - make sure we synthesize an implicit one */
1574 buf = "{ /* implicit finally clause */\n";
1575 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1576 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1577 buf += "}";
1578 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001579 }
1580 // Now emit the final closing curly brace...
1581 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1582 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001583 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001584 return 0;
1585}
1586
Steve Naroffb29b4272008-04-14 22:03:09 +00001587Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001588 return 0;
1589}
1590
Steve Naroffb29b4272008-04-14 22:03:09 +00001591Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001592 return 0;
1593}
1594
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001595// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001596// the throw expression is typically a message expression that's already
1597// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001598Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001599 // Get the start location and compute the semi location.
1600 SourceLocation startLoc = S->getLocStart();
1601 const char *startBuf = SM->getCharacterData(startLoc);
1602
1603 assert((*startBuf == '@') && "bogus @throw location");
1604
1605 std::string buf;
1606 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001607 if (S->getThrowExpr())
1608 buf = "objc_exception_throw(";
1609 else // add an implicit argument
1610 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001611
1612 // handle "@ throw" correctly.
1613 const char *wBuf = strchr(startBuf, 'w');
1614 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1615 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1616
Steve Naroff2bd03922007-11-07 15:32:26 +00001617 const char *semiBuf = strchr(startBuf, ';');
1618 assert((*semiBuf == ';') && "@throw: can't find ';'");
1619 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1620 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001621 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001622 return 0;
1623}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001624
Steve Naroffb29b4272008-04-14 22:03:09 +00001625Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001626 // Create a new string expression.
1627 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001628 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001629 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001630 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1631 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001632 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001633 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001634
Chris Lattner07506182007-11-30 22:53:43 +00001635 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001636 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001637 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001638}
1639
Steve Naroffb29b4272008-04-14 22:03:09 +00001640Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001641 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1642 // Create a call to sel_registerName("selName").
1643 llvm::SmallVector<Expr*, 8> SelExprs;
1644 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001645 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1646 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001647 false, argType, SourceLocation(),
1648 SourceLocation()));
1649 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1650 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001651 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001652 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001653 return SelExp;
1654}
1655
Steve Naroffb29b4272008-04-14 22:03:09 +00001656CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001657 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001658 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001659 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001660
1661 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001662 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001663
1664 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001665 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001666 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1667 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001668
1669 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001670
Steve Naroff934f2762007-10-24 22:48:43 +00001671 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1672}
1673
Steve Naroffd5255f52007-11-01 13:24:47 +00001674static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1675 const char *&startRef, const char *&endRef) {
1676 while (startBuf < endBuf) {
1677 if (*startBuf == '<')
1678 startRef = startBuf; // mark the start.
1679 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001680 if (startRef && *startRef == '<') {
1681 endRef = startBuf; // mark the end.
1682 return true;
1683 }
1684 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001685 }
1686 startBuf++;
1687 }
1688 return false;
1689}
1690
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001691static void scanToNextArgument(const char *&argRef) {
1692 int angle = 0;
1693 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1694 if (*argRef == '<')
1695 angle++;
1696 else if (*argRef == '>')
1697 angle--;
1698 argRef++;
1699 }
1700 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1701}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001702
Steve Naroffb29b4272008-04-14 22:03:09 +00001703bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001704
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001705 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001706 return true;
1707
Steve Naroffd5255f52007-11-01 13:24:47 +00001708 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001709 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001710 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001711 return true; // we have "Class <Protocol> *".
1712 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001713 return false;
1714}
1715
Steve Naroff4f95b752008-07-29 18:15:38 +00001716void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1717 QualType Type = E->getType();
1718 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001719 SourceLocation Loc, EndLoc;
1720
1721 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1722 Loc = ECE->getLParenLoc();
1723 EndLoc = ECE->getRParenLoc();
1724 } else {
1725 Loc = E->getLocStart();
1726 EndLoc = E->getLocEnd();
1727 }
1728 // This will defend against trying to rewrite synthesized expressions.
1729 if (Loc.isInvalid() || EndLoc.isInvalid())
1730 return;
1731
Steve Naroff4f95b752008-07-29 18:15:38 +00001732 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001733 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001734 const char *startRef = 0, *endRef = 0;
1735 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1736 // Get the locations of the startRef, endRef.
1737 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1738 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1739 // Comment out the protocol references.
1740 InsertText(LessLoc, "/*", 2);
1741 InsertText(GreaterLoc, "*/", 2);
1742 }
1743 }
1744}
1745
Steve Naroffb29b4272008-04-14 22:03:09 +00001746void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001747 SourceLocation Loc;
1748 QualType Type;
1749 const FunctionTypeProto *proto = 0;
1750 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1751 Loc = VD->getLocation();
1752 Type = VD->getType();
1753 }
1754 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1755 Loc = FD->getLocation();
1756 // Check for ObjC 'id' and class types that have been adorned with protocol
1757 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1758 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1759 assert(funcType && "missing function type");
1760 proto = dyn_cast<FunctionTypeProto>(funcType);
1761 if (!proto)
1762 return;
1763 Type = proto->getResultType();
1764 }
1765 else
1766 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001767
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001768 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001769 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001770
1771 const char *endBuf = SM->getCharacterData(Loc);
1772 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001773 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001774 startBuf--; // scan backward (from the decl location) for return type.
1775 const char *startRef = 0, *endRef = 0;
1776 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1777 // Get the locations of the startRef, endRef.
1778 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1779 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1780 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001781 InsertText(LessLoc, "/*", 2);
1782 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001783 }
1784 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001785 if (!proto)
1786 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001787 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001788 const char *startBuf = SM->getCharacterData(Loc);
1789 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001790 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1791 if (needToScanForQualifiers(proto->getArgType(i))) {
1792 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001793
Steve Naroffd5255f52007-11-01 13:24:47 +00001794 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001795 // scan forward (from the decl location) for argument types.
1796 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001797 const char *startRef = 0, *endRef = 0;
1798 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1799 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001800 SourceLocation LessLoc =
1801 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1802 SourceLocation GreaterLoc =
1803 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001804 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001805 InsertText(LessLoc, "/*", 2);
1806 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001807 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001808 startBuf = ++endBuf;
1809 }
1810 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001811 // If the function name is derived from a macro expansion, then the
1812 // argument buffer will not follow the name. Need to speak with Chris.
1813 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001814 startBuf++; // scan forward (from the decl location) for argument types.
1815 startBuf++;
1816 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001817 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001818}
1819
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001820// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001821void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001822 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1823 llvm::SmallVector<QualType, 16> ArgTys;
1824 ArgTys.push_back(Context->getPointerType(
1825 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001826 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001827 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001828 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001829 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001830 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001831 SelGetUidIdent, getFuncType,
1832 FunctionDecl::Extern, false, 0);
1833}
1834
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001835// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001836void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001837 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1838 llvm::SmallVector<QualType, 16> ArgTys;
1839 ArgTys.push_back(Context->getPointerType(
1840 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001841 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001842 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001843 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001844 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001845 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001846 SelGetProtoIdent, getFuncType,
1847 FunctionDecl::Extern, false, 0);
1848}
1849
Steve Naroffb29b4272008-04-14 22:03:09 +00001850void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001851 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001852 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001853 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001854 return;
1855 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001856 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001857}
1858
Steve Naroffc0a123c2008-03-11 17:37:02 +00001859// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001860void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001861 if (SuperContructorFunctionDecl)
1862 return;
1863 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1864 llvm::SmallVector<QualType, 16> ArgTys;
1865 QualType argT = Context->getObjCIdType();
1866 assert(!argT.isNull() && "Can't find 'id' type");
1867 ArgTys.push_back(argT);
1868 ArgTys.push_back(argT);
1869 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1870 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001871 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001872 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001873 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001874 msgSendIdent, msgSendType,
1875 FunctionDecl::Extern, false, 0);
1876}
1877
Steve Naroff09b266e2007-10-30 23:14:51 +00001878// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001879void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001880 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1881 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001882 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001883 assert(!argT.isNull() && "Can't find 'id' type");
1884 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001885 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001886 assert(!argT.isNull() && "Can't find 'SEL' type");
1887 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001888 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001889 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001890 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001891 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001892 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001893 msgSendIdent, msgSendType,
1894 FunctionDecl::Extern, false, 0);
1895}
1896
Steve Naroff874e2322007-11-15 10:28:18 +00001897// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001898void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001899 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1900 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001901 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001902 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001903 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001904 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1905 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1906 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001907 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001908 assert(!argT.isNull() && "Can't find 'SEL' type");
1909 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001910 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001911 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001912 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001913 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001914 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001915 msgSendIdent, msgSendType,
1916 FunctionDecl::Extern, false, 0);
1917}
1918
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001919// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001920void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001921 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1922 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001923 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001924 assert(!argT.isNull() && "Can't find 'id' type");
1925 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001926 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001927 assert(!argT.isNull() && "Can't find 'SEL' type");
1928 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001929 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001930 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001931 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001932 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001933 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001934 msgSendIdent, msgSendType,
1935 FunctionDecl::Extern, false, 0);
1936}
1937
1938// SynthMsgSendSuperStretFunctionDecl -
1939// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001940void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001941 IdentifierInfo *msgSendIdent =
1942 &Context->Idents.get("objc_msgSendSuper_stret");
1943 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001944 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001945 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001946 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001947 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1948 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1949 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001950 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001951 assert(!argT.isNull() && "Can't find 'SEL' type");
1952 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001953 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001954 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001955 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001956 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001957 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001958 msgSendIdent, msgSendType,
1959 FunctionDecl::Extern, false, 0);
1960}
1961
Steve Naroff1284db82008-05-08 22:02:18 +00001962// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001963void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001964 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1965 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001966 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001967 assert(!argT.isNull() && "Can't find 'id' type");
1968 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001969 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001970 assert(!argT.isNull() && "Can't find 'SEL' type");
1971 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001972 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001973 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001974 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001975 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001976 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001977 msgSendIdent, msgSendType,
1978 FunctionDecl::Extern, false, 0);
1979}
1980
Steve Naroff09b266e2007-10-30 23:14:51 +00001981// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001982void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001983 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1984 llvm::SmallVector<QualType, 16> ArgTys;
1985 ArgTys.push_back(Context->getPointerType(
1986 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001987 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001988 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001989 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001990 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001991 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001992 getClassIdent, getClassType,
1993 FunctionDecl::Extern, false, 0);
1994}
1995
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001996// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001997void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001998 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1999 llvm::SmallVector<QualType, 16> ArgTys;
2000 ArgTys.push_back(Context->getPointerType(
2001 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002002 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002003 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002004 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002005 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002006 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002007 getClassIdent, getClassType,
2008 FunctionDecl::Extern, false, 0);
2009}
2010
Steve Naroffb29b4272008-04-14 22:03:09 +00002011Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002012 QualType strType = getConstantStringStructType();
2013
2014 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002015
2016 std::string tmpName = InFileName;
2017 unsigned i;
2018 for (i=0; i < tmpName.length(); i++) {
2019 char c = tmpName.at(i);
2020 // replace any non alphanumeric characters with '_'.
2021 if (!isalpha(c) && (c < '0' || c > '9'))
2022 tmpName[i] = '_';
2023 }
2024 S += tmpName;
2025 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002026 S += utostr(NumObjCStringLiterals++);
2027
Steve Naroffba92b2e2008-03-27 22:29:16 +00002028 Preamble += "static __NSConstantStringImpl " + S;
2029 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2030 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002031 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002032 std::string prettyBufS;
2033 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002034 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002035 Preamble += prettyBuf.str();
2036 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002037 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002038 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002039
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002040 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002041 &Context->Idents.get(S.c_str()), strType,
2042 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002043 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2044 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2045 Context->getPointerType(DRE->getType()),
2046 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002047 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002048 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002049 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002050 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002051 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002052 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002053}
2054
Steve Naroffb29b4272008-04-14 22:03:09 +00002055ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002056 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002057 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002058
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002059 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2060 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002061 assert(PT);
2062 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2063 return IT->getDecl();
2064 }
2065 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002066}
2067
2068// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002069QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002070 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002071 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002072 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002073 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002074 QualType FieldTypes[2];
2075
2076 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002077 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002078 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002079 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002080 // Create fields
2081 FieldDecl *FieldDecls[2];
2082
2083 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002084 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002085 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002086
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002087 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002088 }
2089 return Context->getTagDeclType(SuperStructDecl);
2090}
2091
Steve Naroffb29b4272008-04-14 22:03:09 +00002092QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002093 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002094 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002095 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002096 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002097 QualType FieldTypes[4];
2098
2099 // struct objc_object *receiver;
2100 FieldTypes[0] = Context->getObjCIdType();
2101 // int flags;
2102 FieldTypes[1] = Context->IntTy;
2103 // char *str;
2104 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2105 // long length;
2106 FieldTypes[3] = Context->LongTy;
2107 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002108 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002109
2110 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002111 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002112 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002113
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002114 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002115 }
2116 return Context->getTagDeclType(ConstantStringDecl);
2117}
2118
Steve Naroffb29b4272008-04-14 22:03:09 +00002119Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002120 if (!SelGetUidFunctionDecl)
2121 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002122 if (!MsgSendFunctionDecl)
2123 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002124 if (!MsgSendSuperFunctionDecl)
2125 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002126 if (!MsgSendStretFunctionDecl)
2127 SynthMsgSendStretFunctionDecl();
2128 if (!MsgSendSuperStretFunctionDecl)
2129 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002130 if (!MsgSendFpretFunctionDecl)
2131 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002132 if (!GetClassFunctionDecl)
2133 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002134 if (!GetMetaClassFunctionDecl)
2135 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002136
Steve Naroff874e2322007-11-15 10:28:18 +00002137 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002138 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2139 // May need to use objc_msgSend_stret() as well.
2140 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002141 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002142 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002143 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002144 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002145 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002146 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002147 }
Steve Naroff874e2322007-11-15 10:28:18 +00002148
Steve Naroff934f2762007-10-24 22:48:43 +00002149 // Synthesize a call to objc_msgSend().
2150 llvm::SmallVector<Expr*, 8> MsgExprs;
2151 IdentifierInfo *clsName = Exp->getClassName();
2152
2153 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2154 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002155 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2156 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002157 if (!strcmp(clsName->getName(), "super")) {
2158 MsgSendFlavor = MsgSendSuperFunctionDecl;
2159 if (MsgSendStretFlavor)
2160 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2161 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2162
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002163 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002164 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002165
2166 llvm::SmallVector<Expr*, 4> InitExprs;
2167
2168 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002169 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002170 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002171 Context->getObjCIdType(),
2172 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002173 llvm::SmallVector<Expr*, 8> ClsExprs;
2174 QualType argType = Context->getPointerType(Context->CharTy);
2175 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2176 SuperDecl->getIdentifier()->getLength(),
2177 false, argType, SourceLocation(),
2178 SourceLocation()));
2179 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2180 &ClsExprs[0],
2181 ClsExprs.size());
2182 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002183 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002184 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002185 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002186 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002187 // struct objc_super
2188 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002189 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002190
Steve Naroff23f41272008-03-11 18:14:26 +00002191 if (LangOpts.Microsoft) {
2192 SynthSuperContructorFunctionDecl();
2193 // Simulate a contructor call...
2194 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2195 superType, SourceLocation());
2196 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2197 superType, SourceLocation());
2198 } else {
2199 // (struct objc_super) { <exprs from above> }
2200 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2201 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002202 SourceLocation(), false);
2203 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2204 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002205 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002206 // struct objc_super *
2207 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2208 Context->getPointerType(SuperRep->getType()),
2209 SourceLocation());
2210 MsgExprs.push_back(Unop);
2211 } else {
2212 llvm::SmallVector<Expr*, 8> ClsExprs;
2213 QualType argType = Context->getPointerType(Context->CharTy);
2214 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2215 clsName->getLength(),
2216 false, argType, SourceLocation(),
2217 SourceLocation()));
2218 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2219 &ClsExprs[0],
2220 ClsExprs.size());
2221 MsgExprs.push_back(Cls);
2222 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002223 } else { // instance message.
2224 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002225
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002226 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002227 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002228 if (MsgSendStretFlavor)
2229 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002230 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2231
2232 llvm::SmallVector<Expr*, 4> InitExprs;
2233
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002234 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002235 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002236 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002237 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002238 SourceLocation()),
2239 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002240 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002241
2242 llvm::SmallVector<Expr*, 8> ClsExprs;
2243 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002244 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2245 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002246 false, argType, SourceLocation(),
2247 SourceLocation()));
2248 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002249 &ClsExprs[0],
2250 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002251 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002252 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002253 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002254 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002255 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002256 // struct objc_super
2257 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002258 Expr *SuperRep;
2259
2260 if (LangOpts.Microsoft) {
2261 SynthSuperContructorFunctionDecl();
2262 // Simulate a contructor call...
2263 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2264 superType, SourceLocation());
2265 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2266 superType, SourceLocation());
2267 } else {
2268 // (struct objc_super) { <exprs from above> }
2269 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2270 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002271 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002272 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2273 }
Steve Naroff874e2322007-11-15 10:28:18 +00002274 // struct objc_super *
2275 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2276 Context->getPointerType(SuperRep->getType()),
2277 SourceLocation());
2278 MsgExprs.push_back(Unop);
2279 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002280 // Remove all type-casts because it may contain objc-style types; e.g.
2281 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002282 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002283 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002284 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002285 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002286 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002287 MsgExprs.push_back(recExpr);
2288 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002289 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002290 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002291 llvm::SmallVector<Expr*, 8> SelExprs;
2292 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002293 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2294 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002295 false, argType, SourceLocation(),
2296 SourceLocation()));
2297 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2298 &SelExprs[0], SelExprs.size());
2299 MsgExprs.push_back(SelExp);
2300
2301 // Now push any user supplied arguments.
2302 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002303 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002304 // Make all implicit casts explicit...ICE comes in handy:-)
2305 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2306 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002307 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002308 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002309 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002310 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002311 }
2312 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002313 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002314 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002315 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002316 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002317 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002318 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002319 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002320 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002321 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002322 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002323 // We've transferred the ownership to MsgExprs. Null out the argument in
2324 // the original expression, since we will delete it below.
2325 Exp->setArg(i, 0);
2326 }
Steve Naroffab972d32007-11-04 22:37:50 +00002327 // Generate the funky cast.
2328 CastExpr *cast;
2329 llvm::SmallVector<QualType, 8> ArgTypes;
2330 QualType returnType;
2331
2332 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002333 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2334 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2335 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002336 ArgTypes.push_back(Context->getObjCIdType());
2337 ArgTypes.push_back(Context->getObjCSelType());
2338 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002339 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002340 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002341 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2342 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002343 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002344 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2345 if (isBlockPointerType(t)) {
2346 const BlockPointerType *BPT = t->getAsBlockPointerType();
2347 t = Context->getPointerType(BPT->getPointeeType());
2348 }
Steve Naroff352336b2007-11-05 14:36:37 +00002349 ArgTypes.push_back(t);
2350 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002351 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2352 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002353 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002354 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002355 }
2356 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002357 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002358
2359 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002360 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2361 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002362
2363 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2364 // If we don't do this cast, we get the following bizarre warning/note:
2365 // xx.m:13: warning: function called through a non-compatible type
2366 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002367 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002368 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002369 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002370
Steve Naroffab972d32007-11-04 22:37:50 +00002371 // Now do the "normal" pointer to function cast.
2372 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002373 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002374 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002375 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002376 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002377 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002378
2379 // Don't forget the parens to enforce the proper binding.
2380 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2381
2382 const FunctionType *FT = msgSendType->getAsFunctionType();
2383 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2384 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002385 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002386 if (MsgSendStretFlavor) {
2387 // We have the method which returns a struct/union. Must also generate
2388 // call to objc_msgSend_stret and hang both varieties on a conditional
2389 // expression which dictate which one to envoke depending on size of
2390 // method's return type.
2391
2392 // Create a reference to the objc_msgSend_stret() declaration.
2393 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2394 SourceLocation());
2395 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002396 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002397 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002398 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002399 // Now do the "normal" pointer to function cast.
2400 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002401 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002402 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002403 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002404 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002405
2406 // Don't forget the parens to enforce the proper binding.
2407 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2408
2409 FT = msgSendType->getAsFunctionType();
2410 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2411 FT->getResultType(), SourceLocation());
2412
2413 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002414 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2415 returnType.getAsOpaquePtr(),
2416 Context->getSizeType(),
2417 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002418 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2419 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2420 // For X86 it is more complicated and some kind of target specific routine
2421 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002422 unsigned IntSize =
2423 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002424 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2425 Context->IntTy,
2426 SourceLocation());
2427 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2428 BinaryOperator::LE,
2429 Context->IntTy,
2430 SourceLocation());
2431 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2432 ConditionalOperator *CondExpr =
2433 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002434 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002435 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002436 return ReplacingStmt;
2437}
2438
Steve Naroffb29b4272008-04-14 22:03:09 +00002439Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002440 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002441
Steve Naroffc77a6362008-12-04 16:24:46 +00002442 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002443 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002444 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002445
Steve Naroff4c3580e2008-12-04 23:50:32 +00002446 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002447 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002448}
2449
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002450/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2451/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002452Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002453 if (!GetProtocolFunctionDecl)
2454 SynthGetProtocolFunctionDecl();
2455 // Create a call to objc_getProtocol("ProtocolName").
2456 llvm::SmallVector<Expr*, 8> ProtoExprs;
2457 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002458 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2459 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002460 false, argType, SourceLocation(),
2461 SourceLocation()));
2462 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2463 &ProtoExprs[0],
2464 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002465 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002466 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002467 return ProtoExp;
2468
2469}
2470
Steve Naroffbaf58c32008-05-31 14:15:04 +00002471bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2472 const char *endBuf) {
2473 while (startBuf < endBuf) {
2474 if (*startBuf == '#') {
2475 // Skip whitespace.
2476 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2477 ;
2478 if (!strncmp(startBuf, "if", strlen("if")) ||
2479 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2480 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2481 !strncmp(startBuf, "define", strlen("define")) ||
2482 !strncmp(startBuf, "undef", strlen("undef")) ||
2483 !strncmp(startBuf, "else", strlen("else")) ||
2484 !strncmp(startBuf, "elif", strlen("elif")) ||
2485 !strncmp(startBuf, "endif", strlen("endif")) ||
2486 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2487 !strncmp(startBuf, "include", strlen("include")) ||
2488 !strncmp(startBuf, "import", strlen("import")) ||
2489 !strncmp(startBuf, "include_next", strlen("include_next")))
2490 return true;
2491 }
2492 startBuf++;
2493 }
2494 return false;
2495}
2496
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002497/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002498/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002499void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002500 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002501 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002502 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002503 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002504 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002505 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002506 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002507 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002508 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002509 SourceLocation LocStart = CDecl->getLocStart();
2510 SourceLocation LocEnd = CDecl->getLocEnd();
2511
2512 const char *startBuf = SM->getCharacterData(LocStart);
2513 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002514
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002515 // If no ivars and no root or if its root, directly or indirectly,
2516 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002517 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2518 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002519 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002520 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002521 return;
2522 }
2523
2524 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002525 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002526 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002527 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002528 if (LangOpts.Microsoft)
2529 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002530
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002531 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002532 const char *cursor = strchr(startBuf, '{');
2533 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002534 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002535 // If the buffer contains preprocessor directives, we do more fine-grained
2536 // rewrites. This is intended to fix code that looks like (which occurs in
2537 // NSURL.h, for example):
2538 //
2539 // #ifdef XYZ
2540 // @interface Foo : NSObject
2541 // #else
2542 // @interface FooBar : NSObject
2543 // #endif
2544 // {
2545 // int i;
2546 // }
2547 // @end
2548 //
2549 // This clause is segregated to avoid breaking the common case.
2550 if (BufferContainsPPDirectives(startBuf, cursor)) {
2551 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2552 CDecl->getClassLoc();
2553 const char *endHeader = SM->getCharacterData(L);
2554 endHeader += Lexer::MeasureTokenLength(L, *SM);
2555
Chris Lattner3db6cae2008-07-21 18:19:38 +00002556 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002557 // advance to the end of the referenced protocols.
2558 while (endHeader < cursor && *endHeader != '>') endHeader++;
2559 endHeader++;
2560 }
2561 // rewrite the original header
2562 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2563 } else {
2564 // rewrite the original header *without* disturbing the '{'
2565 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2566 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002567 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002568 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002569 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002570 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002571 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002572 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002573
2574 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002575 SourceLocation OnePastCurly =
2576 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2577 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002578 }
2579 cursor++; // past '{'
2580
2581 // Now comment out any visibility specifiers.
2582 while (cursor < endBuf) {
2583 if (*cursor == '@') {
2584 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002585 // Skip whitespace.
2586 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2587 /*scan*/;
2588
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002589 // FIXME: presence of @public, etc. inside comment results in
2590 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002591 if (!strncmp(cursor, "public", strlen("public")) ||
2592 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002593 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002594 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002595 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002596 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002597 // FIXME: If there are cases where '<' is used in ivar declaration part
2598 // of user code, then scan the ivar list and use needToScanForQualifiers
2599 // for type checking.
2600 else if (*cursor == '<') {
2601 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002602 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002603 cursor = strchr(cursor, '>');
2604 cursor++;
2605 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002606 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002607 } else if (*cursor == '^') { // rewrite block specifier.
2608 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2609 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002610 }
Steve Narofffea763e82007-11-14 19:25:57 +00002611 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002612 }
Steve Narofffea763e82007-11-14 19:25:57 +00002613 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002614 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002615 } else { // we don't have any instance variables - insert super struct.
2616 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2617 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002618 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002619 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002620 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002621 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002622 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002623 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002624 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002625 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002626 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002627}
2628
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002629// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002630/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002631void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002632 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002633 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002634 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002635 const char *ClassName,
2636 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002637 if (MethodBegin == MethodEnd) return;
2638
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002639 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002640 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002641 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002642 SEL _cmd;
2643 char *method_types;
2644 void *_imp;
2645 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002646 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002647 Result += "\nstruct _objc_method {\n";
2648 Result += "\tSEL _cmd;\n";
2649 Result += "\tchar *method_types;\n";
2650 Result += "\tvoid *_imp;\n";
2651 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002652
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002653 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002654 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002655
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002656 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002657
2658 /* struct {
2659 struct _objc_method_list *next_method;
2660 int method_count;
2661 struct _objc_method method_list[];
2662 }
2663 */
2664 Result += "\nstatic struct {\n";
2665 Result += "\tstruct _objc_method_list *next_method;\n";
2666 Result += "\tint method_count;\n";
2667 Result += "\tstruct _objc_method method_list[";
2668 Result += utostr(MethodEnd-MethodBegin);
2669 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002670 Result += prefix;
2671 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2672 Result += "_METHODS_";
2673 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002674 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002675 Result += IsInstanceMethod ? "inst" : "cls";
2676 Result += "_meth\")))= ";
2677 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002678
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002679 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002680 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002681 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002682 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002683 Result += "\", \"";
2684 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002685 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002686 Result += MethodInternalNames[*MethodBegin];
2687 Result += "}\n";
2688 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2689 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002690 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002691 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002692 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002693 Result += "\", \"";
2694 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002695 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002696 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002697 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002698 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002699 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002700}
2701
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002702/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002703void RewriteObjC::
2704RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2705 const char *prefix,
2706 const char *ClassName,
2707 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002708 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002709 if (Protocols.empty()) return;
2710
2711 for (unsigned i = 0; i != Protocols.size(); i++) {
2712 ObjCProtocolDecl *PDecl = Protocols[i];
2713 // Output struct protocol_methods holder of method selector and type.
2714 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2715 /* struct protocol_methods {
2716 SEL _cmd;
2717 char *method_types;
2718 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002719 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002720 Result += "\nstruct protocol_methods {\n";
2721 Result += "\tSEL _cmd;\n";
2722 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002723 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002724
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002725 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002726 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002727 // Do not synthesize the protocol more than once.
2728 if (ObjCSynthesizedProtocols.count(PDecl))
2729 continue;
2730
2731 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2732 unsigned NumMethods = PDecl->getNumInstanceMethods();
2733 /* struct _objc_protocol_method_list {
2734 int protocol_method_count;
2735 struct protocol_methods protocols[];
2736 }
2737 */
2738 Result += "\nstatic struct {\n";
2739 Result += "\tint protocol_method_count;\n";
2740 Result += "\tstruct protocol_methods protocols[";
2741 Result += utostr(NumMethods);
2742 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002743 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002744 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2745 "{\n\t" + utostr(NumMethods) + "\n";
2746
2747 // Output instance methods declared in this protocol.
2748 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2749 E = PDecl->instmeth_end(); I != E; ++I) {
2750 if (I == PDecl->instmeth_begin())
2751 Result += "\t ,{{(SEL)\"";
2752 else
2753 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002754 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002755 std::string MethodTypeString;
2756 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2757 Result += "\", \"";
2758 Result += MethodTypeString;
2759 Result += "\"}\n";
2760 }
2761 Result += "\t }\n};\n";
2762 }
2763
2764 // Output class methods declared in this protocol.
2765 int NumMethods = PDecl->getNumClassMethods();
2766 if (NumMethods > 0) {
2767 /* struct _objc_protocol_method_list {
2768 int protocol_method_count;
2769 struct protocol_methods protocols[];
2770 }
2771 */
2772 Result += "\nstatic struct {\n";
2773 Result += "\tint protocol_method_count;\n";
2774 Result += "\tstruct protocol_methods protocols[";
2775 Result += utostr(NumMethods);
2776 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002777 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002778 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2779 "{\n\t";
2780 Result += utostr(NumMethods);
2781 Result += "\n";
2782
2783 // Output instance methods declared in this protocol.
2784 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2785 E = PDecl->classmeth_end(); I != E; ++I) {
2786 if (I == PDecl->classmeth_begin())
2787 Result += "\t ,{{(SEL)\"";
2788 else
2789 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002790 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002791 std::string MethodTypeString;
2792 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2793 Result += "\", \"";
2794 Result += MethodTypeString;
2795 Result += "\"}\n";
2796 }
2797 Result += "\t }\n};\n";
2798 }
2799
2800 // Output:
2801 /* struct _objc_protocol {
2802 // Objective-C 1.0 extensions
2803 struct _objc_protocol_extension *isa;
2804 char *protocol_name;
2805 struct _objc_protocol **protocol_list;
2806 struct _objc_protocol_method_list *instance_methods;
2807 struct _objc_protocol_method_list *class_methods;
2808 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002809 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002810 static bool objc_protocol = false;
2811 if (!objc_protocol) {
2812 Result += "\nstruct _objc_protocol {\n";
2813 Result += "\tstruct _objc_protocol_extension *isa;\n";
2814 Result += "\tchar *protocol_name;\n";
2815 Result += "\tstruct _objc_protocol **protocol_list;\n";
2816 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2817 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2818 Result += "};\n";
2819
2820 objc_protocol = true;
2821 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002822
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002823 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002824 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002825 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2826 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002827 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002828 Result += "\", 0, ";
2829 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2830 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002831 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002832 Result += ", ";
2833 }
2834 else
2835 Result += "0, ";
2836 if (PDecl->getNumClassMethods() > 0) {
2837 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002838 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002839 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002840 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002841 else
2842 Result += "0\n";
2843 Result += "};\n";
2844
2845 // Mark this protocol as having been generated.
2846 if (!ObjCSynthesizedProtocols.insert(PDecl))
2847 assert(false && "protocol already synthesized");
2848 }
2849 // Output the top lovel protocol meta-data for the class.
2850 /* struct _objc_protocol_list {
2851 struct _objc_protocol_list *next;
2852 int protocol_count;
2853 struct _objc_protocol *class_protocols[];
2854 }
2855 */
2856 Result += "\nstatic struct {\n";
2857 Result += "\tstruct _objc_protocol_list *next;\n";
2858 Result += "\tint protocol_count;\n";
2859 Result += "\tstruct _objc_protocol *class_protocols[";
2860 Result += utostr(Protocols.size());
2861 Result += "];\n} _OBJC_";
2862 Result += prefix;
2863 Result += "_PROTOCOLS_";
2864 Result += ClassName;
2865 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2866 "{\n\t0, ";
2867 Result += utostr(Protocols.size());
2868 Result += "\n";
2869
2870 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002871 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002872 Result += " \n";
2873
2874 for (unsigned i = 1; i != Protocols.size(); i++) {
2875 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002876 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002877 Result += "\n";
2878 }
2879 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002880}
2881
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002882/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002883/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002884void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002885 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002886 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002887 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002888 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002889 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2890 CDecl = CDecl->getNextClassCategory())
2891 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2892 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002893
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002894 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002895 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002896 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002897
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002898 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002899 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002900 true, "CATEGORY_", FullCategoryName.c_str(),
2901 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002902
2903 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002904 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002905 false, "CATEGORY_", FullCategoryName.c_str(),
2906 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002907
2908 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002909 // Null CDecl is case of a category implementation with no category interface
2910 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002911 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002912 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002913
2914 /* struct _objc_category {
2915 char *category_name;
2916 char *class_name;
2917 struct _objc_method_list *instance_methods;
2918 struct _objc_method_list *class_methods;
2919 struct _objc_protocol_list *protocols;
2920 // Objective-C 1.0 extensions
2921 uint32_t size; // sizeof (struct _objc_category)
2922 struct _objc_property_list *instance_properties; // category's own
2923 // @property decl.
2924 };
2925 */
2926
2927 static bool objc_category = false;
2928 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002929 Result += "\nstruct _objc_category {\n";
2930 Result += "\tchar *category_name;\n";
2931 Result += "\tchar *class_name;\n";
2932 Result += "\tstruct _objc_method_list *instance_methods;\n";
2933 Result += "\tstruct _objc_method_list *class_methods;\n";
2934 Result += "\tstruct _objc_protocol_list *protocols;\n";
2935 Result += "\tunsigned int size;\n";
2936 Result += "\tstruct _objc_property_list *instance_properties;\n";
2937 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002938 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002939 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002940 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2941 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002942 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002943 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002944 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002945 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002946 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002947
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002948 if (IDecl->getNumInstanceMethods() > 0) {
2949 Result += "\t, (struct _objc_method_list *)"
2950 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2951 Result += FullCategoryName;
2952 Result += "\n";
2953 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002954 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002955 Result += "\t, 0\n";
2956 if (IDecl->getNumClassMethods() > 0) {
2957 Result += "\t, (struct _objc_method_list *)"
2958 "&_OBJC_CATEGORY_CLASS_METHODS_";
2959 Result += FullCategoryName;
2960 Result += "\n";
2961 }
2962 else
2963 Result += "\t, 0\n";
2964
Chris Lattner780f3292008-07-21 21:32:27 +00002965 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002966 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2967 Result += FullCategoryName;
2968 Result += "\n";
2969 }
2970 else
2971 Result += "\t, 0\n";
2972 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002973}
2974
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002975/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2976/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002977void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002978 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002979 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002980 if (ivar->isBitField()) {
2981 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2982 // place all bitfields at offset 0.
2983 Result += "0";
2984 } else {
2985 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002986 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002987 if (LangOpts.Microsoft)
2988 Result += "_IMPL";
2989 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002990 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002991 Result += ")";
2992 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002993}
2994
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002995//===----------------------------------------------------------------------===//
2996// Meta Data Emission
2997//===----------------------------------------------------------------------===//
2998
Steve Naroffb29b4272008-04-14 22:03:09 +00002999void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003000 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003001 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003002
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003003 // Explictly declared @interface's are already synthesized.
3004 if (CDecl->ImplicitInterfaceDecl()) {
3005 // FIXME: Implementation of a class with no @interface (legacy) doese not
3006 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003007 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003008 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003009
Chris Lattnerbe6df082007-12-12 07:56:42 +00003010 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003011 unsigned NumIvars = !IDecl->ivar_empty()
3012 ? IDecl->ivar_size()
3013 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003014 if (NumIvars > 0) {
3015 static bool objc_ivar = false;
3016 if (!objc_ivar) {
3017 /* struct _objc_ivar {
3018 char *ivar_name;
3019 char *ivar_type;
3020 int ivar_offset;
3021 };
3022 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003023 Result += "\nstruct _objc_ivar {\n";
3024 Result += "\tchar *ivar_name;\n";
3025 Result += "\tchar *ivar_type;\n";
3026 Result += "\tint ivar_offset;\n";
3027 Result += "};\n";
3028
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003029 objc_ivar = true;
3030 }
3031
Steve Naroff946a6932008-03-11 00:12:29 +00003032 /* struct {
3033 int ivar_count;
3034 struct _objc_ivar ivar_list[nIvars];
3035 };
3036 */
3037 Result += "\nstatic struct {\n";
3038 Result += "\tint ivar_count;\n";
3039 Result += "\tstruct _objc_ivar ivar_list[";
3040 Result += utostr(NumIvars);
3041 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003042 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003043 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003044 "{\n\t";
3045 Result += utostr(NumIvars);
3046 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003047
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003048 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003049 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003050 IVI = IDecl->ivar_begin();
3051 IVE = IDecl->ivar_end();
3052 } else {
3053 IVI = CDecl->ivar_begin();
3054 IVE = CDecl->ivar_end();
3055 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003056 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003057 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003058 Result += "\", \"";
3059 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003060 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003061 Result += StrEncoding;
3062 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003063 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003064 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003065 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003066 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003067 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003068 Result += "\", \"";
3069 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003070 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003071 Result += StrEncoding;
3072 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003073 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003074 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003075 }
3076
3077 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003078 }
3079
3080 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003081 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003082 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003083
3084 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003085 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003086 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003087
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003088 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003089 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003090 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003091
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003092
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003093 // Declaration of class/meta-class metadata
3094 /* struct _objc_class {
3095 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003096 const char *super_class_name;
3097 char *name;
3098 long version;
3099 long info;
3100 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003101 struct _objc_ivar_list *ivars;
3102 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003103 struct objc_cache *cache;
3104 struct objc_protocol_list *protocols;
3105 const char *ivar_layout;
3106 struct _objc_class_ext *ext;
3107 };
3108 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003109 static bool objc_class = false;
3110 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003111 Result += "\nstruct _objc_class {\n";
3112 Result += "\tstruct _objc_class *isa;\n";
3113 Result += "\tconst char *super_class_name;\n";
3114 Result += "\tchar *name;\n";
3115 Result += "\tlong version;\n";
3116 Result += "\tlong info;\n";
3117 Result += "\tlong instance_size;\n";
3118 Result += "\tstruct _objc_ivar_list *ivars;\n";
3119 Result += "\tstruct _objc_method_list *methods;\n";
3120 Result += "\tstruct objc_cache *cache;\n";
3121 Result += "\tstruct _objc_protocol_list *protocols;\n";
3122 Result += "\tconst char *ivar_layout;\n";
3123 Result += "\tstruct _objc_class_ext *ext;\n";
3124 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003125 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003126 }
3127
3128 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003129 ObjCInterfaceDecl *RootClass = 0;
3130 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003131 while (SuperClass) {
3132 RootClass = SuperClass;
3133 SuperClass = SuperClass->getSuperClass();
3134 }
3135 SuperClass = CDecl->getSuperClass();
3136
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003137 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003138 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003139 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003140 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003141 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003142 Result += "\"";
3143
3144 if (SuperClass) {
3145 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003146 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003147 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003148 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003149 Result += "\"";
3150 }
3151 else {
3152 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003153 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003154 Result += "\"";
3155 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003156 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003157 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003158 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003159 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003160 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003161 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003162 Result += "\n";
3163 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003164 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003165 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003166 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003167 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003168 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003169 Result += ",0,0\n";
3170 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003171 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003172 Result += "\t,0,0,0,0\n";
3173 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003174
3175 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003176 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003177 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003178 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003179 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003180 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003181 if (SuperClass) {
3182 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003183 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003184 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003185 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003186 Result += "\"";
3187 }
3188 else {
3189 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003190 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003191 Result += "\"";
3192 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003193 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003194 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003195 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003196 Result += ",0";
3197 else {
3198 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003199 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003200 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003201 if (LangOpts.Microsoft)
3202 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003203 Result += ")";
3204 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003205 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003206 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003207 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003208 Result += "\n\t";
3209 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003210 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003211 Result += ",0";
3212 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003213 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003214 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003215 Result += ", 0\n\t";
3216 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003217 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003218 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003219 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003220 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003221 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003222 Result += ", 0,0\n";
3223 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003224 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003225 Result += ",0,0,0\n";
3226 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003227}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003228
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003229/// RewriteImplementations - This routine rewrites all method implementations
3230/// and emits meta-data.
3231
Steve Narofface66252008-11-13 20:07:04 +00003232void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003233 int ClsDefCount = ClassImplementation.size();
3234 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003235
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003236 // Rewrite implemented methods
3237 for (int i = 0; i < ClsDefCount; i++)
3238 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003239
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003240 for (int i = 0; i < CatDefCount; i++)
3241 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003242}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003243
Steve Narofface66252008-11-13 20:07:04 +00003244void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3245 int ClsDefCount = ClassImplementation.size();
3246 int CatDefCount = CategoryImplementation.size();
3247
Steve Naroff5df5b762008-05-07 21:23:49 +00003248 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003249 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003250 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003251 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003252 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003253
3254 // For each implemented category, write out all its meta data.
3255 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003256 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003257
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003258 // Write objc_symtab metadata
3259 /*
3260 struct _objc_symtab
3261 {
3262 long sel_ref_cnt;
3263 SEL *refs;
3264 short cls_def_cnt;
3265 short cat_def_cnt;
3266 void *defs[cls_def_cnt + cat_def_cnt];
3267 };
3268 */
3269
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003270 Result += "\nstruct _objc_symtab {\n";
3271 Result += "\tlong sel_ref_cnt;\n";
3272 Result += "\tSEL *refs;\n";
3273 Result += "\tshort cls_def_cnt;\n";
3274 Result += "\tshort cat_def_cnt;\n";
3275 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3276 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003277
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003278 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003279 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003280 Result += "\t0, 0, " + utostr(ClsDefCount)
3281 + ", " + utostr(CatDefCount) + "\n";
3282 for (int i = 0; i < ClsDefCount; i++) {
3283 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003284 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003285 Result += "\n";
3286 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003287
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003288 for (int i = 0; i < CatDefCount; i++) {
3289 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003290 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003291 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003292 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003293 Result += "\n";
3294 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003295
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003296 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003297
3298 // Write objc_module metadata
3299
3300 /*
3301 struct _objc_module {
3302 long version;
3303 long size;
3304 const char *name;
3305 struct _objc_symtab *symtab;
3306 }
3307 */
3308
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003309 Result += "\nstruct _objc_module {\n";
3310 Result += "\tlong version;\n";
3311 Result += "\tlong size;\n";
3312 Result += "\tconst char *name;\n";
3313 Result += "\tstruct _objc_symtab *symtab;\n";
3314 Result += "};\n\n";
3315 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003316 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003317 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3318 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003319 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003320
3321 if (LangOpts.Microsoft) {
3322 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003323 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003324 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3325 Result += "&_OBJC_MODULES;\n";
3326 Result += "#pragma data_seg(pop)\n\n";
3327 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003328}
Chris Lattner311ff022007-10-16 22:36:42 +00003329
Steve Naroff54055232008-10-27 17:20:55 +00003330std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3331 const char *funcName,
3332 std::string Tag) {
3333 const FunctionType *AFT = CE->getFunctionType();
3334 QualType RT = AFT->getResultType();
3335 std::string StructRef = "struct " + Tag;
3336 std::string S = "static " + RT.getAsString() + " __" +
3337 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003338
Steve Naroff54055232008-10-27 17:20:55 +00003339 BlockDecl *BD = CE->getBlockDecl();
3340
3341 if (isa<FunctionTypeNoProto>(AFT)) {
3342 S += "()";
3343 } else if (BD->param_empty()) {
3344 S += "(" + StructRef + " *__cself)";
3345 } else {
3346 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3347 assert(FT && "SynthesizeBlockFunc: No function proto");
3348 S += '(';
3349 // first add the implicit argument.
3350 S += StructRef + " *__cself, ";
3351 std::string ParamStr;
3352 for (BlockDecl::param_iterator AI = BD->param_begin(),
3353 E = BD->param_end(); AI != E; ++AI) {
3354 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003355 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003356 (*AI)->getType().getAsStringInternal(ParamStr);
3357 S += ParamStr;
3358 }
3359 if (FT->isVariadic()) {
3360 if (!BD->param_empty()) S += ", ";
3361 S += "...";
3362 }
3363 S += ')';
3364 }
3365 S += " {\n";
3366
3367 // Create local declarations to avoid rewriting all closure decl ref exprs.
3368 // First, emit a declaration for all "by ref" decls.
3369 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3370 E = BlockByRefDecls.end(); I != E; ++I) {
3371 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003372 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003373 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003374 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003375 }
3376 // Next, emit a declaration for all "by copy" declarations.
3377 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3378 E = BlockByCopyDecls.end(); I != E; ++I) {
3379 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003380 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003381 // Handle nested closure invocation. For example:
3382 //
3383 // void (^myImportedClosure)(void);
3384 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3385 //
3386 // void (^anotherClosure)(void);
3387 // anotherClosure = ^(void) {
3388 // myImportedClosure(); // import and invoke the closure
3389 // };
3390 //
3391 if (isBlockPointerType((*I)->getType()))
3392 S += "struct __block_impl *";
3393 else
3394 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003395 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003396 }
3397 std::string RewrittenStr = RewrittenBlockExprs[CE];
3398 const char *cstr = RewrittenStr.c_str();
3399 while (*cstr++ != '{') ;
3400 S += cstr;
3401 S += "\n";
3402 return S;
3403}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003404
Steve Naroff54055232008-10-27 17:20:55 +00003405std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3406 const char *funcName,
3407 std::string Tag) {
3408 std::string StructRef = "struct " + Tag;
3409 std::string S = "static void __";
3410
3411 S += funcName;
3412 S += "_block_copy_" + utostr(i);
3413 S += "(" + StructRef;
3414 S += "*dst, " + StructRef;
3415 S += "*src) {";
3416 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3417 E = ImportedBlockDecls.end(); I != E; ++I) {
3418 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003419 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003420 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003421 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003422 S += ");}";
3423 }
3424 S += "\nstatic void __";
3425 S += funcName;
3426 S += "_block_dispose_" + utostr(i);
3427 S += "(" + StructRef;
3428 S += "*src) {";
3429 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3430 E = ImportedBlockDecls.end(); I != E; ++I) {
3431 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003432 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003433 S += ");";
3434 }
3435 S += "}\n";
3436 return S;
3437}
3438
3439std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3440 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003441 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003442 std::string Constructor = " " + Tag;
3443
3444 S += " {\n struct __block_impl impl;\n";
3445
3446 if (hasCopyDisposeHelpers)
3447 S += " void *copy;\n void *dispose;\n";
3448
3449 Constructor += "(void *fp";
3450
3451 if (hasCopyDisposeHelpers)
3452 Constructor += ", void *copyHelp, void *disposeHelp";
3453
3454 if (BlockDeclRefs.size()) {
3455 // Output all "by copy" declarations.
3456 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3457 E = BlockByCopyDecls.end(); I != E; ++I) {
3458 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003459 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003460 std::string ArgName = "_" + FieldName;
3461 // Handle nested closure invocation. For example:
3462 //
3463 // void (^myImportedBlock)(void);
3464 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3465 //
3466 // void (^anotherBlock)(void);
3467 // anotherBlock = ^(void) {
3468 // myImportedBlock(); // import and invoke the closure
3469 // };
3470 //
3471 if (isBlockPointerType((*I)->getType())) {
3472 S += "struct __block_impl *";
3473 Constructor += ", void *" + ArgName;
3474 } else {
3475 (*I)->getType().getAsStringInternal(FieldName);
3476 (*I)->getType().getAsStringInternal(ArgName);
3477 Constructor += ", " + ArgName;
3478 }
3479 S += FieldName + ";\n";
3480 }
3481 // Output all "by ref" declarations.
3482 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3483 E = BlockByRefDecls.end(); I != E; ++I) {
3484 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003485 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003486 std::string ArgName = "_" + FieldName;
3487 // Handle nested closure invocation. For example:
3488 //
3489 // void (^myImportedBlock)(void);
3490 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3491 //
3492 // void (^anotherBlock)(void);
3493 // anotherBlock = ^(void) {
3494 // myImportedBlock(); // import and invoke the closure
3495 // };
3496 //
3497 if (isBlockPointerType((*I)->getType())) {
3498 S += "struct __block_impl *";
3499 Constructor += ", void *" + ArgName;
3500 } else {
3501 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3502 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3503 Constructor += ", " + ArgName;
3504 }
3505 S += FieldName + "; // by ref\n";
3506 }
3507 // Finish writing the constructor.
3508 // FIXME: handle NSConcreteGlobalBlock.
3509 Constructor += ", int flags=0) {\n";
3510 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3511 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3512
3513 if (hasCopyDisposeHelpers)
3514 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3515
3516 // Initialize all "by copy" arguments.
3517 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3518 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003519 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003520 Constructor += " ";
3521 if (isBlockPointerType((*I)->getType()))
3522 Constructor += Name + " = (struct __block_impl *)_";
3523 else
3524 Constructor += Name + " = _";
3525 Constructor += Name + ";\n";
3526 }
3527 // Initialize all "by ref" arguments.
3528 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3529 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003530 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003531 Constructor += " ";
3532 if (isBlockPointerType((*I)->getType()))
3533 Constructor += Name + " = (struct __block_impl *)_";
3534 else
3535 Constructor += Name + " = _";
3536 Constructor += Name + ";\n";
3537 }
3538 } else {
3539 // Finish writing the constructor.
3540 // FIXME: handle NSConcreteGlobalBlock.
3541 Constructor += ", int flags=0) {\n";
3542 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3543 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3544 if (hasCopyDisposeHelpers)
3545 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3546 }
3547 Constructor += " ";
3548 Constructor += "}\n";
3549 S += Constructor;
3550 S += "};\n";
3551 return S;
3552}
3553
3554void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3555 const char *FunName) {
3556 // Insert closures that were part of the function.
3557 for (unsigned i = 0; i < Blocks.size(); i++) {
3558
3559 CollectBlockDeclRefInfo(Blocks[i]);
3560
3561 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3562
3563 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3564 ImportedBlockDecls.size() > 0);
3565
3566 InsertText(FunLocStart, CI.c_str(), CI.size());
3567
3568 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3569
3570 InsertText(FunLocStart, CF.c_str(), CF.size());
3571
3572 if (ImportedBlockDecls.size()) {
3573 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3574 InsertText(FunLocStart, HF.c_str(), HF.size());
3575 }
3576
3577 BlockDeclRefs.clear();
3578 BlockByRefDecls.clear();
3579 BlockByCopyDecls.clear();
3580 BlockCallExprs.clear();
3581 ImportedBlockDecls.clear();
3582 }
3583 Blocks.clear();
3584 RewrittenBlockExprs.clear();
3585}
3586
3587void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3588 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003589 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003590
3591 SynthesizeBlockLiterals(FunLocStart, FuncName);
3592}
3593
3594void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003595 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3596 //SourceLocation FunLocStart = MD->getLocStart();
3597 // FIXME: This hack works around a bug in Rewrite.InsertText().
3598 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003599 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003600 // Convert colons to underscores.
3601 std::string::size_type loc = 0;
3602 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3603 FuncName.replace(loc, 1, "_");
3604
3605 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3606}
3607
3608void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3609 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3610 CI != E; ++CI)
3611 if (*CI) {
3612 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3613 GetBlockDeclRefExprs(CBE->getBody());
3614 else
3615 GetBlockDeclRefExprs(*CI);
3616 }
3617 // Handle specific things.
3618 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3619 // FIXME: Handle enums.
3620 if (!isa<FunctionDecl>(CDRE->getDecl()))
3621 BlockDeclRefs.push_back(CDRE);
3622 return;
3623}
3624
3625void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3626 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3627 CI != E; ++CI)
3628 if (*CI) {
3629 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3630 GetBlockCallExprs(CBE->getBody());
3631 else
3632 GetBlockCallExprs(*CI);
3633 }
3634
3635 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3636 if (CE->getCallee()->getType()->isBlockPointerType()) {
3637 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3638 }
3639 }
3640 return;
3641}
3642
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003643Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003644 // Navigate to relevant type information.
3645 const char *closureName = 0;
3646 const BlockPointerType *CPT = 0;
3647
3648 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003649 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003650 CPT = DRE->getType()->getAsBlockPointerType();
3651 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003652 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003653 CPT = CDRE->getType()->getAsBlockPointerType();
3654 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003655 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003656 CPT = MExpr->getType()->getAsBlockPointerType();
3657 } else {
3658 assert(1 && "RewriteBlockClass: Bad type");
3659 }
3660 assert(CPT && "RewriteBlockClass: Bad type");
3661 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3662 assert(FT && "RewriteBlockClass: Bad type");
3663 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3664 // FTP will be null for closures that don't take arguments.
3665
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003666 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3667 SourceLocation(),
3668 &Context->Idents.get("__block_impl"));
3669 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003670
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003671 // Generate a funky cast.
3672 llvm::SmallVector<QualType, 8> ArgTypes;
3673
3674 // Push the block argument type.
3675 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003676 if (FTP) {
3677 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003678 E = FTP->arg_type_end(); I && (I != E); ++I) {
3679 QualType t = *I;
3680 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3681 if (isBlockPointerType(t)) {
3682 const BlockPointerType *BPT = t->getAsBlockPointerType();
3683 t = Context->getPointerType(BPT->getPointeeType());
3684 }
3685 ArgTypes.push_back(t);
3686 }
Steve Naroff54055232008-10-27 17:20:55 +00003687 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003688 // Now do the pointer to function cast.
3689 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3690 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3691
3692 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003693
Steve Naroffb2f9e512008-11-03 23:29:32 +00003694 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003695 // Don't forget the parens to enforce the proper binding.
3696 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3697 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003698
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003699 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3700 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3701 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3702
Steve Naroffb2f9e512008-11-03 23:29:32 +00003703 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003704 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3705
3706 llvm::SmallVector<Expr*, 8> BlkExprs;
3707 // Add the implicit argument.
3708 BlkExprs.push_back(BlkCast);
3709 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003710 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3711 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003712 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003713 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003714 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3715 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003716}
3717
3718void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003719 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3720 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003721}
3722
3723void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3724 // FIXME: Add more elaborate code generation required by the ABI.
3725 InsertText(BDRE->getLocStart(), "*", 1);
3726}
3727
Steve Naroffb2f9e512008-11-03 23:29:32 +00003728void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3729 SourceLocation LocStart = CE->getLParenLoc();
3730 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003731
3732 // Need to avoid trying to rewrite synthesized casts.
3733 if (LocStart.isInvalid())
3734 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003735 // Need to avoid trying to rewrite casts contained in macros.
3736 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3737 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003738
Steve Naroff54055232008-10-27 17:20:55 +00003739 const char *startBuf = SM->getCharacterData(LocStart);
3740 const char *endBuf = SM->getCharacterData(LocEnd);
3741
3742 // advance the location to startArgList.
3743 const char *argPtr = startBuf;
3744
3745 while (*argPtr++ && (argPtr < endBuf)) {
3746 switch (*argPtr) {
3747 case '^':
3748 // Replace the '^' with '*'.
3749 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3750 ReplaceText(LocStart, 1, "*", 1);
3751 break;
3752 }
3753 }
3754 return;
3755}
3756
3757void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3758 SourceLocation DeclLoc = FD->getLocation();
3759 unsigned parenCount = 0;
3760
3761 // We have 1 or more arguments that have closure pointers.
3762 const char *startBuf = SM->getCharacterData(DeclLoc);
3763 const char *startArgList = strchr(startBuf, '(');
3764
3765 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3766
3767 parenCount++;
3768 // advance the location to startArgList.
3769 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3770 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3771
3772 const char *argPtr = startArgList;
3773
3774 while (*argPtr++ && parenCount) {
3775 switch (*argPtr) {
3776 case '^':
3777 // Replace the '^' with '*'.
3778 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3779 ReplaceText(DeclLoc, 1, "*", 1);
3780 break;
3781 case '(':
3782 parenCount++;
3783 break;
3784 case ')':
3785 parenCount--;
3786 break;
3787 }
3788 }
3789 return;
3790}
3791
3792bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3793 const FunctionTypeProto *FTP;
3794 const PointerType *PT = QT->getAsPointerType();
3795 if (PT) {
3796 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3797 } else {
3798 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3799 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3800 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3801 }
3802 if (FTP) {
3803 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3804 E = FTP->arg_type_end(); I != E; ++I)
3805 if (isBlockPointerType(*I))
3806 return true;
3807 }
3808 return false;
3809}
3810
3811void RewriteObjC::GetExtentOfArgList(const char *Name,
3812 const char *&LParen, const char *&RParen) {
3813 const char *argPtr = strchr(Name, '(');
3814 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3815
3816 LParen = argPtr; // output the start.
3817 argPtr++; // skip past the left paren.
3818 unsigned parenCount = 1;
3819
3820 while (*argPtr && parenCount) {
3821 switch (*argPtr) {
3822 case '(': parenCount++; break;
3823 case ')': parenCount--; break;
3824 default: break;
3825 }
3826 if (parenCount) argPtr++;
3827 }
3828 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3829 RParen = argPtr; // output the end
3830}
3831
3832void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3833 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3834 RewriteBlockPointerFunctionArgs(FD);
3835 return;
3836 }
3837 // Handle Variables and Typedefs.
3838 SourceLocation DeclLoc = ND->getLocation();
3839 QualType DeclT;
3840 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3841 DeclT = VD->getType();
3842 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3843 DeclT = TDD->getUnderlyingType();
3844 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3845 DeclT = FD->getType();
3846 else
3847 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3848
3849 const char *startBuf = SM->getCharacterData(DeclLoc);
3850 const char *endBuf = startBuf;
3851 // scan backward (from the decl location) for the end of the previous decl.
3852 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3853 startBuf--;
3854
3855 // *startBuf != '^' if we are dealing with a pointer to function that
3856 // may take block argument types (which will be handled below).
3857 if (*startBuf == '^') {
3858 // Replace the '^' with '*', computing a negative offset.
3859 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3860 ReplaceText(DeclLoc, 1, "*", 1);
3861 }
3862 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3863 // Replace the '^' with '*' for arguments.
3864 DeclLoc = ND->getLocation();
3865 startBuf = SM->getCharacterData(DeclLoc);
3866 const char *argListBegin, *argListEnd;
3867 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3868 while (argListBegin < argListEnd) {
3869 if (*argListBegin == '^') {
3870 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3871 ReplaceText(CaretLoc, 1, "*", 1);
3872 }
3873 argListBegin++;
3874 }
3875 }
3876 return;
3877}
3878
3879void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3880 // Add initializers for any closure decl refs.
3881 GetBlockDeclRefExprs(Exp->getBody());
3882 if (BlockDeclRefs.size()) {
3883 // Unique all "by copy" declarations.
3884 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3885 if (!BlockDeclRefs[i]->isByRef())
3886 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3887 // Unique all "by ref" declarations.
3888 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3889 if (BlockDeclRefs[i]->isByRef()) {
3890 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3891 }
3892 // Find any imported blocks...they will need special attention.
3893 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3894 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003895 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003896 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3897 }
3898 }
3899}
3900
Steve Narofffa15fd92008-10-28 20:29:00 +00003901FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3902 IdentifierInfo *ID = &Context->Idents.get(name);
3903 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3904 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3905 ID, FType, FunctionDecl::Extern, false, 0);
3906}
3907
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003908Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003909 Blocks.push_back(Exp);
3910
3911 CollectBlockDeclRefInfo(Exp);
3912 std::string FuncName;
3913
3914 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003915 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003916 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00003917 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003918 // Convert colons to underscores.
3919 std::string::size_type loc = 0;
3920 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3921 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003922 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003923 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00003924
3925 std::string BlockNumber = utostr(Blocks.size()-1);
3926
3927 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3928 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3929
3930 // Get a pointer to the function type so we can cast appropriately.
3931 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3932
3933 FunctionDecl *FD;
3934 Expr *NewRep;
3935
3936 // Simulate a contructor call...
3937 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3938 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3939
3940 llvm::SmallVector<Expr*, 4> InitExprs;
3941
Steve Narofffdc03722008-10-29 21:23:59 +00003942 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003943 FD = SynthBlockInitFunctionDecl(Func.c_str());
3944 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3945 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003946 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003947 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003948
3949 if (ImportedBlockDecls.size()) {
3950 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003951 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3952 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3953 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003954 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003955 InitExprs.push_back(castExpr);
3956
Steve Narofffa15fd92008-10-28 20:29:00 +00003957 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003958 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3959 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3960 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003961 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003962 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003963 }
3964 // Add initializers for any closure decl refs.
3965 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00003966 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00003967 // Output all "by copy" declarations.
3968 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3969 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003970 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003971 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00003972 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003973 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003974 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003975 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003976 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3977 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003978 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003979 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003980 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003981 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003982 }
Steve Narofffdc03722008-10-29 21:23:59 +00003983 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003984 }
3985 // Output all "by ref" declarations.
3986 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3987 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003988 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003989 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3990 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3991 Context->getPointerType(Exp->getType()),
3992 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00003993 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003994 }
3995 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003996 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3997 FType, SourceLocation());
3998 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3999 Context->getPointerType(NewRep->getType()),
4000 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00004001 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004002 BlockDeclRefs.clear();
4003 BlockByRefDecls.clear();
4004 BlockByCopyDecls.clear();
4005 ImportedBlockDecls.clear();
4006 return NewRep;
4007}
4008
4009//===----------------------------------------------------------------------===//
4010// Function Body / Expression rewriting
4011//===----------------------------------------------------------------------===//
4012
Steve Naroffc77a6362008-12-04 16:24:46 +00004013// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4014// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4015// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4016// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4017// Since the rewriter isn't capable of rewriting rewritten code, it's important
4018// we get this right.
4019void RewriteObjC::CollectPropertySetters(Stmt *S) {
4020 // Perform a bottom up traversal of all children.
4021 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4022 CI != E; ++CI)
4023 if (*CI)
4024 CollectPropertySetters(*CI);
4025
4026 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4027 if (BinOp->isAssignmentOp()) {
4028 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4029 PropSetters[PRE] = BinOp;
4030 }
4031 }
4032}
4033
Steve Narofffa15fd92008-10-28 20:29:00 +00004034Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4035 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4036 isa<DoStmt>(S) || isa<ForStmt>(S))
4037 Stmts.push_back(S);
4038 else if (isa<ObjCForCollectionStmt>(S)) {
4039 Stmts.push_back(S);
4040 ObjCBcLabelNo.push_back(++BcLabelCount);
4041 }
4042
4043 SourceRange OrigStmtRange = S->getSourceRange();
4044
4045 // Perform a bottom up rewrite of all children.
4046 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4047 CI != E; ++CI)
4048 if (*CI) {
4049 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4050 if (newStmt)
4051 *CI = newStmt;
4052 }
4053
4054 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4055 // Rewrite the block body in place.
4056 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4057
4058 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004059 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4060 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004061
4062 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4063 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004064 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004065 return blockTranscribed;
4066 }
4067 // Handle specific things.
4068 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4069 return RewriteAtEncode(AtEncode);
4070
4071 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4072 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4073
Steve Naroffc77a6362008-12-04 16:24:46 +00004074 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4075 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4076 if (BinOp) {
4077 // Because the rewriter doesn't allow us to rewrite rewritten code,
4078 // we need to rewrite the right hand side prior to rewriting the setter.
4079 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff4c3580e2008-12-04 23:50:32 +00004080 //
4081 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4082 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4083 // to see the original expression). Consider this example:
4084 //
4085 // Foo *obj1, *obj2;
4086 //
4087 // obj1.i = [obj2 rrrr];
4088 //
4089 // 'BinOp' for the previous expression looks like:
4090 //
4091 // (BinaryOperator 0x231ccf0 'int' '='
4092 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4093 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4094 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4095 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4096 //
4097 // 'newStmt' represents the rewritten message expression. For example:
4098 //
4099 // (CallExpr 0x231d300 'id':'struct objc_object *'
4100 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4101 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4102 // (CStyleCastExpr 0x231d220 'void *'
4103 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4104 //
4105 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4106 // can be used as the setter argument. ReplaceStmt() will still 'see'
4107 // the original RHS (since we haven't altered BinOp).
4108 //
4109 // This implies the Rewrite* routines can no longer delete the original
4110 // node. As a result, we now leak the original AST nodes.
4111 //
Steve Naroffc77a6362008-12-04 16:24:46 +00004112 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt));
4113 } else {
4114 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004115 }
4116 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004117 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4118 return RewriteAtSelector(AtSelector);
4119
4120 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4121 return RewriteObjCStringLiteral(AtString);
4122
4123 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004124#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004125 // Before we rewrite it, put the original message expression in a comment.
4126 SourceLocation startLoc = MessExpr->getLocStart();
4127 SourceLocation endLoc = MessExpr->getLocEnd();
4128
4129 const char *startBuf = SM->getCharacterData(startLoc);
4130 const char *endBuf = SM->getCharacterData(endLoc);
4131
4132 std::string messString;
4133 messString += "// ";
4134 messString.append(startBuf, endBuf-startBuf+1);
4135 messString += "\n";
4136
4137 // FIXME: Missing definition of
4138 // InsertText(clang::SourceLocation, char const*, unsigned int).
4139 // InsertText(startLoc, messString.c_str(), messString.size());
4140 // Tried this, but it didn't work either...
4141 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004142#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004143 return RewriteMessageExpr(MessExpr);
4144 }
4145
4146 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4147 return RewriteObjCTryStmt(StmtTry);
4148
4149 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4150 return RewriteObjCSynchronizedStmt(StmtTry);
4151
4152 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4153 return RewriteObjCThrowStmt(StmtThrow);
4154
4155 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4156 return RewriteObjCProtocolExpr(ProtocolExp);
4157
4158 if (ObjCForCollectionStmt *StmtForCollection =
4159 dyn_cast<ObjCForCollectionStmt>(S))
4160 return RewriteObjCForCollectionStmt(StmtForCollection,
4161 OrigStmtRange.getEnd());
4162 if (BreakStmt *StmtBreakStmt =
4163 dyn_cast<BreakStmt>(S))
4164 return RewriteBreakStmt(StmtBreakStmt);
4165 if (ContinueStmt *StmtContinueStmt =
4166 dyn_cast<ContinueStmt>(S))
4167 return RewriteContinueStmt(StmtContinueStmt);
4168
4169 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4170 // and cast exprs.
4171 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4172 // FIXME: What we're doing here is modifying the type-specifier that
4173 // precedes the first Decl. In the future the DeclGroup should have
4174 // a separate type-specifier that we can rewrite.
4175 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4176
4177 // Blocks rewrite rules.
4178 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4179 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004180 ScopedDecl *SD = *DI;
4181 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4182 if (isBlockPointerType(ND->getType()))
4183 RewriteBlockPointerDecl(ND);
4184 else if (ND->getType()->isFunctionPointerType())
4185 CheckFunctionPointerDecl(ND->getType(), ND);
4186 }
4187 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4188 if (isBlockPointerType(TD->getUnderlyingType()))
4189 RewriteBlockPointerDecl(TD);
4190 else if (TD->getUnderlyingType()->isFunctionPointerType())
4191 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4192 }
4193 }
4194 }
4195
4196 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4197 RewriteObjCQualifiedInterfaceTypes(CE);
4198
4199 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4200 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4201 assert(!Stmts.empty() && "Statement stack is empty");
4202 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4203 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4204 && "Statement stack mismatch");
4205 Stmts.pop_back();
4206 }
4207 // Handle blocks rewriting.
4208 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4209 if (BDRE->isByRef())
4210 RewriteBlockDeclRefExpr(BDRE);
4211 }
4212 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004213 if (CE->getCallee()->getType()->isBlockPointerType()) {
4214 Stmt *BlockCall = SynthesizeBlockCall(CE);
4215 ReplaceStmt(S, BlockCall);
4216 return BlockCall;
4217 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004218 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004219 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004220 RewriteCastExpr(CE);
4221 }
4222#if 0
4223 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4224 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4225 // Get the new text.
4226 std::string SStr;
4227 llvm::raw_string_ostream Buf(SStr);
4228 Replacement->printPretty(Buf);
4229 const std::string &Str = Buf.str();
4230
4231 printf("CAST = %s\n", &Str[0]);
4232 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4233 delete S;
4234 return Replacement;
4235 }
4236#endif
4237 // Return this stmt unmodified.
4238 return S;
4239}
4240
4241/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4242/// main file of the input.
4243void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4245 // Since function prototypes don't have ParmDecl's, we check the function
4246 // prototype. This enables us to rewrite function declarations and
4247 // definitions using the same code.
4248 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4249
4250 if (Stmt *Body = FD->getBody()) {
4251 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004252 CollectPropertySetters(Body);
Steve Narofffa15fd92008-10-28 20:29:00 +00004253 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroffc77a6362008-12-04 16:24:46 +00004254
Steve Narofffa15fd92008-10-28 20:29:00 +00004255 // This synthesizes and inserts the block "impl" struct, invoke function,
4256 // and any copy/dispose helper functions.
4257 InsertBlockLiteralsWithinFunction(FD);
4258 CurFunctionDef = 0;
4259 }
4260 return;
4261 }
4262 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4263 if (Stmt *Body = MD->getBody()) {
4264 //Body->dump();
4265 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004266 CollectPropertySetters(Body);
Steve Narofffa15fd92008-10-28 20:29:00 +00004267 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4268 InsertBlockLiteralsWithinMethod(MD);
4269 CurMethodDef = 0;
4270 }
4271 }
4272 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4273 ClassImplementation.push_back(CI);
4274 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4275 CategoryImplementation.push_back(CI);
4276 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4277 RewriteForwardClassDecl(CD);
4278 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4279 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004280 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004281 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004282 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004283 CheckFunctionPointerDecl(VD->getType(), VD);
4284 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004285 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004286 RewriteCastExpr(CE);
4287 }
4288 }
4289 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004290 if (VD->getInit()) {
4291 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004292 CollectPropertySetters(VD->getInit());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004293 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004294 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004295 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004296 GlobalVarDecl = 0;
4297
4298 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004299 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004300 RewriteCastExpr(CE);
4301 }
4302 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004303 return;
4304 }
4305 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4306 if (isBlockPointerType(TD->getUnderlyingType()))
4307 RewriteBlockPointerDecl(TD);
4308 else if (TD->getUnderlyingType()->isFunctionPointerType())
4309 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4310 return;
4311 }
4312 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4313 if (RD->isDefinition()) {
4314 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4315 e = RD->field_end(); i != e; ++i) {
4316 FieldDecl *FD = *i;
4317 if (isBlockPointerType(FD->getType()))
4318 RewriteBlockPointerDecl(FD);
4319 }
4320 }
4321 return;
4322 }
4323 // Nothing yet.
4324}
4325
4326void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4327 // Get the top-level buffer that this corresponds to.
4328
4329 // Rewrite tabs if we care.
4330 //RewriteTabs();
4331
4332 if (Diags.hasErrorOccurred())
4333 return;
4334
4335 // Create the output file.
4336
4337 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4338 llvm::raw_ostream *OutFile;
4339 if (OutFileName == "-") {
4340 OutFile = &llvm::outs();
4341 } else if (!OutFileName.empty()) {
4342 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004343 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004344 OwnedStream.reset(OutFile);
4345 } else if (InFileName == "-") {
4346 OutFile = &llvm::outs();
4347 } else {
4348 llvm::sys::Path Path(InFileName);
4349 Path.eraseSuffix();
4350 Path.appendSuffix("cpp");
4351 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004352 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004353 OwnedStream.reset(OutFile);
4354 }
4355
4356 RewriteInclude();
4357
4358 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4359 Preamble.c_str(), Preamble.size(), false);
4360
Steve Naroff0aab7962008-11-14 14:10:01 +00004361 if (ClassImplementation.size() || CategoryImplementation.size())
4362 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004363
4364 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4365 // we are done.
4366 if (const RewriteBuffer *RewriteBuf =
4367 Rewrite.getRewriteBufferFor(MainFileID)) {
4368 //printf("Changed:\n");
4369 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4370 } else {
4371 fprintf(stderr, "No changes\n");
4372 }
Steve Narofface66252008-11-13 20:07:04 +00004373
Steve Naroff0aab7962008-11-14 14:10:01 +00004374 if (ClassImplementation.size() || CategoryImplementation.size()) {
4375 // Rewrite Objective-c meta data*
4376 std::string ResultStr;
4377 SynthesizeMetaDataIntoBuffer(ResultStr);
4378 // Emit metadata.
4379 *OutFile << ResultStr;
4380 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004381 OutFile->flush();
4382}
4383