blob: 37d416ac97cab2da67f351770dfb1c5f34b3e7b7 [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
107 FunctionDecl *CurFunctionDef;
108
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000109 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000110 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000111 virtual void Initialize(ASTContext &context);
112
113 virtual void InitializeTU(TranslationUnit &TU) {
114 TU.SetOwnsDecls(false);
115 Initialize(TU.getContext());
116 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000117
Chris Lattner8a12c272007-10-11 18:38:32 +0000118
Chris Lattnerf04da132007-10-24 17:06:59 +0000119 // Top Level Driver code.
120 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000121 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000122 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000123 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000124
125 ~RewriteObjC() {}
126
127 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000128
129 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000130 // If replacement succeeded or warning disabled return with no warning.
131 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000132 return;
133
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000134 SourceRange Range = Old->getSourceRange();
135 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
136 0, 0, &Range, 1);
137 }
138
Steve Naroffba92b2e2008-03-27 22:29:16 +0000139 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
140 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000141 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000142 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000143 SilenceRewriteMacroWarning)
144 return;
145
146 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
147 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000148
Chris Lattneraadaf782008-01-31 19:51:04 +0000149 void RemoveText(SourceLocation Loc, unsigned StrLen) {
150 // If removal succeeded or warning disabled return with no warning.
151 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
152 return;
153
154 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
155 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000156
Chris Lattneraadaf782008-01-31 19:51:04 +0000157 void ReplaceText(SourceLocation Start, unsigned OrigLength,
158 const char *NewStr, unsigned NewLength) {
159 // If removal succeeded or warning disabled return with no warning.
160 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
161 SilenceRewriteMacroWarning)
162 return;
163
164 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
165 }
166
Chris Lattnerf04da132007-10-24 17:06:59 +0000167 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000168 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000169 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000170 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000171 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
172 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000173 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000174 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
175 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
176 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
177 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
178 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000179 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000180 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000181 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000182 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000183 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000184 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000185 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000186 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000187 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000188
Chris Lattnerf04da132007-10-24 17:06:59 +0000189 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000190 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000191 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000192 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000193 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000194 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000195 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000196 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000197 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000198 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000199 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
200 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
201 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000202 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
203 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000204 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
205 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000206 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000207 Stmt *RewriteBreakStmt(BreakStmt *S);
208 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000209 void SynthCountByEnumWithState(std::string &buf);
210
Steve Naroff09b266e2007-10-30 23:14:51 +0000211 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000212 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000213 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000214 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000215 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000216 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000217 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000218 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000219 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000220 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000221
Chris Lattnerf04da132007-10-24 17:06:59 +0000222 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000223 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000224 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000225
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000227 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000228
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000229 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
230 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000231 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000232 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000233 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000234 const char *ClassName,
235 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000236
Chris Lattner780f3292008-07-21 21:32:27 +0000237 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
238 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000239 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000240 const char *ClassName,
241 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000242 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000243 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000244 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
245 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000246 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000247 void RewriteImplementations(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000248
249 // Block rewriting.
250 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
251 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
252
253 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
254 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
255
256 // Block specific rewrite rules.
257 std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0);
258
259 void RewriteBlockCall(CallExpr *Exp);
260 void RewriteBlockPointerDecl(NamedDecl *VD);
261 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
262 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
263
264 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
265 const char *funcName, std::string Tag);
266 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
267 const char *funcName, std::string Tag);
268 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
269 bool hasCopyDisposeHelpers);
270 std::string SynthesizeBlockCall(CallExpr *Exp);
271 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
272 const char *FunName);
273
274 void CollectBlockDeclRefInfo(BlockExpr *Exp);
275 void GetBlockCallExprs(Stmt *S);
276 void GetBlockDeclRefExprs(Stmt *S);
277
278 // We avoid calling Type::isBlockPointerType(), since it operates on the
279 // canonical type. We only care if the top-level type is a closure pointer.
280 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
281
282 // FIXME: This predicate seems like it would be useful to add to ASTContext.
283 bool isObjCType(QualType T) {
284 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
285 return false;
286
287 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
288
289 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
290 OCT == Context->getCanonicalType(Context->getObjCClassType()))
291 return true;
292
293 if (const PointerType *PT = OCT->getAsPointerType()) {
294 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
295 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
296 return true;
297 }
298 return false;
299 }
300 bool PointerTypeTakesAnyBlockArguments(QualType QT);
301 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
302 void RewriteCastExpr(CastExpr *CE);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000303 };
304}
305
Steve Naroff54055232008-10-27 17:20:55 +0000306void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
307 NamedDecl *D) {
308 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
309 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
310 E = fproto->arg_type_end(); I && (I != E); ++I)
311 if (isBlockPointerType(*I)) {
312 // All the args are checked/rewritten. Don't call twice!
313 RewriteBlockPointerDecl(D);
314 break;
315 }
316 }
317}
318
319void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
320 const PointerType *PT = funcType->getAsPointerType();
321 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
322 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
323}
324
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000325static bool IsHeaderFile(const std::string &Filename) {
326 std::string::size_type DotPos = Filename.rfind('.');
327
328 if (DotPos == std::string::npos) {
329 // no file extension
330 return false;
331 }
332
333 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
334 // C header: .h
335 // C++ header: .hh or .H;
336 return Ext == "h" || Ext == "hh" || Ext == "H";
337}
338
Steve Naroffb29b4272008-04-14 22:03:09 +0000339RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000340 Diagnostic &D, const LangOptions &LOpts)
341 : Diags(D), LangOpts(LOpts) {
342 IsHeader = IsHeaderFile(inFile);
343 InFileName = inFile;
344 OutFileName = outFile;
345 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
346 "rewriting sub-expression within a macro (may not be correct)");
347}
348
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000349ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000350 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000351 Diagnostic &Diags,
352 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000353 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000354}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000355
Steve Naroffb29b4272008-04-14 22:03:09 +0000356void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000357 Context = &context;
358 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000359 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000360 MsgSendFunctionDecl = 0;
361 MsgSendSuperFunctionDecl = 0;
362 MsgSendStretFunctionDecl = 0;
363 MsgSendSuperStretFunctionDecl = 0;
364 MsgSendFpretFunctionDecl = 0;
365 GetClassFunctionDecl = 0;
366 GetMetaClassFunctionDecl = 0;
367 SelGetUidFunctionDecl = 0;
368 CFStringFunctionDecl = 0;
369 GetProtocolFunctionDecl = 0;
370 ConstantStringClassReference = 0;
371 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000372 CurMethodDef = 0;
373 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000374 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000375 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000376 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000377 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000378 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000379
380 // Get the ID and start/end of the main file.
381 MainFileID = SM->getMainFileID();
382 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
383 MainFileStart = MainBuf->getBufferStart();
384 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000385
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000386 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000387
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000388 // declaring objc_selector outside the parameter list removes a silly
389 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000390 if (IsHeader)
391 Preamble = "#pragma once\n";
392 Preamble += "struct objc_selector; struct objc_class;\n";
393 Preamble += "#ifndef OBJC_SUPER\n";
394 Preamble += "struct objc_super { struct objc_object *object; ";
395 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000396 if (LangOpts.Microsoft) {
397 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000398 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
399 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000400 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000401 Preamble += "};\n";
402 Preamble += "#define OBJC_SUPER\n";
403 Preamble += "#endif\n";
404 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
405 Preamble += "typedef struct objc_object Protocol;\n";
406 Preamble += "#define _REWRITER_typedef_Protocol\n";
407 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000408 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000409 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
410 else
411 Preamble += "#define __OBJC_RW_EXTERN extern\n";
412 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000413 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000414 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000415 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000416 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000417 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000418 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000419 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000420 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000421 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000422 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000423 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000424 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000425 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000426 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
427 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
428 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
429 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
430 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000431 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000432 // @synchronized hooks.
433 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
434 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000435 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000436 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
437 Preamble += "struct __objcFastEnumerationState {\n\t";
438 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000439 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000440 Preamble += "unsigned long *mutationsPtr;\n\t";
441 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000442 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000443 Preamble += "#define __FASTENUMERATIONSTATE\n";
444 Preamble += "#endif\n";
445 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
446 Preamble += "struct __NSConstantStringImpl {\n";
447 Preamble += " int *isa;\n";
448 Preamble += " int flags;\n";
449 Preamble += " char *str;\n";
450 Preamble += " long length;\n";
451 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000452 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
453 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
454 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000455 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000456 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000457 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
458 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000459 // Blocks preamble.
460 Preamble += "#ifndef BLOCK_IMPL\n";
461 Preamble += "#define BLOCK_IMPL\n";
462 Preamble += "struct __block_impl {\n";
463 Preamble += " void *isa;\n";
464 Preamble += " int Flags;\n";
465 Preamble += " int Size;\n";
466 Preamble += " void *FuncPtr;\n";
467 Preamble += "};\n";
468 Preamble += "enum {\n";
469 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
470 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
471 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000472 Preamble += "// Runtime copy/destroy helper functions\n";
473 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
474 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
475 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
476 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
477 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
478 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
479 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000480 if (LangOpts.Microsoft) {
481 Preamble += "#undef __OBJC_RW_EXTERN\n";
482 Preamble += "#define __attribute__(X)\n";
483 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000484}
485
486
Chris Lattnerf04da132007-10-24 17:06:59 +0000487//===----------------------------------------------------------------------===//
488// Top Level Driver Code
489//===----------------------------------------------------------------------===//
490
Steve Naroffb29b4272008-04-14 22:03:09 +0000491void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000492 // Two cases: either the decl could be in the main file, or it could be in a
493 // #included file. If the former, rewrite it now. If the later, check to see
494 // if we rewrote the #include/#import.
495 SourceLocation Loc = D->getLocation();
496 Loc = SM->getLogicalLoc(Loc);
497
498 // If this is for a builtin, ignore it.
499 if (Loc.isInvalid()) return;
500
Steve Naroffebf2b562007-10-23 23:50:29 +0000501 // Look for built-in declarations that we need to refer during the rewrite.
502 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000503 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000504 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000505 // declared in <Foundation/NSString.h>
506 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
507 ConstantStringClassReference = FVD;
508 return;
509 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000510 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000511 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000512 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000513 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000514 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000515 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000516 } else if (ObjCForwardProtocolDecl *FP =
517 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000518 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000519 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000520 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000521 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000522 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000523}
524
Chris Lattnerf04da132007-10-24 17:06:59 +0000525/// HandleDeclInMainFile - This is called for each top-level decl defined in the
526/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000527void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Steve Naroff54055232008-10-27 17:20:55 +0000528 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
529 // Since function prototypes don't have ParmDecl's, we check the function
530 // prototype. This enables us to rewrite function declarations and
531 // definitions using the same code.
532 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
533
534 if (Stmt *Body = FD->getBody()) {
535 CurFunctionDef = FD;
Steve Narofff3473a72007-11-09 15:20:18 +0000536 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff54055232008-10-27 17:20:55 +0000537 // This synthesizes and inserts the block "impl" struct, invoke function,
538 // and any copy/dispose helper functions.
539 InsertBlockLiteralsWithinFunction(FD);
540 CurFunctionDef = 0;
541 }
542 return;
543 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000544 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000545 if (Stmt *Body = MD->getBody()) {
546 //Body->dump();
Steve Naroff54055232008-10-27 17:20:55 +0000547 CurMethodDef = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000548 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff54055232008-10-27 17:20:55 +0000549 InsertBlockLiteralsWithinMethod(MD);
550 CurMethodDef = 0;
Steve Naroff874e2322007-11-15 10:28:18 +0000551 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000552 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000553 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000554 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000555 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000556 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000557 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000558 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000559 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000560 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000561 if (VD->getInit())
562 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
563 }
Steve Naroff54055232008-10-27 17:20:55 +0000564 // Rewrite rules for blocks.
565 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
566 if (isBlockPointerType(VD->getType())) {
567 RewriteBlockPointerDecl(VD);
568 if (VD->getInit()) {
569 if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) {
570 RewriteFunctionBodyOrGlobalInitializer(CBE->getBody());
571
572 // We've just rewritten the block body in place.
573 // Now we snarf the rewritten text and stash it away for later use.
574 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
575 RewrittenBlockExprs[CBE] = S;
576 std::string Init = SynthesizeBlockInitExpr(CBE, VD);
577 // Do the rewrite, using S.size() which contains the rewritten size.
578 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
579 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
580 } else if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
581 RewriteCastExpr(CE);
582 }
583 }
584 } else if (VD->getType()->isFunctionPointerType()) {
585 CheckFunctionPointerDecl(VD->getType(), VD);
586 if (VD->getInit()) {
587 if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
588 RewriteCastExpr(CE);
589 }
590 }
591 }
592 return;
593 }
594 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
595 if (isBlockPointerType(TD->getUnderlyingType()))
596 RewriteBlockPointerDecl(TD);
597 else if (TD->getUnderlyingType()->isFunctionPointerType())
598 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
599 return;
600 }
601 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
602 if (RD->isDefinition()) {
603 for (RecordDecl::field_const_iterator i = RD->field_begin(),
604 e = RD->field_end(); i != e; ++i) {
605 FieldDecl *FD = *i;
606 if (isBlockPointerType(FD->getType()))
607 RewriteBlockPointerDecl(FD);
608 }
609 }
610 return;
611 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000612 // Nothing yet.
613}
614
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000615void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000616 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000617
618 // Rewrite tabs if we care.
619 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000620
Steve Naroffa7b402d2008-03-28 22:26:09 +0000621 if (Diags.hasErrorOccurred())
622 return;
623
624 // Create the output file.
625
Ted Kremeneka95d3752008-09-13 05:16:45 +0000626 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
627 llvm::raw_ostream *OutFile;
Steve Naroffa7b402d2008-03-28 22:26:09 +0000628 if (OutFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000629 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000630 } else if (!OutFileName.empty()) {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000631 std::string Err;
632 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), Err);
633 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000634 } else if (InFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000635 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000636 } else {
637 llvm::sys::Path Path(InFileName);
638 Path.eraseSuffix();
639 Path.appendSuffix("cpp");
Ted Kremeneka95d3752008-09-13 05:16:45 +0000640 std::string Err;
641 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), Err);
642 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000643 }
644
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000645 RewriteInclude();
646
Steve Naroffba92b2e2008-03-27 22:29:16 +0000647 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
648 Preamble.c_str(), Preamble.size(), false);
649
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000650 // Rewrite Objective-c meta data*
651 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000652 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000653
Chris Lattnerf04da132007-10-24 17:06:59 +0000654 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
655 // we are done.
656 if (const RewriteBuffer *RewriteBuf =
657 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000658 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000659 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000660 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000661 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000662 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000663 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000664 *OutFile << ResultStr;
Ted Kremeneka95d3752008-09-13 05:16:45 +0000665 OutFile->flush();
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000666}
667
Chris Lattnerf04da132007-10-24 17:06:59 +0000668//===----------------------------------------------------------------------===//
669// Syntactic (non-AST) Rewriting Code
670//===----------------------------------------------------------------------===//
671
Steve Naroffb29b4272008-04-14 22:03:09 +0000672void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000673 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
674 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
675 const char *MainBufStart = MainBuf.first;
676 const char *MainBufEnd = MainBuf.second;
677 size_t ImportLen = strlen("import");
678 size_t IncludeLen = strlen("include");
679
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000680 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000681 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
682 if (*BufPtr == '#') {
683 if (++BufPtr == MainBufEnd)
684 return;
685 while (*BufPtr == ' ' || *BufPtr == '\t')
686 if (++BufPtr == MainBufEnd)
687 return;
688 if (!strncmp(BufPtr, "import", ImportLen)) {
689 // replace import with include
690 SourceLocation ImportLoc =
691 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000692 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000693 BufPtr += ImportLen;
694 }
695 }
696 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000697}
698
Steve Naroffb29b4272008-04-14 22:03:09 +0000699void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000700 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
701 const char *MainBufStart = MainBuf.first;
702 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000703
Chris Lattnerf04da132007-10-24 17:06:59 +0000704 // Loop over the whole file, looking for tabs.
705 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
706 if (*BufPtr != '\t')
707 continue;
708
709 // Okay, we found a tab. This tab will turn into at least one character,
710 // but it depends on which 'virtual column' it is in. Compute that now.
711 unsigned VCol = 0;
712 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
713 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
714 ++VCol;
715
716 // Okay, now that we know the virtual column, we know how many spaces to
717 // insert. We assume 8-character tab-stops.
718 unsigned Spaces = 8-(VCol & 7);
719
720 // Get the location of the tab.
721 SourceLocation TabLoc =
722 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
723
724 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000725 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000726 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000727}
728
729
Steve Naroffb29b4272008-04-14 22:03:09 +0000730void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000731 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000732 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000733
734 // Get the start location and compute the semi location.
735 SourceLocation startLoc = ClassDecl->getLocation();
736 const char *startBuf = SM->getCharacterData(startLoc);
737 const char *semiPtr = strchr(startBuf, ';');
738
739 // Translate to typedef's that forward reference structs with the same name
740 // as the class. As a convenience, we include the original declaration
741 // as a comment.
742 std::string typedefString;
743 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000744 typedefString.append(startBuf, semiPtr-startBuf+1);
745 typedefString += "\n";
746 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000747 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000748 typedefString += "#ifndef _REWRITER_typedef_";
749 typedefString += ForwardDecl->getName();
750 typedefString += "\n";
751 typedefString += "#define _REWRITER_typedef_";
752 typedefString += ForwardDecl->getName();
753 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000754 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000755 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000756 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000757 }
758
759 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000760 ReplaceText(startLoc, semiPtr-startBuf+1,
761 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000762}
763
Steve Naroffb29b4272008-04-14 22:03:09 +0000764void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000765 SourceLocation LocStart = Method->getLocStart();
766 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000767
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000768 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000769 InsertText(LocStart, "#if 0\n", 6);
770 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000771 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000772 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000773 }
774}
775
Steve Naroffb29b4272008-04-14 22:03:09 +0000776void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000777{
Chris Lattner55d13b42008-03-16 21:23:50 +0000778 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000779 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000780 SourceLocation Loc = Property->getLocation();
781
Chris Lattneraadaf782008-01-31 19:51:04 +0000782 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000783
784 // FIXME: handle properties that are declared across multiple lines.
785 }
786}
787
Steve Naroffb29b4272008-04-14 22:03:09 +0000788void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000789 SourceLocation LocStart = CatDecl->getLocStart();
790
791 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000792 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000793
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000794 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000795 E = CatDecl->instmeth_end(); I != E; ++I)
796 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000797 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000798 E = CatDecl->classmeth_end(); I != E; ++I)
799 RewriteMethodDeclaration(*I);
800
Steve Naroff423cb562007-10-30 13:30:57 +0000801 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000802 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000803}
804
Steve Naroffb29b4272008-04-14 22:03:09 +0000805void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000806 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000807
Steve Naroff752d6ef2007-10-30 16:42:30 +0000808 SourceLocation LocStart = PDecl->getLocStart();
809
810 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000811 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000812
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000813 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000814 E = PDecl->instmeth_end(); I != E; ++I)
815 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000816 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000817 E = PDecl->classmeth_end(); I != E; ++I)
818 RewriteMethodDeclaration(*I);
819
Steve Naroff752d6ef2007-10-30 16:42:30 +0000820 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000821 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000822 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000823
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000824 // Must comment out @optional/@required
825 const char *startBuf = SM->getCharacterData(LocStart);
826 const char *endBuf = SM->getCharacterData(LocEnd);
827 for (const char *p = startBuf; p < endBuf; p++) {
828 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
829 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000830 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000831 ReplaceText(OptionalLoc, strlen("@optional"),
832 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000833
834 }
835 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
836 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000837 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000838 ReplaceText(OptionalLoc, strlen("@required"),
839 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000840
841 }
842 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000843}
844
Steve Naroffb29b4272008-04-14 22:03:09 +0000845void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000846 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000847 if (LocStart.isInvalid())
848 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000849 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000850 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000851}
852
Steve Naroffb29b4272008-04-14 22:03:09 +0000853void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000854 std::string &ResultStr) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000855 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000856 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000857 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000858 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000859 else if (OMD->getResultType()->isFunctionPointerType()) {
860 // needs special handling, since pointer-to-functions have special
861 // syntax (where a decaration models use).
862 QualType retType = OMD->getResultType();
863 if (const PointerType* PT = retType->getAsPointerType()) {
864 QualType PointeeTy = PT->getPointeeType();
865 if ((FPRetType = PointeeTy->getAsFunctionType())) {
866 ResultStr += FPRetType->getResultType().getAsString();
867 ResultStr += "(*";
868 }
869 }
870 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000871 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000872 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000873
874 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000875 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000876
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000877 if (OMD->isInstance())
878 NameStr += "_I_";
879 else
880 NameStr += "_C_";
881
882 NameStr += OMD->getClassInterface()->getName();
883 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000884
885 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000886 if (ObjCCategoryImplDecl *CID =
887 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000888 NameStr += CID->getName();
889 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000890 }
Steve Naroff563b8282008-04-04 22:23:44 +0000891 // Append selector names, replacing ':' with '_'
892 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000893 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000894 else {
895 std::string selString = OMD->getSelector().getName();
896 int len = selString.size();
897 for (int i = 0; i < len; i++)
898 if (selString[i] == ':')
899 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000900 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000901 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000902 // Remember this name for metadata emission
903 MethodInternalNames[OMD] = NameStr;
904 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000905
906 // Rewrite arguments
907 ResultStr += "(";
908
909 // invisible arguments
910 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000911 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000912 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000913 if (!LangOpts.Microsoft) {
914 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
915 ResultStr += "struct ";
916 }
917 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000918 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000919 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000920 }
921 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000922 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000923
924 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000925 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000926 ResultStr += " _cmd";
927
928 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000929 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000930 ParmVarDecl *PDecl = OMD->getParamDecl(i);
931 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000932 if (PDecl->getType()->isObjCQualifiedIdType()) {
933 ResultStr += "id ";
934 ResultStr += PDecl->getName();
935 } else {
936 std::string Name = PDecl->getName();
937 PDecl->getType().getAsStringInternal(Name);
938 ResultStr += Name;
939 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000940 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000941 if (OMD->isVariadic())
942 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000943 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000944
Steve Naroff76e429d2008-07-16 14:40:40 +0000945 if (FPRetType) {
946 ResultStr += ")"; // close the precedence "scope" for "*".
947
948 // Now, emit the argument types (if any).
949 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
950 ResultStr += "(";
951 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
952 if (i) ResultStr += ", ";
953 std::string ParamStr = FT->getArgType(i).getAsString();
954 ResultStr += ParamStr;
955 }
956 if (FT->isVariadic()) {
957 if (FT->getNumArgs()) ResultStr += ", ";
958 ResultStr += "...";
959 }
960 ResultStr += ")";
961 } else {
962 ResultStr += "()";
963 }
964 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000965}
Steve Naroffb29b4272008-04-14 22:03:09 +0000966void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000967 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
968 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000969
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000970 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000971 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000972 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000973 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000975 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000976 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
977 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000978 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000979 ObjCMethodDecl *OMD = *I;
980 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000981 SourceLocation LocStart = OMD->getLocStart();
982 SourceLocation LocEnd = OMD->getBody()->getLocStart();
983
984 const char *startBuf = SM->getCharacterData(LocStart);
985 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000986 ReplaceText(LocStart, endBuf-startBuf,
987 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000988 }
989
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000990 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000991 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
992 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000993 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000994 ObjCMethodDecl *OMD = *I;
995 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000996 SourceLocation LocStart = OMD->getLocStart();
997 SourceLocation LocEnd = OMD->getBody()->getLocStart();
998
999 const char *startBuf = SM->getCharacterData(LocStart);
1000 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001001 ReplaceText(LocStart, endBuf-startBuf,
1002 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001003 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001004 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001005 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001006 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001007 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001008}
1009
Steve Naroffb29b4272008-04-14 22:03:09 +00001010void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001011 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001012 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001013 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001014 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +00001015 ResultStr += ClassDecl->getName();
1016 ResultStr += "\n";
1017 ResultStr += "#define _REWRITER_typedef_";
1018 ResultStr += ClassDecl->getName();
1019 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001020 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001021 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +00001022 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001023 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001024 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001025 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001026 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001027
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001028 RewriteProperties(ClassDecl->getNumPropertyDecl(),
1029 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001030 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001031 E = ClassDecl->instmeth_end(); I != E; ++I)
1032 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001033 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001034 E = ClassDecl->classmeth_end(); I != E; ++I)
1035 RewriteMethodDeclaration(*I);
1036
Steve Naroff2feac5e2007-10-30 03:43:13 +00001037 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001038 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001039}
1040
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001041Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1042 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001043 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001044 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001045 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001046 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1047 // lookup which class implements the instance variable.
1048 ObjCInterfaceDecl *clsDeclared = 0;
1049 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1050 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1051
1052 // Synthesize an explicit cast to gain access to the ivar.
1053 std::string RecName = clsDeclared->getIdentifier()->getName();
1054 RecName += "_IMPL";
1055 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001056 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001057 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001058 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1059 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001060 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
1061 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001062 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001063 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1064 IV->getBase()->getLocEnd(),
1065 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001066 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001067 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001068 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1069 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001070 ReplaceStmt(IV, ME);
1071 delete IV;
1072 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001073 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001074
1075 ReplaceStmt(IV->getBase(), PE);
1076 // Cannot delete IV->getBase(), since PE points to it.
1077 // Replace the old base with the cast. This is important when doing
1078 // embedded rewrites. For example, [newInv->_container addObject:0].
1079 IV->setBase(PE);
1080 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001081 }
Steve Naroff84472a82008-04-18 21:55:08 +00001082 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001083 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1084
1085 // Explicit ivar refs need to have a cast inserted.
1086 // FIXME: consider sharing some of this code with the code above.
1087 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001088 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001089 // lookup which class implements the instance variable.
1090 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001091 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001092 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1093
1094 // Synthesize an explicit cast to gain access to the ivar.
1095 std::string RecName = clsDeclared->getIdentifier()->getName();
1096 RecName += "_IMPL";
1097 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001098 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001099 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001100 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1101 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001102 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
1103 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001104 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001105 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1106 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001107 ReplaceStmt(IV->getBase(), PE);
1108 // Cannot delete IV->getBase(), since PE points to it.
1109 // Replace the old base with the cast. This is important when doing
1110 // embedded rewrites. For example, [newInv->_container addObject:0].
1111 IV->setBase(PE);
1112 return IV;
1113 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001114 }
Steve Naroff84472a82008-04-18 21:55:08 +00001115 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001116}
1117
Chris Lattnerf04da132007-10-24 17:06:59 +00001118//===----------------------------------------------------------------------===//
1119// Function Body / Expression rewriting
1120//===----------------------------------------------------------------------===//
1121
Steve Naroffb29b4272008-04-14 22:03:09 +00001122Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001123 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1124 isa<DoStmt>(S) || isa<ForStmt>(S))
1125 Stmts.push_back(S);
1126 else if (isa<ObjCForCollectionStmt>(S)) {
1127 Stmts.push_back(S);
1128 ObjCBcLabelNo.push_back(++BcLabelCount);
1129 }
1130
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001131 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner338d1e22008-01-31 05:10:40 +00001132
1133 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +00001134 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1135 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +00001136 if (*CI) {
Steve Naroffa48396e2008-10-27 18:50:14 +00001137 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
1138 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(CBE->getBody());
1139 if (newStmt)
1140 *CI = newStmt;
1141
1142 // We've just rewritten the block body in place.
1143 // Now we snarf the rewritten text and stash it away for later use.
1144 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1145 RewrittenBlockExprs[CBE] = S;
1146 std::string Init = SynthesizeBlockInitExpr(CBE);
1147 // Do the rewrite, using S.size() which contains the rewritten size.
1148 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
1149 } else {
1150 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
1151 if (newStmt)
1152 *CI = newStmt;
1153 }
Steve Naroff75730982007-11-07 04:08:17 +00001154 }
Steve Naroffebf2b562007-10-23 23:50:29 +00001155
1156 // Handle specific things.
1157 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
1158 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001159
1160 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001161 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroffb42f8412007-11-05 14:50:49 +00001162
1163 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
1164 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +00001165
Steve Naroffbeaf2992007-11-03 11:27:19 +00001166 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
1167 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +00001168
Steve Naroff934f2762007-10-24 22:48:43 +00001169 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
1170 // Before we rewrite it, put the original message expression in a comment.
1171 SourceLocation startLoc = MessExpr->getLocStart();
1172 SourceLocation endLoc = MessExpr->getLocEnd();
1173
1174 const char *startBuf = SM->getCharacterData(startLoc);
1175 const char *endBuf = SM->getCharacterData(endLoc);
1176
1177 std::string messString;
1178 messString += "// ";
1179 messString.append(startBuf, endBuf-startBuf+1);
1180 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +00001181
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001182 // FIXME: Missing definition of
1183 // InsertText(clang::SourceLocation, char const*, unsigned int).
1184 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +00001185 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001186 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +00001187 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001188 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001189
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001190 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
1191 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +00001192
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001193 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
1194 return RewriteObjCSynchronizedStmt(StmtTry);
1195
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001196 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
1197 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001198
1199 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
1200 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001201
1202 if (ObjCForCollectionStmt *StmtForCollection =
1203 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001204 return RewriteObjCForCollectionStmt(StmtForCollection,
1205 OrigStmtRange.getEnd());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001206 if (BreakStmt *StmtBreakStmt =
1207 dyn_cast<BreakStmt>(S))
1208 return RewriteBreakStmt(StmtBreakStmt);
1209 if (ContinueStmt *StmtContinueStmt =
1210 dyn_cast<ContinueStmt>(S))
1211 return RewriteContinueStmt(StmtContinueStmt);
Steve Naroff4f95b752008-07-29 18:15:38 +00001212
Ted Kremenekab9bae72008-10-06 22:45:07 +00001213 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
1214 // and cast exprs.
1215 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
1216 // FIXME: What we're doing here is modifying the type-specifier that
1217 // precedes the first Decl. In the future the DeclGroup should have
1218 // a separate type-specifier that we can rewrite.
1219 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Steve Naroff54055232008-10-27 17:20:55 +00001220
1221 // Blocks rewrite rules.
1222 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
1223 DI != DE; ++DI) {
1224
1225 ScopedDecl *SD = *DI;
1226 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
1227 if (isBlockPointerType(ND->getType()))
1228 RewriteBlockPointerDecl(ND);
1229 else if (ND->getType()->isFunctionPointerType())
1230 CheckFunctionPointerDecl(ND->getType(), ND);
1231 }
1232 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
1233 if (isBlockPointerType(TD->getUnderlyingType()))
1234 RewriteBlockPointerDecl(TD);
1235 else if (TD->getUnderlyingType()->isFunctionPointerType())
1236 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
1237 }
1238 }
Ted Kremenekab9bae72008-10-06 22:45:07 +00001239 }
1240
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001241 if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(S))
Steve Naroff4f95b752008-07-29 18:15:38 +00001242 RewriteObjCQualifiedInterfaceTypes(CE);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001243
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001244 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1245 isa<DoStmt>(S) || isa<ForStmt>(S)) {
1246 assert(!Stmts.empty() && "Statement stack is empty");
1247 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
1248 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
1249 && "Statement stack mismatch");
1250 Stmts.pop_back();
1251 }
Steve Naroff54055232008-10-27 17:20:55 +00001252 // Handle blocks rewriting.
1253 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
1254 if (BDRE->isByRef())
1255 RewriteBlockDeclRefExpr(BDRE);
1256 }
1257 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1258 if (CE->getCallee()->getType()->isBlockPointerType())
1259 RewriteBlockCall(CE);
1260 }
1261 if (CastExpr *CE = dyn_cast<CastExpr>(S)) {
1262 RewriteCastExpr(CE);
1263 }
Steve Naroff874e2322007-11-15 10:28:18 +00001264#if 0
1265 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
1266 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
1267 // Get the new text.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001268 std::string SStr;
1269 llvm::raw_string_ostream Buf(SStr);
Steve Naroff874e2322007-11-15 10:28:18 +00001270 Replacement->printPretty(Buf);
1271 const std::string &Str = Buf.str();
1272
1273 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001274 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +00001275 delete S;
1276 return Replacement;
1277 }
1278#endif
Chris Lattnere64b7772007-10-24 16:57:36 +00001279 // Return this stmt unmodified.
1280 return S;
Chris Lattner311ff022007-10-16 22:36:42 +00001281}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001282
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001283/// SynthCountByEnumWithState - To print:
1284/// ((unsigned int (*)
1285/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1286/// (void *)objc_msgSend)((id)l_collection,
1287/// sel_registerName(
1288/// "countByEnumeratingWithState:objects:count:"),
1289/// &enumState,
1290/// (id *)items, (unsigned int)16)
1291///
Steve Naroffb29b4272008-04-14 22:03:09 +00001292void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001293 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1294 "id *, unsigned int))(void *)objc_msgSend)";
1295 buf += "\n\t\t";
1296 buf += "((id)l_collection,\n\t\t";
1297 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1298 buf += "\n\t\t";
1299 buf += "&enumState, "
1300 "(id *)items, (unsigned int)16)";
1301}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001302
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001303/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1304/// statement to exit to its outer synthesized loop.
1305///
Steve Naroffb29b4272008-04-14 22:03:09 +00001306Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001307 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1308 return S;
1309 // replace break with goto __break_label
1310 std::string buf;
1311
1312 SourceLocation startLoc = S->getLocStart();
1313 buf = "goto __break_label_";
1314 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001315 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001316
1317 return 0;
1318}
1319
1320/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1321/// statement to continue with its inner synthesized loop.
1322///
Steve Naroffb29b4272008-04-14 22:03:09 +00001323Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001324 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1325 return S;
1326 // replace continue with goto __continue_label
1327 std::string buf;
1328
1329 SourceLocation startLoc = S->getLocStart();
1330 buf = "goto __continue_label_";
1331 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001332 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001333
1334 return 0;
1335}
1336
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001337/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001338/// It rewrites:
1339/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001340
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001341/// Into:
1342/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001343/// type elem;
1344/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001345/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001346/// id l_collection = (id)collection;
1347/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1348/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001349/// if (limit) {
1350/// unsigned long startMutations = *enumState.mutationsPtr;
1351/// do {
1352/// unsigned long counter = 0;
1353/// do {
1354/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001355/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001356/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001357/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001358/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001359/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001360/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1361/// objects:items count:16]);
1362/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001363/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001364/// }
1365/// else
1366/// elem = nil;
1367/// }
1368///
Steve Naroffb29b4272008-04-14 22:03:09 +00001369Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001370 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001371 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1372 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1373 "ObjCForCollectionStmt Statement stack mismatch");
1374 assert(!ObjCBcLabelNo.empty() &&
1375 "ObjCForCollectionStmt - Label No stack empty");
1376
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001377 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001378 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001379 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001380 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001381 std::string buf;
1382 buf = "\n{\n\t";
1383 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1384 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001385 ScopedDecl* D = DS->getSolitaryDecl();
1386 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001387 elementTypeAsString = ElementType.getAsString();
1388 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001389 buf += " ";
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001390 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001391 buf += elementName;
1392 buf += ";\n\t";
1393 }
Chris Lattner06767512008-04-08 05:52:18 +00001394 else {
1395 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001396 elementName = DR->getDecl()->getName();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001397 elementTypeAsString
1398 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001399 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001400
1401 // struct __objcFastEnumerationState enumState = { 0 };
1402 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1403 // id items[16];
1404 buf += "id items[16];\n\t";
1405 // id l_collection = (id)
1406 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001407 // Find start location of 'collection' the hard way!
1408 const char *startCollectionBuf = startBuf;
1409 startCollectionBuf += 3; // skip 'for'
1410 startCollectionBuf = strchr(startCollectionBuf, '(');
1411 startCollectionBuf++; // skip '('
1412 // find 'in' and skip it.
1413 while (*startCollectionBuf != ' ' ||
1414 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1415 (*(startCollectionBuf+3) != ' ' &&
1416 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1417 startCollectionBuf++;
1418 startCollectionBuf += 3;
1419
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001420 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001421 ReplaceText(startLoc, startCollectionBuf - startBuf,
1422 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001423 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001424 SourceLocation rightParenLoc = S->getRParenLoc();
1425 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1426 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001427 buf = ";\n\t";
1428
1429 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1430 // objects:items count:16];
1431 // which is synthesized into:
1432 // unsigned int limit =
1433 // ((unsigned int (*)
1434 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1435 // (void *)objc_msgSend)((id)l_collection,
1436 // sel_registerName(
1437 // "countByEnumeratingWithState:objects:count:"),
1438 // (struct __objcFastEnumerationState *)&state,
1439 // (id *)items, (unsigned int)16);
1440 buf += "unsigned long limit =\n\t\t";
1441 SynthCountByEnumWithState(buf);
1442 buf += ";\n\t";
1443 /// if (limit) {
1444 /// unsigned long startMutations = *enumState.mutationsPtr;
1445 /// do {
1446 /// unsigned long counter = 0;
1447 /// do {
1448 /// if (startMutations != *enumState.mutationsPtr)
1449 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001450 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001451 buf += "if (limit) {\n\t";
1452 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1453 buf += "do {\n\t\t";
1454 buf += "unsigned long counter = 0;\n\t\t";
1455 buf += "do {\n\t\t\t";
1456 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1457 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1458 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001459 buf += " = (";
1460 buf += elementTypeAsString;
1461 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001462 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001463 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001464
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001465 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001466 /// } while (counter < limit);
1467 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1468 /// objects:items count:16]);
1469 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001470 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001471 /// }
1472 /// else
1473 /// elem = nil;
1474 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001475 ///
1476 buf = ";\n\t";
1477 buf += "__continue_label_";
1478 buf += utostr(ObjCBcLabelNo.back());
1479 buf += ": ;";
1480 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001481 buf += "} while (counter < limit);\n\t";
1482 buf += "} while (limit = ";
1483 SynthCountByEnumWithState(buf);
1484 buf += ");\n\t";
1485 buf += elementName;
1486 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001487 buf += "__break_label_";
1488 buf += utostr(ObjCBcLabelNo.back());
1489 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001490 buf += "}\n\t";
1491 buf += "else\n\t\t";
1492 buf += elementName;
1493 buf += " = nil;\n";
1494 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001495
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001496 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001497 if (isa<CompoundStmt>(S->getBody())) {
1498 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1499 InsertText(endBodyLoc, buf.c_str(), buf.size());
1500 } else {
1501 /* Need to treat single statements specially. For example:
1502 *
1503 * for (A *a in b) if (stuff()) break;
1504 * for (A *a in b) xxxyy;
1505 *
1506 * The following code simply scans ahead to the semi to find the actual end.
1507 */
1508 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1509 const char *semiBuf = strchr(stmtBuf, ';');
1510 assert(semiBuf && "Can't find ';'");
1511 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1512 InsertText(endBodyLoc, buf.c_str(), buf.size());
1513 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001514 Stmts.pop_back();
1515 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001516 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001517}
1518
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001519/// RewriteObjCSynchronizedStmt -
1520/// This routine rewrites @synchronized(expr) stmt;
1521/// into:
1522/// objc_sync_enter(expr);
1523/// @try stmt @finally { objc_sync_exit(expr); }
1524///
Steve Naroffb29b4272008-04-14 22:03:09 +00001525Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001526 // Get the start location and compute the semi location.
1527 SourceLocation startLoc = S->getLocStart();
1528 const char *startBuf = SM->getCharacterData(startLoc);
1529
1530 assert((*startBuf == '@') && "bogus @synchronized location");
1531
1532 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001533 buf = "objc_sync_enter((id)";
1534 const char *lparenBuf = startBuf;
1535 while (*lparenBuf != '(') lparenBuf++;
1536 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001537 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1538 // the sync expression is typically a message expression that's already
1539 // been rewritten! (which implies the SourceLocation's are invalid).
1540 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001541 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001542 while (*endBuf != ')') endBuf--;
1543 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001544 buf = ");\n";
1545 // declare a new scope with two variables, _stack and _rethrow.
1546 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1547 buf += "int buf[18/*32-bit i386*/];\n";
1548 buf += "char *pointers[4];} _stack;\n";
1549 buf += "id volatile _rethrow = 0;\n";
1550 buf += "objc_exception_try_enter(&_stack);\n";
1551 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001552 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001553 startLoc = S->getSynchBody()->getLocEnd();
1554 startBuf = SM->getCharacterData(startLoc);
1555
Steve Naroffc7089f12008-08-19 13:04:19 +00001556 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001557 SourceLocation lastCurlyLoc = startLoc;
1558 buf = "}\nelse {\n";
1559 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1560 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001561 buf += " objc_sync_exit(";
Steve Naroff3498cc92008-08-21 13:03:03 +00001562 Expr *syncExpr = new ExplicitCastExpr(Context->getObjCIdType(),
1563 S->getSynchExpr(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001564 std::string syncExprBufS;
1565 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001566 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001567 buf += syncExprBuf.str();
1568 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001569 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1570 buf += "}\n";
1571 buf += "}";
1572
Chris Lattneraadaf782008-01-31 19:51:04 +00001573 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001574 return 0;
1575}
1576
Steve Naroffb29b4272008-04-14 22:03:09 +00001577Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001578 // Get the start location and compute the semi location.
1579 SourceLocation startLoc = S->getLocStart();
1580 const char *startBuf = SM->getCharacterData(startLoc);
1581
1582 assert((*startBuf == '@') && "bogus @try location");
1583
1584 std::string buf;
1585 // declare a new scope with two variables, _stack and _rethrow.
1586 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1587 buf += "int buf[18/*32-bit i386*/];\n";
1588 buf += "char *pointers[4];} _stack;\n";
1589 buf += "id volatile _rethrow = 0;\n";
1590 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001591 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001592
Chris Lattneraadaf782008-01-31 19:51:04 +00001593 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001594
1595 startLoc = S->getTryBody()->getLocEnd();
1596 startBuf = SM->getCharacterData(startLoc);
1597
1598 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001599
Steve Naroff75730982007-11-07 04:08:17 +00001600 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001601 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1602 if (catchList) {
1603 startLoc = startLoc.getFileLocWithOffset(1);
1604 buf = " /* @catch begin */ else {\n";
1605 buf += " id _caught = objc_exception_extract(&_stack);\n";
1606 buf += " objc_exception_try_enter (&_stack);\n";
1607 buf += " if (_setjmp(_stack.buf))\n";
1608 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1609 buf += " else { /* @catch continue */";
1610
1611 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001612 } else { /* no catch list */
1613 buf = "}\nelse {\n";
1614 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1615 buf += "}";
1616 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001617 }
Steve Naroff75730982007-11-07 04:08:17 +00001618 bool sawIdTypedCatch = false;
1619 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001620 while (catchList) {
1621 Stmt *catchStmt = catchList->getCatchParamStmt();
1622
1623 if (catchList == S->getCatchStmts())
1624 buf = "if ("; // we are generating code for the first catch clause
1625 else
1626 buf = "else if (";
1627 startLoc = catchList->getLocStart();
1628 startBuf = SM->getCharacterData(startLoc);
1629
1630 assert((*startBuf == '@') && "bogus @catch location");
1631
1632 const char *lParenLoc = strchr(startBuf, '(');
1633
Steve Naroffbe4b3332008-02-01 22:08:12 +00001634 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001635 // Now rewrite the body...
1636 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001637 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1638 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001639 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1640 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001641 assert((*bodyBuf == '{') && "bogus @catch body location");
1642
1643 buf += "1) { id _tmp = _caught;";
1644 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1645 buf.c_str(), buf.size());
1646 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001647 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001648 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001649 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001650 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001651 sawIdTypedCatch = true;
1652 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001653 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001654
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001655 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001656 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001657 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001658 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001659 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001660 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001661 }
1662 }
1663 // Now rewrite the body...
1664 lastCatchBody = catchList->getCatchBody();
1665 SourceLocation rParenLoc = catchList->getRParenLoc();
1666 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1667 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1668 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1669 assert((*rParenBuf == ')') && "bogus @catch paren location");
1670 assert((*bodyBuf == '{') && "bogus @catch body location");
1671
1672 buf = " = _caught;";
1673 // Here we replace ") {" with "= _caught;" (which initializes and
1674 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001675 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001676 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001677 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001678 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001679 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001680 catchList = catchList->getNextCatchStmt();
1681 }
1682 // Complete the catch list...
1683 if (lastCatchBody) {
1684 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001685 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1686 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001687
Steve Naroff378f47a2008-09-11 15:29:03 +00001688 // Insert the last (implicit) else clause *before* the right curly brace.
1689 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1690 buf = "} /* last catch end */\n";
1691 buf += "else {\n";
1692 buf += " _rethrow = _caught;\n";
1693 buf += " objc_exception_try_exit(&_stack);\n";
1694 buf += "} } /* @catch end */\n";
1695 if (!S->getFinallyStmt())
1696 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001697 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001698
1699 // Set lastCurlyLoc
1700 lastCurlyLoc = lastCatchBody->getLocEnd();
1701 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001702 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001703 startLoc = finalStmt->getLocStart();
1704 startBuf = SM->getCharacterData(startLoc);
1705 assert((*startBuf == '@') && "bogus @finally start");
1706
1707 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001708 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001709
1710 Stmt *body = finalStmt->getFinallyBody();
1711 SourceLocation startLoc = body->getLocStart();
1712 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001713 assert(*SM->getCharacterData(startLoc) == '{' &&
1714 "bogus @finally body location");
1715 assert(*SM->getCharacterData(endLoc) == '}' &&
1716 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001717
1718 startLoc = startLoc.getFileLocWithOffset(1);
1719 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001720 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001721 endLoc = endLoc.getFileLocWithOffset(-1);
1722 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001723 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001724
1725 // Set lastCurlyLoc
1726 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001727 } else { /* no finally clause - make sure we synthesize an implicit one */
1728 buf = "{ /* implicit finally clause */\n";
1729 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1730 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1731 buf += "}";
1732 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001733 }
1734 // Now emit the final closing curly brace...
1735 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1736 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001737 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001738 return 0;
1739}
1740
Steve Naroffb29b4272008-04-14 22:03:09 +00001741Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001742 return 0;
1743}
1744
Steve Naroffb29b4272008-04-14 22:03:09 +00001745Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001746 return 0;
1747}
1748
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001749// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001750// the throw expression is typically a message expression that's already
1751// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001752Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001753 // Get the start location and compute the semi location.
1754 SourceLocation startLoc = S->getLocStart();
1755 const char *startBuf = SM->getCharacterData(startLoc);
1756
1757 assert((*startBuf == '@') && "bogus @throw location");
1758
1759 std::string buf;
1760 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001761 if (S->getThrowExpr())
1762 buf = "objc_exception_throw(";
1763 else // add an implicit argument
1764 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001765
1766 // handle "@ throw" correctly.
1767 const char *wBuf = strchr(startBuf, 'w');
1768 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1769 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1770
Steve Naroff2bd03922007-11-07 15:32:26 +00001771 const char *semiBuf = strchr(startBuf, ';');
1772 assert((*semiBuf == ';') && "@throw: can't find ';'");
1773 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1774 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001775 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001776 return 0;
1777}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001778
Steve Naroffb29b4272008-04-14 22:03:09 +00001779Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001780 // Create a new string expression.
1781 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001782 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001783 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001784 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1785 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001786 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001787 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001788
Chris Lattner07506182007-11-30 22:53:43 +00001789 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001790 delete Exp;
1791 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001792}
1793
Steve Naroffb29b4272008-04-14 22:03:09 +00001794Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001795 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1796 // Create a call to sel_registerName("selName").
1797 llvm::SmallVector<Expr*, 8> SelExprs;
1798 QualType argType = Context->getPointerType(Context->CharTy);
1799 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1800 Exp->getSelector().getName().size(),
1801 false, argType, SourceLocation(),
1802 SourceLocation()));
1803 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1804 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001805 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001806 delete Exp;
1807 return SelExp;
1808}
1809
Steve Naroffb29b4272008-04-14 22:03:09 +00001810CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001811 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001812 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001813 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001814
1815 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001816 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001817
1818 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001819 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001820 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1821
1822 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001823
Steve Naroff934f2762007-10-24 22:48:43 +00001824 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1825}
1826
Steve Naroffd5255f52007-11-01 13:24:47 +00001827static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1828 const char *&startRef, const char *&endRef) {
1829 while (startBuf < endBuf) {
1830 if (*startBuf == '<')
1831 startRef = startBuf; // mark the start.
1832 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001833 if (startRef && *startRef == '<') {
1834 endRef = startBuf; // mark the end.
1835 return true;
1836 }
1837 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001838 }
1839 startBuf++;
1840 }
1841 return false;
1842}
1843
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001844static void scanToNextArgument(const char *&argRef) {
1845 int angle = 0;
1846 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1847 if (*argRef == '<')
1848 angle++;
1849 else if (*argRef == '>')
1850 angle--;
1851 argRef++;
1852 }
1853 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1854}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001855
Steve Naroffb29b4272008-04-14 22:03:09 +00001856bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001857
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001858 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001859 return true;
1860
Steve Naroffd5255f52007-11-01 13:24:47 +00001861 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001862 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001863 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001864 return true; // we have "Class <Protocol> *".
1865 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001866 return false;
1867}
1868
Steve Naroff4f95b752008-07-29 18:15:38 +00001869void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1870 QualType Type = E->getType();
1871 if (needToScanForQualifiers(Type)) {
1872 SourceLocation Loc = E->getLocStart();
1873 const char *startBuf = SM->getCharacterData(Loc);
1874 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1875 const char *startRef = 0, *endRef = 0;
1876 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1877 // Get the locations of the startRef, endRef.
1878 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1879 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1880 // Comment out the protocol references.
1881 InsertText(LessLoc, "/*", 2);
1882 InsertText(GreaterLoc, "*/", 2);
1883 }
1884 }
1885}
1886
Steve Naroffb29b4272008-04-14 22:03:09 +00001887void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001888 SourceLocation Loc;
1889 QualType Type;
1890 const FunctionTypeProto *proto = 0;
1891 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1892 Loc = VD->getLocation();
1893 Type = VD->getType();
1894 }
1895 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1896 Loc = FD->getLocation();
1897 // Check for ObjC 'id' and class types that have been adorned with protocol
1898 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1899 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1900 assert(funcType && "missing function type");
1901 proto = dyn_cast<FunctionTypeProto>(funcType);
1902 if (!proto)
1903 return;
1904 Type = proto->getResultType();
1905 }
1906 else
1907 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001908
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001909 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001910 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001911
1912 const char *endBuf = SM->getCharacterData(Loc);
1913 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001914 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001915 startBuf--; // scan backward (from the decl location) for return type.
1916 const char *startRef = 0, *endRef = 0;
1917 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1918 // Get the locations of the startRef, endRef.
1919 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1920 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1921 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001922 InsertText(LessLoc, "/*", 2);
1923 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001924 }
1925 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001926 if (!proto)
1927 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001928 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001929 const char *startBuf = SM->getCharacterData(Loc);
1930 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001931 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1932 if (needToScanForQualifiers(proto->getArgType(i))) {
1933 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001934
Steve Naroffd5255f52007-11-01 13:24:47 +00001935 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001936 // scan forward (from the decl location) for argument types.
1937 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001938 const char *startRef = 0, *endRef = 0;
1939 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1940 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001941 SourceLocation LessLoc =
1942 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1943 SourceLocation GreaterLoc =
1944 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001945 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001946 InsertText(LessLoc, "/*", 2);
1947 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001948 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001949 startBuf = ++endBuf;
1950 }
1951 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001952 // If the function name is derived from a macro expansion, then the
1953 // argument buffer will not follow the name. Need to speak with Chris.
1954 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001955 startBuf++; // scan forward (from the decl location) for argument types.
1956 startBuf++;
1957 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001958 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001959}
1960
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001961// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001962void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001963 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1964 llvm::SmallVector<QualType, 16> ArgTys;
1965 ArgTys.push_back(Context->getPointerType(
1966 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001967 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001968 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001969 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001970 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001971 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001972 SelGetUidIdent, getFuncType,
1973 FunctionDecl::Extern, false, 0);
1974}
1975
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001976// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001977void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001978 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1979 llvm::SmallVector<QualType, 16> ArgTys;
1980 ArgTys.push_back(Context->getPointerType(
1981 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001982 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001983 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001984 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001985 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001986 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001987 SelGetProtoIdent, getFuncType,
1988 FunctionDecl::Extern, false, 0);
1989}
1990
Steve Naroffb29b4272008-04-14 22:03:09 +00001991void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001992 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001993 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001994 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001995 return;
1996 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001997 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001998}
1999
Steve Naroffc0a123c2008-03-11 17:37:02 +00002000// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002001void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002002 if (SuperContructorFunctionDecl)
2003 return;
2004 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
2005 llvm::SmallVector<QualType, 16> ArgTys;
2006 QualType argT = Context->getObjCIdType();
2007 assert(!argT.isNull() && "Can't find 'id' type");
2008 ArgTys.push_back(argT);
2009 ArgTys.push_back(argT);
2010 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2011 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002012 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002013 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002014 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00002015 msgSendIdent, msgSendType,
2016 FunctionDecl::Extern, false, 0);
2017}
2018
Steve Naroff09b266e2007-10-30 23:14:51 +00002019// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002020void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002021 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2022 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002023 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002024 assert(!argT.isNull() && "Can't find 'id' type");
2025 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002026 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002027 assert(!argT.isNull() && "Can't find 'SEL' type");
2028 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002029 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002030 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002031 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002032 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002033 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002034 msgSendIdent, msgSendType,
2035 FunctionDecl::Extern, false, 0);
2036}
2037
Steve Naroff874e2322007-11-15 10:28:18 +00002038// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002039void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002040 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2041 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002042 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002043 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002044 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002045 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2046 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2047 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002048 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002049 assert(!argT.isNull() && "Can't find 'SEL' type");
2050 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002051 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002052 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002053 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002054 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002055 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002056 msgSendIdent, msgSendType,
2057 FunctionDecl::Extern, false, 0);
2058}
2059
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002060// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002061void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002062 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2063 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002064 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002065 assert(!argT.isNull() && "Can't find 'id' type");
2066 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002067 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002068 assert(!argT.isNull() && "Can't find 'SEL' type");
2069 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002070 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002071 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002072 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002073 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002074 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002075 msgSendIdent, msgSendType,
2076 FunctionDecl::Extern, false, 0);
2077}
2078
2079// SynthMsgSendSuperStretFunctionDecl -
2080// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002081void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002082 IdentifierInfo *msgSendIdent =
2083 &Context->Idents.get("objc_msgSendSuper_stret");
2084 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002085 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002086 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002087 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002088 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2089 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2090 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002091 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002092 assert(!argT.isNull() && "Can't find 'SEL' type");
2093 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002094 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002095 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002096 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002097 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002098 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002099 msgSendIdent, msgSendType,
2100 FunctionDecl::Extern, false, 0);
2101}
2102
Steve Naroff1284db82008-05-08 22:02:18 +00002103// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002104void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002105 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2106 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002107 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002108 assert(!argT.isNull() && "Can't find 'id' type");
2109 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002110 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002111 assert(!argT.isNull() && "Can't find 'SEL' type");
2112 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002113 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002114 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002115 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002116 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002117 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002118 msgSendIdent, msgSendType,
2119 FunctionDecl::Extern, false, 0);
2120}
2121
Steve Naroff09b266e2007-10-30 23:14:51 +00002122// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002123void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002124 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2125 llvm::SmallVector<QualType, 16> ArgTys;
2126 ArgTys.push_back(Context->getPointerType(
2127 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002128 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002129 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002130 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002131 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002132 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002133 getClassIdent, getClassType,
2134 FunctionDecl::Extern, false, 0);
2135}
2136
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002137// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002138void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002139 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2140 llvm::SmallVector<QualType, 16> ArgTys;
2141 ArgTys.push_back(Context->getPointerType(
2142 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002143 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002144 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002145 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002146 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002147 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002148 getClassIdent, getClassType,
2149 FunctionDecl::Extern, false, 0);
2150}
2151
Steve Naroffb29b4272008-04-14 22:03:09 +00002152Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002153 QualType strType = getConstantStringStructType();
2154
2155 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002156
2157 std::string tmpName = InFileName;
2158 unsigned i;
2159 for (i=0; i < tmpName.length(); i++) {
2160 char c = tmpName.at(i);
2161 // replace any non alphanumeric characters with '_'.
2162 if (!isalpha(c) && (c < '0' || c > '9'))
2163 tmpName[i] = '_';
2164 }
2165 S += tmpName;
2166 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002167 S += utostr(NumObjCStringLiterals++);
2168
Steve Naroffba92b2e2008-03-27 22:29:16 +00002169 Preamble += "static __NSConstantStringImpl " + S;
2170 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2171 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002172 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002173 std::string prettyBufS;
2174 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002175 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002176 Preamble += prettyBuf.str();
2177 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002178 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002179 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002180
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002181 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002182 &Context->Idents.get(S.c_str()), strType,
2183 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002184 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2185 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2186 Context->getPointerType(DRE->getType()),
2187 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002188 // cast to NSConstantString *
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002189 CastExpr *cast = new ExplicitCastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002190 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00002191 delete Exp;
2192 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002193}
2194
Steve Naroffb29b4272008-04-14 22:03:09 +00002195ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002196 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002197 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002198
Chris Lattnerd9f69102008-08-10 01:53:14 +00002199 if (PredefinedExpr *PDE = dyn_cast<PredefinedExpr>(recExpr))
2200 if (PDE->getIdentType() == PredefinedExpr::ObjCSuper) {
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002201 const PointerType *PT = PDE->getType()->getAsPointerType();
2202 assert(PT);
2203 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2204 return IT->getDecl();
2205 }
2206 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002207}
2208
2209// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002210QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002211 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002212 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002213 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002214 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002215 QualType FieldTypes[2];
2216
2217 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002218 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002219 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002220 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002221 // Create fields
2222 FieldDecl *FieldDecls[2];
2223
2224 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002225 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002226 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002227
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002228 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002229 }
2230 return Context->getTagDeclType(SuperStructDecl);
2231}
2232
Steve Naroffb29b4272008-04-14 22:03:09 +00002233QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002234 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002235 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002236 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002237 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002238 QualType FieldTypes[4];
2239
2240 // struct objc_object *receiver;
2241 FieldTypes[0] = Context->getObjCIdType();
2242 // int flags;
2243 FieldTypes[1] = Context->IntTy;
2244 // char *str;
2245 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2246 // long length;
2247 FieldTypes[3] = Context->LongTy;
2248 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002249 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002250
2251 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002252 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002253 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002254
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002255 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002256 }
2257 return Context->getTagDeclType(ConstantStringDecl);
2258}
2259
Steve Naroffb29b4272008-04-14 22:03:09 +00002260Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002261 if (!SelGetUidFunctionDecl)
2262 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002263 if (!MsgSendFunctionDecl)
2264 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002265 if (!MsgSendSuperFunctionDecl)
2266 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002267 if (!MsgSendStretFunctionDecl)
2268 SynthMsgSendStretFunctionDecl();
2269 if (!MsgSendSuperStretFunctionDecl)
2270 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002271 if (!MsgSendFpretFunctionDecl)
2272 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002273 if (!GetClassFunctionDecl)
2274 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002275 if (!GetMetaClassFunctionDecl)
2276 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002277
Steve Naroff874e2322007-11-15 10:28:18 +00002278 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002279 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2280 // May need to use objc_msgSend_stret() as well.
2281 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002282 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002283 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002284 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002285 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002286 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002287 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002288 }
Steve Naroff874e2322007-11-15 10:28:18 +00002289
Steve Naroff934f2762007-10-24 22:48:43 +00002290 // Synthesize a call to objc_msgSend().
2291 llvm::SmallVector<Expr*, 8> MsgExprs;
2292 IdentifierInfo *clsName = Exp->getClassName();
2293
2294 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2295 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002296 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2297 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002298 if (!strcmp(clsName->getName(), "super")) {
2299 MsgSendFlavor = MsgSendSuperFunctionDecl;
2300 if (MsgSendStretFlavor)
2301 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2302 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2303
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002304 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002305 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002306
2307 llvm::SmallVector<Expr*, 4> InitExprs;
2308
2309 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002310 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002311 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002312 Context->getObjCIdType(),
2313 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002314 llvm::SmallVector<Expr*, 8> ClsExprs;
2315 QualType argType = Context->getPointerType(Context->CharTy);
2316 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2317 SuperDecl->getIdentifier()->getLength(),
2318 false, argType, SourceLocation(),
2319 SourceLocation()));
2320 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2321 &ClsExprs[0],
2322 ClsExprs.size());
2323 // To turn off a warning, type-cast to 'id'
2324 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002325 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002326 Cls, SourceLocation())); // set 'super class', using objc_getClass().
2327 // struct objc_super
2328 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002329 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002330
Steve Naroff23f41272008-03-11 18:14:26 +00002331 if (LangOpts.Microsoft) {
2332 SynthSuperContructorFunctionDecl();
2333 // Simulate a contructor call...
2334 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2335 superType, SourceLocation());
2336 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2337 superType, SourceLocation());
2338 } else {
2339 // (struct objc_super) { <exprs from above> }
2340 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2341 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002342 SourceLocation(), false);
2343 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2344 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002345 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002346 // struct objc_super *
2347 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2348 Context->getPointerType(SuperRep->getType()),
2349 SourceLocation());
2350 MsgExprs.push_back(Unop);
2351 } else {
2352 llvm::SmallVector<Expr*, 8> ClsExprs;
2353 QualType argType = Context->getPointerType(Context->CharTy);
2354 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2355 clsName->getLength(),
2356 false, argType, SourceLocation(),
2357 SourceLocation()));
2358 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2359 &ClsExprs[0],
2360 ClsExprs.size());
2361 MsgExprs.push_back(Cls);
2362 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002363 } else { // instance message.
2364 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002365
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002366 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002367 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002368 if (MsgSendStretFlavor)
2369 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002370 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2371
2372 llvm::SmallVector<Expr*, 4> InitExprs;
2373
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002374 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002375 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002376 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002377 Context->getObjCIdType(),
2378 SourceLocation()),
2379 SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002380
2381 llvm::SmallVector<Expr*, 8> ClsExprs;
2382 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002383 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2384 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002385 false, argType, SourceLocation(),
2386 SourceLocation()));
2387 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002388 &ClsExprs[0],
2389 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002390 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002391 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002392 new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002393 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002394 // struct objc_super
2395 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002396 Expr *SuperRep;
2397
2398 if (LangOpts.Microsoft) {
2399 SynthSuperContructorFunctionDecl();
2400 // Simulate a contructor call...
2401 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2402 superType, SourceLocation());
2403 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2404 superType, SourceLocation());
2405 } else {
2406 // (struct objc_super) { <exprs from above> }
2407 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2408 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002409 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002410 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2411 }
Steve Naroff874e2322007-11-15 10:28:18 +00002412 // struct objc_super *
2413 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2414 Context->getPointerType(SuperRep->getType()),
2415 SourceLocation());
2416 MsgExprs.push_back(Unop);
2417 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002418 // Remove all type-casts because it may contain objc-style types; e.g.
2419 // Foo<Proto> *.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002420 while (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002421 recExpr = CE->getSubExpr();
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002422 recExpr = new ExplicitCastExpr(Context->getObjCIdType(), recExpr,
2423 SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002424 MsgExprs.push_back(recExpr);
2425 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002426 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002427 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002428 llvm::SmallVector<Expr*, 8> SelExprs;
2429 QualType argType = Context->getPointerType(Context->CharTy);
2430 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2431 Exp->getSelector().getName().size(),
2432 false, argType, SourceLocation(),
2433 SourceLocation()));
2434 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2435 &SelExprs[0], SelExprs.size());
2436 MsgExprs.push_back(SelExp);
2437
2438 // Now push any user supplied arguments.
2439 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002440 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002441 // Make all implicit casts explicit...ICE comes in handy:-)
2442 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2443 // Reuse the ICE type, it is exactly what the doctor ordered.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002444 userExpr = new ExplicitCastExpr(ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002445 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002446 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002447 }
2448 // Make id<P...> cast into an 'id' cast.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002449 else if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002450 if (CE->getType()->isObjCQualifiedIdType()) {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002451 while ((CE = dyn_cast<ExplicitCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002452 userExpr = CE->getSubExpr();
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002453 userExpr = new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002454 userExpr, SourceLocation());
2455 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002456 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002457 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002458 // We've transferred the ownership to MsgExprs. Null out the argument in
2459 // the original expression, since we will delete it below.
2460 Exp->setArg(i, 0);
2461 }
Steve Naroffab972d32007-11-04 22:37:50 +00002462 // Generate the funky cast.
2463 CastExpr *cast;
2464 llvm::SmallVector<QualType, 8> ArgTypes;
2465 QualType returnType;
2466
2467 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002468 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2469 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2470 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002471 ArgTypes.push_back(Context->getObjCIdType());
2472 ArgTypes.push_back(Context->getObjCSelType());
2473 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002474 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002475 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002476 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2477 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002478 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002479 ArgTypes.push_back(t);
2480 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002481 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2482 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002483 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002484 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002485 }
2486 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002487 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002488
2489 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002490 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2491 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002492
2493 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2494 // If we don't do this cast, we get the following bizarre warning/note:
2495 // xx.m:13: warning: function called through a non-compatible type
2496 // xx.m:13: note: if this code is reached, the program will abort
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002497 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Steve Naroffab972d32007-11-04 22:37:50 +00002498 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002499
Steve Naroffab972d32007-11-04 22:37:50 +00002500 // Now do the "normal" pointer to function cast.
2501 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002502 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002503 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002504 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002505 castType = Context->getPointerType(castType);
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002506 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002507
2508 // Don't forget the parens to enforce the proper binding.
2509 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2510
2511 const FunctionType *FT = msgSendType->getAsFunctionType();
2512 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2513 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002514 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002515 if (MsgSendStretFlavor) {
2516 // We have the method which returns a struct/union. Must also generate
2517 // call to objc_msgSend_stret and hang both varieties on a conditional
2518 // expression which dictate which one to envoke depending on size of
2519 // method's return type.
2520
2521 // Create a reference to the objc_msgSend_stret() declaration.
2522 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2523 SourceLocation());
2524 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002525 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002526 SourceLocation());
2527 // Now do the "normal" pointer to function cast.
2528 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002529 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002530 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002531 castType = Context->getPointerType(castType);
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002532 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002533
2534 // Don't forget the parens to enforce the proper binding.
2535 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2536
2537 FT = msgSendType->getAsFunctionType();
2538 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2539 FT->getResultType(), SourceLocation());
2540
2541 // Build sizeof(returnType)
2542 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2543 returnType, Context->getSizeType(),
2544 SourceLocation(), SourceLocation());
2545 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2546 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2547 // For X86 it is more complicated and some kind of target specific routine
2548 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002549 unsigned IntSize =
2550 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002551 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2552 Context->IntTy,
2553 SourceLocation());
2554 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2555 BinaryOperator::LE,
2556 Context->IntTy,
2557 SourceLocation());
2558 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2559 ConditionalOperator *CondExpr =
2560 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002561 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002562 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002563 return ReplacingStmt;
2564}
2565
Steve Naroffb29b4272008-04-14 22:03:09 +00002566Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002567 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002568 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002569 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002570
Chris Lattnere64b7772007-10-24 16:57:36 +00002571 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002572 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002573}
2574
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002575/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2576/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002577Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002578 if (!GetProtocolFunctionDecl)
2579 SynthGetProtocolFunctionDecl();
2580 // Create a call to objc_getProtocol("ProtocolName").
2581 llvm::SmallVector<Expr*, 8> ProtoExprs;
2582 QualType argType = Context->getPointerType(Context->CharTy);
2583 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2584 strlen(Exp->getProtocol()->getName()),
2585 false, argType, SourceLocation(),
2586 SourceLocation()));
2587 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2588 &ProtoExprs[0],
2589 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002590 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002591 delete Exp;
2592 return ProtoExp;
2593
2594}
2595
Steve Naroffbaf58c32008-05-31 14:15:04 +00002596bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2597 const char *endBuf) {
2598 while (startBuf < endBuf) {
2599 if (*startBuf == '#') {
2600 // Skip whitespace.
2601 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2602 ;
2603 if (!strncmp(startBuf, "if", strlen("if")) ||
2604 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2605 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2606 !strncmp(startBuf, "define", strlen("define")) ||
2607 !strncmp(startBuf, "undef", strlen("undef")) ||
2608 !strncmp(startBuf, "else", strlen("else")) ||
2609 !strncmp(startBuf, "elif", strlen("elif")) ||
2610 !strncmp(startBuf, "endif", strlen("endif")) ||
2611 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2612 !strncmp(startBuf, "include", strlen("include")) ||
2613 !strncmp(startBuf, "import", strlen("import")) ||
2614 !strncmp(startBuf, "include_next", strlen("include_next")))
2615 return true;
2616 }
2617 startBuf++;
2618 }
2619 return false;
2620}
2621
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002622/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002623/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002624void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002625 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002626 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2627 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002628 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002629 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002630 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002631 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002632 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002633 SourceLocation LocStart = CDecl->getLocStart();
2634 SourceLocation LocEnd = CDecl->getLocEnd();
2635
2636 const char *startBuf = SM->getCharacterData(LocStart);
2637 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002638
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002639 // If no ivars and no root or if its root, directly or indirectly,
2640 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002641 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2642 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002643 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002644 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002645 return;
2646 }
2647
2648 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002649 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002650 Result += "\nstruct ";
2651 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002652 if (LangOpts.Microsoft)
2653 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002654
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002655 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002656 const char *cursor = strchr(startBuf, '{');
2657 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002658 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002659 // If the buffer contains preprocessor directives, we do more fine-grained
2660 // rewrites. This is intended to fix code that looks like (which occurs in
2661 // NSURL.h, for example):
2662 //
2663 // #ifdef XYZ
2664 // @interface Foo : NSObject
2665 // #else
2666 // @interface FooBar : NSObject
2667 // #endif
2668 // {
2669 // int i;
2670 // }
2671 // @end
2672 //
2673 // This clause is segregated to avoid breaking the common case.
2674 if (BufferContainsPPDirectives(startBuf, cursor)) {
2675 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2676 CDecl->getClassLoc();
2677 const char *endHeader = SM->getCharacterData(L);
2678 endHeader += Lexer::MeasureTokenLength(L, *SM);
2679
Chris Lattner3db6cae2008-07-21 18:19:38 +00002680 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002681 // advance to the end of the referenced protocols.
2682 while (endHeader < cursor && *endHeader != '>') endHeader++;
2683 endHeader++;
2684 }
2685 // rewrite the original header
2686 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2687 } else {
2688 // rewrite the original header *without* disturbing the '{'
2689 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2690 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002691 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002692 Result = "\n struct ";
2693 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002694 Result += "_IMPL ";
2695 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002696 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002697
2698 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002699 SourceLocation OnePastCurly =
2700 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2701 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002702 }
2703 cursor++; // past '{'
2704
2705 // Now comment out any visibility specifiers.
2706 while (cursor < endBuf) {
2707 if (*cursor == '@') {
2708 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002709 // Skip whitespace.
2710 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2711 /*scan*/;
2712
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002713 // FIXME: presence of @public, etc. inside comment results in
2714 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002715 if (!strncmp(cursor, "public", strlen("public")) ||
2716 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002717 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002718 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002719 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002720 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002721 // FIXME: If there are cases where '<' is used in ivar declaration part
2722 // of user code, then scan the ivar list and use needToScanForQualifiers
2723 // for type checking.
2724 else if (*cursor == '<') {
2725 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002726 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002727 cursor = strchr(cursor, '>');
2728 cursor++;
2729 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002730 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002731 }
Steve Narofffea763e82007-11-14 19:25:57 +00002732 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002733 }
Steve Narofffea763e82007-11-14 19:25:57 +00002734 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002735 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002736 } else { // we don't have any instance variables - insert super struct.
2737 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2738 Result += " {\n struct ";
2739 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002740 Result += "_IMPL ";
2741 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002742 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002743 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002744 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002745 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002746 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002747 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002748}
2749
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002750// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002751/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002752void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002753 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002754 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002755 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002756 const char *ClassName,
2757 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002758 if (MethodBegin == MethodEnd) return;
2759
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002760 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002761 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002762 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002763 SEL _cmd;
2764 char *method_types;
2765 void *_imp;
2766 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002767 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002768 Result += "\nstruct _objc_method {\n";
2769 Result += "\tSEL _cmd;\n";
2770 Result += "\tchar *method_types;\n";
2771 Result += "\tvoid *_imp;\n";
2772 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002773
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002774 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002775 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002776
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002777 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002778
2779 /* struct {
2780 struct _objc_method_list *next_method;
2781 int method_count;
2782 struct _objc_method method_list[];
2783 }
2784 */
2785 Result += "\nstatic struct {\n";
2786 Result += "\tstruct _objc_method_list *next_method;\n";
2787 Result += "\tint method_count;\n";
2788 Result += "\tstruct _objc_method method_list[";
2789 Result += utostr(MethodEnd-MethodBegin);
2790 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002791 Result += prefix;
2792 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2793 Result += "_METHODS_";
2794 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002795 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002796 Result += IsInstanceMethod ? "inst" : "cls";
2797 Result += "_meth\")))= ";
2798 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002799
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002800 Result += "\t,{{(SEL)\"";
2801 Result += (*MethodBegin)->getSelector().getName().c_str();
2802 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002803 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002804 Result += "\", \"";
2805 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002806 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002807 Result += MethodInternalNames[*MethodBegin];
2808 Result += "}\n";
2809 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2810 Result += "\t ,{(SEL)\"";
2811 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002812 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002813 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002814 Result += "\", \"";
2815 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002816 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002817 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002818 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002819 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002820 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002821}
2822
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002823/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002824void RewriteObjC::
2825RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2826 const char *prefix,
2827 const char *ClassName,
2828 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002829 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002830 if (Protocols.empty()) return;
2831
2832 for (unsigned i = 0; i != Protocols.size(); i++) {
2833 ObjCProtocolDecl *PDecl = Protocols[i];
2834 // Output struct protocol_methods holder of method selector and type.
2835 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2836 /* struct protocol_methods {
2837 SEL _cmd;
2838 char *method_types;
2839 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002840 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002841 Result += "\nstruct protocol_methods {\n";
2842 Result += "\tSEL _cmd;\n";
2843 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002844 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002845
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002846 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002847 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002848 // Do not synthesize the protocol more than once.
2849 if (ObjCSynthesizedProtocols.count(PDecl))
2850 continue;
2851
2852 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2853 unsigned NumMethods = PDecl->getNumInstanceMethods();
2854 /* struct _objc_protocol_method_list {
2855 int protocol_method_count;
2856 struct protocol_methods protocols[];
2857 }
2858 */
2859 Result += "\nstatic struct {\n";
2860 Result += "\tint protocol_method_count;\n";
2861 Result += "\tstruct protocol_methods protocols[";
2862 Result += utostr(NumMethods);
2863 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2864 Result += PDecl->getName();
2865 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2866 "{\n\t" + utostr(NumMethods) + "\n";
2867
2868 // Output instance methods declared in this protocol.
2869 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2870 E = PDecl->instmeth_end(); I != E; ++I) {
2871 if (I == PDecl->instmeth_begin())
2872 Result += "\t ,{{(SEL)\"";
2873 else
2874 Result += "\t ,{(SEL)\"";
2875 Result += (*I)->getSelector().getName().c_str();
2876 std::string MethodTypeString;
2877 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2878 Result += "\", \"";
2879 Result += MethodTypeString;
2880 Result += "\"}\n";
2881 }
2882 Result += "\t }\n};\n";
2883 }
2884
2885 // Output class methods declared in this protocol.
2886 int NumMethods = PDecl->getNumClassMethods();
2887 if (NumMethods > 0) {
2888 /* struct _objc_protocol_method_list {
2889 int protocol_method_count;
2890 struct protocol_methods protocols[];
2891 }
2892 */
2893 Result += "\nstatic struct {\n";
2894 Result += "\tint protocol_method_count;\n";
2895 Result += "\tstruct protocol_methods protocols[";
2896 Result += utostr(NumMethods);
2897 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2898 Result += PDecl->getName();
2899 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2900 "{\n\t";
2901 Result += utostr(NumMethods);
2902 Result += "\n";
2903
2904 // Output instance methods declared in this protocol.
2905 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2906 E = PDecl->classmeth_end(); I != E; ++I) {
2907 if (I == PDecl->classmeth_begin())
2908 Result += "\t ,{{(SEL)\"";
2909 else
2910 Result += "\t ,{(SEL)\"";
2911 Result += (*I)->getSelector().getName().c_str();
2912 std::string MethodTypeString;
2913 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2914 Result += "\", \"";
2915 Result += MethodTypeString;
2916 Result += "\"}\n";
2917 }
2918 Result += "\t }\n};\n";
2919 }
2920
2921 // Output:
2922 /* struct _objc_protocol {
2923 // Objective-C 1.0 extensions
2924 struct _objc_protocol_extension *isa;
2925 char *protocol_name;
2926 struct _objc_protocol **protocol_list;
2927 struct _objc_protocol_method_list *instance_methods;
2928 struct _objc_protocol_method_list *class_methods;
2929 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002930 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002931 static bool objc_protocol = false;
2932 if (!objc_protocol) {
2933 Result += "\nstruct _objc_protocol {\n";
2934 Result += "\tstruct _objc_protocol_extension *isa;\n";
2935 Result += "\tchar *protocol_name;\n";
2936 Result += "\tstruct _objc_protocol **protocol_list;\n";
2937 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2938 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2939 Result += "};\n";
2940
2941 objc_protocol = true;
2942 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002943
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002944 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2945 Result += PDecl->getName();
2946 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2947 "{\n\t0, \"";
2948 Result += PDecl->getName();
2949 Result += "\", 0, ";
2950 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2951 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2952 Result += PDecl->getName();
2953 Result += ", ";
2954 }
2955 else
2956 Result += "0, ";
2957 if (PDecl->getNumClassMethods() > 0) {
2958 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2959 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002960 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002961 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002962 else
2963 Result += "0\n";
2964 Result += "};\n";
2965
2966 // Mark this protocol as having been generated.
2967 if (!ObjCSynthesizedProtocols.insert(PDecl))
2968 assert(false && "protocol already synthesized");
2969 }
2970 // Output the top lovel protocol meta-data for the class.
2971 /* struct _objc_protocol_list {
2972 struct _objc_protocol_list *next;
2973 int protocol_count;
2974 struct _objc_protocol *class_protocols[];
2975 }
2976 */
2977 Result += "\nstatic struct {\n";
2978 Result += "\tstruct _objc_protocol_list *next;\n";
2979 Result += "\tint protocol_count;\n";
2980 Result += "\tstruct _objc_protocol *class_protocols[";
2981 Result += utostr(Protocols.size());
2982 Result += "];\n} _OBJC_";
2983 Result += prefix;
2984 Result += "_PROTOCOLS_";
2985 Result += ClassName;
2986 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2987 "{\n\t0, ";
2988 Result += utostr(Protocols.size());
2989 Result += "\n";
2990
2991 Result += "\t,{&_OBJC_PROTOCOL_";
2992 Result += Protocols[0]->getName();
2993 Result += " \n";
2994
2995 for (unsigned i = 1; i != Protocols.size(); i++) {
2996 Result += "\t ,&_OBJC_PROTOCOL_";
2997 Result += Protocols[i]->getName();
2998 Result += "\n";
2999 }
3000 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003001}
3002
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003003/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003004/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003005void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003006 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003007 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003008 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003009 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003010 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3011 CDecl = CDecl->getNextClassCategory())
3012 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3013 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003014
Chris Lattnereb44eee2007-12-23 01:40:15 +00003015 std::string FullCategoryName = ClassDecl->getName();
3016 FullCategoryName += '_';
3017 FullCategoryName += IDecl->getName();
3018
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003019 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003020 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003021 true, "CATEGORY_", FullCategoryName.c_str(),
3022 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003023
3024 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003025 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003026 false, "CATEGORY_", FullCategoryName.c_str(),
3027 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003028
3029 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003030 // Null CDecl is case of a category implementation with no category interface
3031 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003032 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003033 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003034
3035 /* struct _objc_category {
3036 char *category_name;
3037 char *class_name;
3038 struct _objc_method_list *instance_methods;
3039 struct _objc_method_list *class_methods;
3040 struct _objc_protocol_list *protocols;
3041 // Objective-C 1.0 extensions
3042 uint32_t size; // sizeof (struct _objc_category)
3043 struct _objc_property_list *instance_properties; // category's own
3044 // @property decl.
3045 };
3046 */
3047
3048 static bool objc_category = false;
3049 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003050 Result += "\nstruct _objc_category {\n";
3051 Result += "\tchar *category_name;\n";
3052 Result += "\tchar *class_name;\n";
3053 Result += "\tstruct _objc_method_list *instance_methods;\n";
3054 Result += "\tstruct _objc_method_list *class_methods;\n";
3055 Result += "\tstruct _objc_protocol_list *protocols;\n";
3056 Result += "\tunsigned int size;\n";
3057 Result += "\tstruct _objc_property_list *instance_properties;\n";
3058 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003059 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003060 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003061 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3062 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003063 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003064 Result += IDecl->getName();
3065 Result += "\"\n\t, \"";
3066 Result += ClassDecl->getName();
3067 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003068
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003069 if (IDecl->getNumInstanceMethods() > 0) {
3070 Result += "\t, (struct _objc_method_list *)"
3071 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3072 Result += FullCategoryName;
3073 Result += "\n";
3074 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003075 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003076 Result += "\t, 0\n";
3077 if (IDecl->getNumClassMethods() > 0) {
3078 Result += "\t, (struct _objc_method_list *)"
3079 "&_OBJC_CATEGORY_CLASS_METHODS_";
3080 Result += FullCategoryName;
3081 Result += "\n";
3082 }
3083 else
3084 Result += "\t, 0\n";
3085
Chris Lattner780f3292008-07-21 21:32:27 +00003086 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003087 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3088 Result += FullCategoryName;
3089 Result += "\n";
3090 }
3091 else
3092 Result += "\t, 0\n";
3093 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003094}
3095
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003096/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3097/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003098void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003099 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003100 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003101 if (ivar->isBitField()) {
3102 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3103 // place all bitfields at offset 0.
3104 Result += "0";
3105 } else {
3106 Result += "__OFFSETOFIVAR__(struct ";
3107 Result += IDecl->getName();
3108 if (LangOpts.Microsoft)
3109 Result += "_IMPL";
3110 Result += ", ";
3111 Result += ivar->getName();
3112 Result += ")";
3113 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003114}
3115
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003116//===----------------------------------------------------------------------===//
3117// Meta Data Emission
3118//===----------------------------------------------------------------------===//
3119
Steve Naroffb29b4272008-04-14 22:03:09 +00003120void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003121 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003122 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003123
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003124 // Explictly declared @interface's are already synthesized.
3125 if (CDecl->ImplicitInterfaceDecl()) {
3126 // FIXME: Implementation of a class with no @interface (legacy) doese not
3127 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003128 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003129 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003130
Chris Lattnerbe6df082007-12-12 07:56:42 +00003131 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003132 unsigned NumIvars = !IDecl->ivar_empty()
3133 ? IDecl->ivar_size()
3134 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003135 if (NumIvars > 0) {
3136 static bool objc_ivar = false;
3137 if (!objc_ivar) {
3138 /* struct _objc_ivar {
3139 char *ivar_name;
3140 char *ivar_type;
3141 int ivar_offset;
3142 };
3143 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003144 Result += "\nstruct _objc_ivar {\n";
3145 Result += "\tchar *ivar_name;\n";
3146 Result += "\tchar *ivar_type;\n";
3147 Result += "\tint ivar_offset;\n";
3148 Result += "};\n";
3149
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003150 objc_ivar = true;
3151 }
3152
Steve Naroff946a6932008-03-11 00:12:29 +00003153 /* struct {
3154 int ivar_count;
3155 struct _objc_ivar ivar_list[nIvars];
3156 };
3157 */
3158 Result += "\nstatic struct {\n";
3159 Result += "\tint ivar_count;\n";
3160 Result += "\tstruct _objc_ivar ivar_list[";
3161 Result += utostr(NumIvars);
3162 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003163 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003164 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003165 "{\n\t";
3166 Result += utostr(NumIvars);
3167 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003168
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003169 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003170 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003171 IVI = IDecl->ivar_begin();
3172 IVE = IDecl->ivar_end();
3173 } else {
3174 IVI = CDecl->ivar_begin();
3175 IVE = CDecl->ivar_end();
3176 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003177 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003178 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003179 Result += "\", \"";
3180 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003181 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003182 Result += StrEncoding;
3183 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003184 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003185 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003186 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003187 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003188 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003189 Result += "\", \"";
3190 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003191 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003192 Result += StrEncoding;
3193 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003194 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003195 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003196 }
3197
3198 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003199 }
3200
3201 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003202 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003203 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003204
3205 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003206 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003207 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003208
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003209 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003210 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003211 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003212
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003213
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003214 // Declaration of class/meta-class metadata
3215 /* struct _objc_class {
3216 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003217 const char *super_class_name;
3218 char *name;
3219 long version;
3220 long info;
3221 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003222 struct _objc_ivar_list *ivars;
3223 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003224 struct objc_cache *cache;
3225 struct objc_protocol_list *protocols;
3226 const char *ivar_layout;
3227 struct _objc_class_ext *ext;
3228 };
3229 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003230 static bool objc_class = false;
3231 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003232 Result += "\nstruct _objc_class {\n";
3233 Result += "\tstruct _objc_class *isa;\n";
3234 Result += "\tconst char *super_class_name;\n";
3235 Result += "\tchar *name;\n";
3236 Result += "\tlong version;\n";
3237 Result += "\tlong info;\n";
3238 Result += "\tlong instance_size;\n";
3239 Result += "\tstruct _objc_ivar_list *ivars;\n";
3240 Result += "\tstruct _objc_method_list *methods;\n";
3241 Result += "\tstruct objc_cache *cache;\n";
3242 Result += "\tstruct _objc_protocol_list *protocols;\n";
3243 Result += "\tconst char *ivar_layout;\n";
3244 Result += "\tstruct _objc_class_ext *ext;\n";
3245 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003246 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003247 }
3248
3249 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003250 ObjCInterfaceDecl *RootClass = 0;
3251 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003252 while (SuperClass) {
3253 RootClass = SuperClass;
3254 SuperClass = SuperClass->getSuperClass();
3255 }
3256 SuperClass = CDecl->getSuperClass();
3257
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003258 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3259 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003260 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003261 "{\n\t(struct _objc_class *)\"";
3262 Result += (RootClass ? RootClass->getName() : CDecl->getName());
3263 Result += "\"";
3264
3265 if (SuperClass) {
3266 Result += ", \"";
3267 Result += SuperClass->getName();
3268 Result += "\", \"";
3269 Result += CDecl->getName();
3270 Result += "\"";
3271 }
3272 else {
3273 Result += ", 0, \"";
3274 Result += CDecl->getName();
3275 Result += "\"";
3276 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003277 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003278 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003279 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003280 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003281 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00003282 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003283 Result += "\n";
3284 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003285 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003286 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003287 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003288 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003289 Result += CDecl->getName();
3290 Result += ",0,0\n";
3291 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003292 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003293 Result += "\t,0,0,0,0\n";
3294 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003295
3296 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003297 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3298 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003299 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003300 "{\n\t&_OBJC_METACLASS_";
3301 Result += CDecl->getName();
3302 if (SuperClass) {
3303 Result += ", \"";
3304 Result += SuperClass->getName();
3305 Result += "\", \"";
3306 Result += CDecl->getName();
3307 Result += "\"";
3308 }
3309 else {
3310 Result += ", 0, \"";
3311 Result += CDecl->getName();
3312 Result += "\"";
3313 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003314 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003315 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003316 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003317 Result += ",0";
3318 else {
3319 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003320 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003321 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003322 if (LangOpts.Microsoft)
3323 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003324 Result += ")";
3325 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003326 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003327 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003328 Result += CDecl->getName();
3329 Result += "\n\t";
3330 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003331 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003332 Result += ",0";
3333 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003334 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003335 Result += CDecl->getName();
3336 Result += ", 0\n\t";
3337 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003338 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003339 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003340 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003341 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003342 Result += CDecl->getName();
3343 Result += ", 0,0\n";
3344 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003345 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003346 Result += ",0,0,0\n";
3347 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003348}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003349
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003350/// RewriteImplementations - This routine rewrites all method implementations
3351/// and emits meta-data.
3352
Steve Naroffb29b4272008-04-14 22:03:09 +00003353void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003354 int ClsDefCount = ClassImplementation.size();
3355 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003356
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003357 if (ClsDefCount == 0 && CatDefCount == 0)
3358 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003359 // Rewrite implemented methods
3360 for (int i = 0; i < ClsDefCount; i++)
3361 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003362
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003363 for (int i = 0; i < CatDefCount; i++)
3364 RewriteImplementationDecl(CategoryImplementation[i]);
3365
Steve Naroff5df5b762008-05-07 21:23:49 +00003366 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003367 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003368 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003369 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003370 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003371
3372 // For each implemented category, write out all its meta data.
3373 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003374 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003375
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003376 // Write objc_symtab metadata
3377 /*
3378 struct _objc_symtab
3379 {
3380 long sel_ref_cnt;
3381 SEL *refs;
3382 short cls_def_cnt;
3383 short cat_def_cnt;
3384 void *defs[cls_def_cnt + cat_def_cnt];
3385 };
3386 */
3387
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003388 Result += "\nstruct _objc_symtab {\n";
3389 Result += "\tlong sel_ref_cnt;\n";
3390 Result += "\tSEL *refs;\n";
3391 Result += "\tshort cls_def_cnt;\n";
3392 Result += "\tshort cat_def_cnt;\n";
3393 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3394 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003395
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003396 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003397 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003398 Result += "\t0, 0, " + utostr(ClsDefCount)
3399 + ", " + utostr(CatDefCount) + "\n";
3400 for (int i = 0; i < ClsDefCount; i++) {
3401 Result += "\t,&_OBJC_CLASS_";
3402 Result += ClassImplementation[i]->getName();
3403 Result += "\n";
3404 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003405
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003406 for (int i = 0; i < CatDefCount; i++) {
3407 Result += "\t,&_OBJC_CATEGORY_";
3408 Result += CategoryImplementation[i]->getClassInterface()->getName();
3409 Result += "_";
3410 Result += CategoryImplementation[i]->getName();
3411 Result += "\n";
3412 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003413
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003414 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003415
3416 // Write objc_module metadata
3417
3418 /*
3419 struct _objc_module {
3420 long version;
3421 long size;
3422 const char *name;
3423 struct _objc_symtab *symtab;
3424 }
3425 */
3426
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003427 Result += "\nstruct _objc_module {\n";
3428 Result += "\tlong version;\n";
3429 Result += "\tlong size;\n";
3430 Result += "\tconst char *name;\n";
3431 Result += "\tstruct _objc_symtab *symtab;\n";
3432 Result += "};\n\n";
3433 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003434 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003435 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3436 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003437 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003438
3439 if (LangOpts.Microsoft) {
3440 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003441 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003442 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3443 Result += "&_OBJC_MODULES;\n";
3444 Result += "#pragma data_seg(pop)\n\n";
3445 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003446}
Chris Lattner311ff022007-10-16 22:36:42 +00003447
Steve Naroff54055232008-10-27 17:20:55 +00003448std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3449 const char *funcName,
3450 std::string Tag) {
3451 const FunctionType *AFT = CE->getFunctionType();
3452 QualType RT = AFT->getResultType();
3453 std::string StructRef = "struct " + Tag;
3454 std::string S = "static " + RT.getAsString() + " __" +
3455 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003456
Steve Naroff54055232008-10-27 17:20:55 +00003457 BlockDecl *BD = CE->getBlockDecl();
3458
3459 if (isa<FunctionTypeNoProto>(AFT)) {
3460 S += "()";
3461 } else if (BD->param_empty()) {
3462 S += "(" + StructRef + " *__cself)";
3463 } else {
3464 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3465 assert(FT && "SynthesizeBlockFunc: No function proto");
3466 S += '(';
3467 // first add the implicit argument.
3468 S += StructRef + " *__cself, ";
3469 std::string ParamStr;
3470 for (BlockDecl::param_iterator AI = BD->param_begin(),
3471 E = BD->param_end(); AI != E; ++AI) {
3472 if (AI != BD->param_begin()) S += ", ";
3473 ParamStr = (*AI)->getName();
3474 (*AI)->getType().getAsStringInternal(ParamStr);
3475 S += ParamStr;
3476 }
3477 if (FT->isVariadic()) {
3478 if (!BD->param_empty()) S += ", ";
3479 S += "...";
3480 }
3481 S += ')';
3482 }
3483 S += " {\n";
3484
3485 // Create local declarations to avoid rewriting all closure decl ref exprs.
3486 // First, emit a declaration for all "by ref" decls.
3487 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3488 E = BlockByRefDecls.end(); I != E; ++I) {
3489 S += " ";
3490 std::string Name = (*I)->getName();
3491 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
3492 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
3493 }
3494 // Next, emit a declaration for all "by copy" declarations.
3495 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3496 E = BlockByCopyDecls.end(); I != E; ++I) {
3497 S += " ";
3498 std::string Name = (*I)->getName();
3499 // Handle nested closure invocation. For example:
3500 //
3501 // void (^myImportedClosure)(void);
3502 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3503 //
3504 // void (^anotherClosure)(void);
3505 // anotherClosure = ^(void) {
3506 // myImportedClosure(); // import and invoke the closure
3507 // };
3508 //
3509 if (isBlockPointerType((*I)->getType()))
3510 S += "struct __block_impl *";
3511 else
3512 (*I)->getType().getAsStringInternal(Name);
3513 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
3514 }
3515 std::string RewrittenStr = RewrittenBlockExprs[CE];
3516 const char *cstr = RewrittenStr.c_str();
3517 while (*cstr++ != '{') ;
3518 S += cstr;
3519 S += "\n";
3520 return S;
3521}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003522
Steve Naroff54055232008-10-27 17:20:55 +00003523std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3524 const char *funcName,
3525 std::string Tag) {
3526 std::string StructRef = "struct " + Tag;
3527 std::string S = "static void __";
3528
3529 S += funcName;
3530 S += "_block_copy_" + utostr(i);
3531 S += "(" + StructRef;
3532 S += "*dst, " + StructRef;
3533 S += "*src) {";
3534 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3535 E = ImportedBlockDecls.end(); I != E; ++I) {
3536 S += "_Block_copy_assign(&dst->";
3537 S += (*I)->getName();
3538 S += ", src->";
3539 S += (*I)->getName();
3540 S += ");}";
3541 }
3542 S += "\nstatic void __";
3543 S += funcName;
3544 S += "_block_dispose_" + utostr(i);
3545 S += "(" + StructRef;
3546 S += "*src) {";
3547 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3548 E = ImportedBlockDecls.end(); I != E; ++I) {
3549 S += "_Block_destroy(src->";
3550 S += (*I)->getName();
3551 S += ");";
3552 }
3553 S += "}\n";
3554 return S;
3555}
3556
3557std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3558 bool hasCopyDisposeHelpers) {
3559 std::string S = "struct " + Tag;
3560 std::string Constructor = " " + Tag;
3561
3562 S += " {\n struct __block_impl impl;\n";
3563
3564 if (hasCopyDisposeHelpers)
3565 S += " void *copy;\n void *dispose;\n";
3566
3567 Constructor += "(void *fp";
3568
3569 if (hasCopyDisposeHelpers)
3570 Constructor += ", void *copyHelp, void *disposeHelp";
3571
3572 if (BlockDeclRefs.size()) {
3573 // Output all "by copy" declarations.
3574 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3575 E = BlockByCopyDecls.end(); I != E; ++I) {
3576 S += " ";
3577 std::string FieldName = (*I)->getName();
3578 std::string ArgName = "_" + FieldName;
3579 // Handle nested closure invocation. For example:
3580 //
3581 // void (^myImportedBlock)(void);
3582 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3583 //
3584 // void (^anotherBlock)(void);
3585 // anotherBlock = ^(void) {
3586 // myImportedBlock(); // import and invoke the closure
3587 // };
3588 //
3589 if (isBlockPointerType((*I)->getType())) {
3590 S += "struct __block_impl *";
3591 Constructor += ", void *" + ArgName;
3592 } else {
3593 (*I)->getType().getAsStringInternal(FieldName);
3594 (*I)->getType().getAsStringInternal(ArgName);
3595 Constructor += ", " + ArgName;
3596 }
3597 S += FieldName + ";\n";
3598 }
3599 // Output all "by ref" declarations.
3600 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3601 E = BlockByRefDecls.end(); I != E; ++I) {
3602 S += " ";
3603 std::string FieldName = (*I)->getName();
3604 std::string ArgName = "_" + FieldName;
3605 // Handle nested closure invocation. For example:
3606 //
3607 // void (^myImportedBlock)(void);
3608 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3609 //
3610 // void (^anotherBlock)(void);
3611 // anotherBlock = ^(void) {
3612 // myImportedBlock(); // import and invoke the closure
3613 // };
3614 //
3615 if (isBlockPointerType((*I)->getType())) {
3616 S += "struct __block_impl *";
3617 Constructor += ", void *" + ArgName;
3618 } else {
3619 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3620 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3621 Constructor += ", " + ArgName;
3622 }
3623 S += FieldName + "; // by ref\n";
3624 }
3625 // Finish writing the constructor.
3626 // FIXME: handle NSConcreteGlobalBlock.
3627 Constructor += ", int flags=0) {\n";
3628 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3629 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3630
3631 if (hasCopyDisposeHelpers)
3632 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3633
3634 // Initialize all "by copy" arguments.
3635 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3636 E = BlockByCopyDecls.end(); I != E; ++I) {
3637 std::string Name = (*I)->getName();
3638 Constructor += " ";
3639 if (isBlockPointerType((*I)->getType()))
3640 Constructor += Name + " = (struct __block_impl *)_";
3641 else
3642 Constructor += Name + " = _";
3643 Constructor += Name + ";\n";
3644 }
3645 // Initialize all "by ref" arguments.
3646 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3647 E = BlockByRefDecls.end(); I != E; ++I) {
3648 std::string Name = (*I)->getName();
3649 Constructor += " ";
3650 if (isBlockPointerType((*I)->getType()))
3651 Constructor += Name + " = (struct __block_impl *)_";
3652 else
3653 Constructor += Name + " = _";
3654 Constructor += Name + ";\n";
3655 }
3656 } else {
3657 // Finish writing the constructor.
3658 // FIXME: handle NSConcreteGlobalBlock.
3659 Constructor += ", int flags=0) {\n";
3660 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3661 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3662 if (hasCopyDisposeHelpers)
3663 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3664 }
3665 Constructor += " ";
3666 Constructor += "}\n";
3667 S += Constructor;
3668 S += "};\n";
3669 return S;
3670}
3671
3672void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3673 const char *FunName) {
3674 // Insert closures that were part of the function.
3675 for (unsigned i = 0; i < Blocks.size(); i++) {
3676
3677 CollectBlockDeclRefInfo(Blocks[i]);
3678
3679 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3680
3681 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3682 ImportedBlockDecls.size() > 0);
3683
3684 InsertText(FunLocStart, CI.c_str(), CI.size());
3685
3686 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3687
3688 InsertText(FunLocStart, CF.c_str(), CF.size());
3689
3690 if (ImportedBlockDecls.size()) {
3691 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3692 InsertText(FunLocStart, HF.c_str(), HF.size());
3693 }
3694
3695 BlockDeclRefs.clear();
3696 BlockByRefDecls.clear();
3697 BlockByCopyDecls.clear();
3698 BlockCallExprs.clear();
3699 ImportedBlockDecls.clear();
3700 }
3701 Blocks.clear();
3702 RewrittenBlockExprs.clear();
3703}
3704
3705void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3706 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3707 const char *FuncName = FD->getName();
3708
3709 SynthesizeBlockLiterals(FunLocStart, FuncName);
3710}
3711
3712void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3713 SourceLocation FunLocStart = MD->getLocStart();
3714 std::string FuncName = std::string(MD->getSelector().getName());
3715 // Convert colons to underscores.
3716 std::string::size_type loc = 0;
3717 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3718 FuncName.replace(loc, 1, "_");
3719
3720 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3721}
3722
3723void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3724 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3725 CI != E; ++CI)
3726 if (*CI) {
3727 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3728 GetBlockDeclRefExprs(CBE->getBody());
3729 else
3730 GetBlockDeclRefExprs(*CI);
3731 }
3732 // Handle specific things.
3733 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3734 // FIXME: Handle enums.
3735 if (!isa<FunctionDecl>(CDRE->getDecl()))
3736 BlockDeclRefs.push_back(CDRE);
3737 return;
3738}
3739
3740void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3741 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3742 CI != E; ++CI)
3743 if (*CI) {
3744 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3745 GetBlockCallExprs(CBE->getBody());
3746 else
3747 GetBlockCallExprs(*CI);
3748 }
3749
3750 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3751 if (CE->getCallee()->getType()->isBlockPointerType()) {
3752 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3753 }
3754 }
3755 return;
3756}
3757
3758std::string RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
3759 // Navigate to relevant type information.
3760 const char *closureName = 0;
3761 const BlockPointerType *CPT = 0;
3762
3763 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
3764 closureName = DRE->getDecl()->getName();
3765 CPT = DRE->getType()->getAsBlockPointerType();
3766 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
3767 closureName = CDRE->getDecl()->getName();
3768 CPT = CDRE->getType()->getAsBlockPointerType();
3769 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
3770 closureName = MExpr->getMemberDecl()->getName();
3771 CPT = MExpr->getType()->getAsBlockPointerType();
3772 } else {
3773 assert(1 && "RewriteBlockClass: Bad type");
3774 }
3775 assert(CPT && "RewriteBlockClass: Bad type");
3776 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3777 assert(FT && "RewriteBlockClass: Bad type");
3778 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3779 // FTP will be null for closures that don't take arguments.
3780
3781 // Build a closure call - start with a paren expr to enforce precedence.
3782 std::string BlockCall = "(";
3783
3784 // Synthesize the cast.
3785 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
3786 BlockCall += "(struct __block_impl *";
3787 if (FTP) {
3788 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3789 E = FTP->arg_type_end(); I && (I != E); ++I)
3790 BlockCall += ", " + (*I).getAsString();
3791 }
3792 BlockCall += "))"; // close the argument list and paren expression.
3793
3794 // Invoke the closure. We need to cast it since the declaration type is
3795 // bogus (it's a function pointer type)
3796 BlockCall += "((struct __block_impl *)";
3797 std::string closureExprBufStr;
3798 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
3799 Exp->getCallee()->printPretty(closureExprBuf);
3800 BlockCall += closureExprBuf.str();
3801 BlockCall += ")->FuncPtr)";
3802
3803 // Add the arguments.
3804 BlockCall += "((struct __block_impl *)";
3805 BlockCall += closureExprBuf.str();
3806 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3807 E = Exp->arg_end(); I != E; ++I) {
3808 std::string syncExprBufS;
3809 llvm::raw_string_ostream Buf(syncExprBufS);
3810 (*I)->printPretty(Buf);
3811 BlockCall += ", " + Buf.str();
3812 }
3813 return BlockCall;
3814}
3815
3816void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
3817 std::string BlockCall = SynthesizeBlockCall(Exp);
3818
3819 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
3820 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
3821
3822 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
3823 BlockCall.c_str(), BlockCall.size());
3824}
3825
3826void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3827 // FIXME: Add more elaborate code generation required by the ABI.
3828 InsertText(BDRE->getLocStart(), "*", 1);
3829}
3830
3831void RewriteObjC::RewriteCastExpr(CastExpr *CE) {
3832 SourceLocation LocStart = CE->getLocStart();
3833 SourceLocation LocEnd = CE->getLocEnd();
3834
3835 const char *startBuf = SM->getCharacterData(LocStart);
3836 const char *endBuf = SM->getCharacterData(LocEnd);
3837
3838 // advance the location to startArgList.
3839 const char *argPtr = startBuf;
3840
3841 while (*argPtr++ && (argPtr < endBuf)) {
3842 switch (*argPtr) {
3843 case '^':
3844 // Replace the '^' with '*'.
3845 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3846 ReplaceText(LocStart, 1, "*", 1);
3847 break;
3848 }
3849 }
3850 return;
3851}
3852
3853void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3854 SourceLocation DeclLoc = FD->getLocation();
3855 unsigned parenCount = 0;
3856
3857 // We have 1 or more arguments that have closure pointers.
3858 const char *startBuf = SM->getCharacterData(DeclLoc);
3859 const char *startArgList = strchr(startBuf, '(');
3860
3861 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3862
3863 parenCount++;
3864 // advance the location to startArgList.
3865 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3866 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3867
3868 const char *argPtr = startArgList;
3869
3870 while (*argPtr++ && parenCount) {
3871 switch (*argPtr) {
3872 case '^':
3873 // Replace the '^' with '*'.
3874 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3875 ReplaceText(DeclLoc, 1, "*", 1);
3876 break;
3877 case '(':
3878 parenCount++;
3879 break;
3880 case ')':
3881 parenCount--;
3882 break;
3883 }
3884 }
3885 return;
3886}
3887
3888bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3889 const FunctionTypeProto *FTP;
3890 const PointerType *PT = QT->getAsPointerType();
3891 if (PT) {
3892 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3893 } else {
3894 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3895 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3896 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3897 }
3898 if (FTP) {
3899 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3900 E = FTP->arg_type_end(); I != E; ++I)
3901 if (isBlockPointerType(*I))
3902 return true;
3903 }
3904 return false;
3905}
3906
3907void RewriteObjC::GetExtentOfArgList(const char *Name,
3908 const char *&LParen, const char *&RParen) {
3909 const char *argPtr = strchr(Name, '(');
3910 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3911
3912 LParen = argPtr; // output the start.
3913 argPtr++; // skip past the left paren.
3914 unsigned parenCount = 1;
3915
3916 while (*argPtr && parenCount) {
3917 switch (*argPtr) {
3918 case '(': parenCount++; break;
3919 case ')': parenCount--; break;
3920 default: break;
3921 }
3922 if (parenCount) argPtr++;
3923 }
3924 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3925 RParen = argPtr; // output the end
3926}
3927
3928void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3929 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3930 RewriteBlockPointerFunctionArgs(FD);
3931 return;
3932 }
3933 // Handle Variables and Typedefs.
3934 SourceLocation DeclLoc = ND->getLocation();
3935 QualType DeclT;
3936 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3937 DeclT = VD->getType();
3938 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3939 DeclT = TDD->getUnderlyingType();
3940 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3941 DeclT = FD->getType();
3942 else
3943 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3944
3945 const char *startBuf = SM->getCharacterData(DeclLoc);
3946 const char *endBuf = startBuf;
3947 // scan backward (from the decl location) for the end of the previous decl.
3948 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3949 startBuf--;
3950
3951 // *startBuf != '^' if we are dealing with a pointer to function that
3952 // may take block argument types (which will be handled below).
3953 if (*startBuf == '^') {
3954 // Replace the '^' with '*', computing a negative offset.
3955 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3956 ReplaceText(DeclLoc, 1, "*", 1);
3957 }
3958 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3959 // Replace the '^' with '*' for arguments.
3960 DeclLoc = ND->getLocation();
3961 startBuf = SM->getCharacterData(DeclLoc);
3962 const char *argListBegin, *argListEnd;
3963 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3964 while (argListBegin < argListEnd) {
3965 if (*argListBegin == '^') {
3966 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3967 ReplaceText(CaretLoc, 1, "*", 1);
3968 }
3969 argListBegin++;
3970 }
3971 }
3972 return;
3973}
3974
3975void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3976 // Add initializers for any closure decl refs.
3977 GetBlockDeclRefExprs(Exp->getBody());
3978 if (BlockDeclRefs.size()) {
3979 // Unique all "by copy" declarations.
3980 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3981 if (!BlockDeclRefs[i]->isByRef())
3982 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3983 // Unique all "by ref" declarations.
3984 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3985 if (BlockDeclRefs[i]->isByRef()) {
3986 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3987 }
3988 // Find any imported blocks...they will need special attention.
3989 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3990 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
3991 GetBlockCallExprs(Blocks[i]);
3992 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3993 }
3994 }
3995}
3996
3997std::string RewriteObjC::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
3998 Blocks.push_back(Exp);
3999
4000 CollectBlockDeclRefInfo(Exp);
4001 std::string FuncName;
4002
4003 if (CurFunctionDef)
4004 FuncName = std::string(CurFunctionDef->getName());
4005 else if (CurMethodDef) {
4006 FuncName = std::string(CurMethodDef->getSelector().getName());
4007 // Convert colons to underscores.
4008 std::string::size_type loc = 0;
4009 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4010 FuncName.replace(loc, 1, "_");
4011 } else if (VD)
4012 FuncName = std::string(VD->getName());
4013
4014 std::string BlockNumber = utostr(Blocks.size()-1);
4015
4016 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4017 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4018
4019 std::string FunkTypeStr;
4020
4021 // Get a pointer to the function type so we can cast appropriately.
4022 Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr);
4023
4024 // Rewrite the closure block with a compound literal. The first cast is
4025 // to prevent warnings from the C compiler.
4026 std::string Init = "(" + FunkTypeStr;
4027
4028 Init += ")&" + Tag;
4029
4030 // Initialize the block function.
4031 Init += "((void*)" + Func;
4032
4033 if (ImportedBlockDecls.size()) {
4034 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
4035 Init += ",(void*)" + Buf;
4036 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
4037 Init += ",(void*)" + Buf;
4038 }
4039 // Add initializers for any closure decl refs.
4040 if (BlockDeclRefs.size()) {
4041 // Output all "by copy" declarations.
4042 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4043 E = BlockByCopyDecls.end(); I != E; ++I) {
4044 Init += ",";
4045 if (isObjCType((*I)->getType())) {
4046 Init += "[[";
4047 Init += (*I)->getName();
4048 Init += " retain] autorelease]";
4049 } else if (isBlockPointerType((*I)->getType())) {
4050 Init += "(void *)";
4051 Init += (*I)->getName();
4052 } else {
4053 Init += (*I)->getName();
4054 }
4055 }
4056 // Output all "by ref" declarations.
4057 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4058 E = BlockByRefDecls.end(); I != E; ++I) {
4059 Init += ",&";
4060 Init += (*I)->getName();
4061 }
4062 }
4063 Init += ")";
4064 BlockDeclRefs.clear();
4065 BlockByRefDecls.clear();
4066 BlockByCopyDecls.clear();
4067 ImportedBlockDecls.clear();
4068
4069 return Init;
4070}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004071