blob: f558d7d93097f1f8e10b090109c1964a1f726f04 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Steve Naroff0113c9d2008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattner77cd2a02007-10-11 00:43:27 +000038namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattner01c57482007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000046 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000051
Ted Kremeneka526c5c2008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000083 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +000099
Steve Naroff54055232008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
Steve Naroff15f081d2008-12-03 00:56:33 +0000107 // This maps a synthesized message expr back to the original property.
108 llvm::DenseMap<Stmt *, ObjCPropertyRefExpr *> PropMsgExprs;
109
Steve Naroff54055232008-10-27 17:20:55 +0000110 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000111 VarDecl *GlobalVarDecl;
112
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000113 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000114 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000115 virtual void Initialize(ASTContext &context);
116
117 virtual void InitializeTU(TranslationUnit &TU) {
118 TU.SetOwnsDecls(false);
119 Initialize(TU.getContext());
120 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000121
Chris Lattner8a12c272007-10-11 18:38:32 +0000122
Chris Lattnerf04da132007-10-24 17:06:59 +0000123 // Top Level Driver code.
124 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000125 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000126 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000127 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000128
129 ~RewriteObjC() {}
130
131 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000132
133 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000134 // If replacement succeeded or warning disabled return with no warning.
135 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000136 return;
137
Chris Lattner0a14eee2008-11-18 07:04:44 +0000138 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
139 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000140 }
141
Steve Naroffba92b2e2008-03-27 22:29:16 +0000142 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
143 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000144 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000145 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000146 SilenceRewriteMacroWarning)
147 return;
148
149 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
150 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000151
Chris Lattneraadaf782008-01-31 19:51:04 +0000152 void RemoveText(SourceLocation Loc, unsigned StrLen) {
153 // If removal succeeded or warning disabled return with no warning.
154 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
155 return;
156
157 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
158 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000159
Chris Lattneraadaf782008-01-31 19:51:04 +0000160 void ReplaceText(SourceLocation Start, unsigned OrigLength,
161 const char *NewStr, unsigned NewLength) {
162 // If removal succeeded or warning disabled return with no warning.
163 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
164 SilenceRewriteMacroWarning)
165 return;
166
167 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
168 }
169
Chris Lattnerf04da132007-10-24 17:06:59 +0000170 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000171 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000172 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000173 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000174 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000175 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
176 ObjCImplementationDecl *IMD,
177 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000178 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000179 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000180 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
181 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
182 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
183 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
184 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000185 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000186 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000187 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000188 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000189 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000190 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000191 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000192 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000193 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000194
Chris Lattnerf04da132007-10-24 17:06:59 +0000195 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000196 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000197 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000198 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff15f081d2008-12-03 00:56:33 +0000199 Stmt *RewritePropertyRefExpr(ObjCPropertyRefExpr *PropRefExpr);
200 Stmt *RewritePropertySetter(BinaryOperator *BinOp, ObjCPropertyRefExpr *PRE);
Steve Naroffb42f8412007-11-05 14:50:49 +0000201 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000202 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000203 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000204 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000205 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000206 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000207 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
208 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
209 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000210 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
211 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000212 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
213 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000214 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000215 Stmt *RewriteBreakStmt(BreakStmt *S);
216 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000217 void SynthCountByEnumWithState(std::string &buf);
218
Steve Naroff09b266e2007-10-30 23:14:51 +0000219 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000220 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000221 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000222 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000223 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000224 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000225 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000226 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000227 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000228 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000229
Chris Lattnerf04da132007-10-24 17:06:59 +0000230 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000232 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000233
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000234 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000235 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000236
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000237 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
238 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000239 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000240 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000241 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000242 const char *ClassName,
243 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000244
Chris Lattner780f3292008-07-21 21:32:27 +0000245 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
246 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000247 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000248 const char *ClassName,
249 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000250 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000251 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000252 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
253 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000254 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000255 void RewriteImplementations();
256 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000257
258 // Block rewriting.
259 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
260 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
261
262 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
263 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
264
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000265 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000266 void RewriteBlockCall(CallExpr *Exp);
267 void RewriteBlockPointerDecl(NamedDecl *VD);
268 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
269 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
270
271 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
272 const char *funcName, std::string Tag);
273 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
274 const char *funcName, std::string Tag);
275 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
276 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000277 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000278 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
279 const char *FunName);
280
281 void CollectBlockDeclRefInfo(BlockExpr *Exp);
282 void GetBlockCallExprs(Stmt *S);
283 void GetBlockDeclRefExprs(Stmt *S);
284
285 // We avoid calling Type::isBlockPointerType(), since it operates on the
286 // canonical type. We only care if the top-level type is a closure pointer.
287 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
288
289 // FIXME: This predicate seems like it would be useful to add to ASTContext.
290 bool isObjCType(QualType T) {
291 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
292 return false;
293
294 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
295
296 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
297 OCT == Context->getCanonicalType(Context->getObjCClassType()))
298 return true;
299
300 if (const PointerType *PT = OCT->getAsPointerType()) {
301 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
302 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
303 return true;
304 }
305 return false;
306 }
307 bool PointerTypeTakesAnyBlockArguments(QualType QT);
308 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000309 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000310
311 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000312 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000313 };
314}
315
Steve Naroff54055232008-10-27 17:20:55 +0000316void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
317 NamedDecl *D) {
318 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
319 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
320 E = fproto->arg_type_end(); I && (I != E); ++I)
321 if (isBlockPointerType(*I)) {
322 // All the args are checked/rewritten. Don't call twice!
323 RewriteBlockPointerDecl(D);
324 break;
325 }
326 }
327}
328
329void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
330 const PointerType *PT = funcType->getAsPointerType();
331 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
332 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
333}
334
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000335static bool IsHeaderFile(const std::string &Filename) {
336 std::string::size_type DotPos = Filename.rfind('.');
337
338 if (DotPos == std::string::npos) {
339 // no file extension
340 return false;
341 }
342
343 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
344 // C header: .h
345 // C++ header: .hh or .H;
346 return Ext == "h" || Ext == "hh" || Ext == "H";
347}
348
Steve Naroffb29b4272008-04-14 22:03:09 +0000349RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000350 Diagnostic &D, const LangOptions &LOpts)
351 : Diags(D), LangOpts(LOpts) {
352 IsHeader = IsHeaderFile(inFile);
353 InFileName = inFile;
354 OutFileName = outFile;
355 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
356 "rewriting sub-expression within a macro (may not be correct)");
357}
358
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000359ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000360 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000361 Diagnostic &Diags,
362 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000363 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000364}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000365
Steve Naroffb29b4272008-04-14 22:03:09 +0000366void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000367 Context = &context;
368 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000369 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000370 MsgSendFunctionDecl = 0;
371 MsgSendSuperFunctionDecl = 0;
372 MsgSendStretFunctionDecl = 0;
373 MsgSendSuperStretFunctionDecl = 0;
374 MsgSendFpretFunctionDecl = 0;
375 GetClassFunctionDecl = 0;
376 GetMetaClassFunctionDecl = 0;
377 SelGetUidFunctionDecl = 0;
378 CFStringFunctionDecl = 0;
379 GetProtocolFunctionDecl = 0;
380 ConstantStringClassReference = 0;
381 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000382 CurMethodDef = 0;
383 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000384 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000385 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000386 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000387 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000388 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000389
390 // Get the ID and start/end of the main file.
391 MainFileID = SM->getMainFileID();
392 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
393 MainFileStart = MainBuf->getBufferStart();
394 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000395
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000396 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000397
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000398 // declaring objc_selector outside the parameter list removes a silly
399 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000400 if (IsHeader)
401 Preamble = "#pragma once\n";
402 Preamble += "struct objc_selector; struct objc_class;\n";
403 Preamble += "#ifndef OBJC_SUPER\n";
404 Preamble += "struct objc_super { struct objc_object *object; ";
405 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000406 if (LangOpts.Microsoft) {
407 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000408 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
409 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000410 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000411 Preamble += "};\n";
412 Preamble += "#define OBJC_SUPER\n";
413 Preamble += "#endif\n";
414 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
415 Preamble += "typedef struct objc_object Protocol;\n";
416 Preamble += "#define _REWRITER_typedef_Protocol\n";
417 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000418 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000419 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
420 else
421 Preamble += "#define __OBJC_RW_EXTERN extern\n";
422 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000423 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000424 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000425 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000426 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000427 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000428 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000429 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000430 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000431 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000432 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000433 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000434 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000435 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000436 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
437 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
438 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
439 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
440 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000441 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000442 // @synchronized hooks.
443 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
444 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000445 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000446 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
447 Preamble += "struct __objcFastEnumerationState {\n\t";
448 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000449 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000450 Preamble += "unsigned long *mutationsPtr;\n\t";
451 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000452 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000453 Preamble += "#define __FASTENUMERATIONSTATE\n";
454 Preamble += "#endif\n";
455 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
456 Preamble += "struct __NSConstantStringImpl {\n";
457 Preamble += " int *isa;\n";
458 Preamble += " int flags;\n";
459 Preamble += " char *str;\n";
460 Preamble += " long length;\n";
461 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000462 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
463 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
464 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000465 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000466 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000467 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
468 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000469 // Blocks preamble.
470 Preamble += "#ifndef BLOCK_IMPL\n";
471 Preamble += "#define BLOCK_IMPL\n";
472 Preamble += "struct __block_impl {\n";
473 Preamble += " void *isa;\n";
474 Preamble += " int Flags;\n";
475 Preamble += " int Size;\n";
476 Preamble += " void *FuncPtr;\n";
477 Preamble += "};\n";
478 Preamble += "enum {\n";
479 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
480 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
481 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000482 Preamble += "// Runtime copy/destroy helper functions\n";
483 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
484 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
485 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
486 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
487 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
488 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
489 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000490 if (LangOpts.Microsoft) {
491 Preamble += "#undef __OBJC_RW_EXTERN\n";
492 Preamble += "#define __attribute__(X)\n";
493 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000494}
495
496
Chris Lattnerf04da132007-10-24 17:06:59 +0000497//===----------------------------------------------------------------------===//
498// Top Level Driver Code
499//===----------------------------------------------------------------------===//
500
Steve Naroffb29b4272008-04-14 22:03:09 +0000501void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000502 // Two cases: either the decl could be in the main file, or it could be in a
503 // #included file. If the former, rewrite it now. If the later, check to see
504 // if we rewrote the #include/#import.
505 SourceLocation Loc = D->getLocation();
506 Loc = SM->getLogicalLoc(Loc);
507
508 // If this is for a builtin, ignore it.
509 if (Loc.isInvalid()) return;
510
Steve Naroffebf2b562007-10-23 23:50:29 +0000511 // Look for built-in declarations that we need to refer during the rewrite.
512 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000513 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000514 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000515 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000516 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000517 ConstantStringClassReference = FVD;
518 return;
519 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000520 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000521 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000522 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000523 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000524 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000525 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000526 } else if (ObjCForwardProtocolDecl *FP =
527 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000528 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000529 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000530 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000531 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000532 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000533}
534
Chris Lattnerf04da132007-10-24 17:06:59 +0000535//===----------------------------------------------------------------------===//
536// Syntactic (non-AST) Rewriting Code
537//===----------------------------------------------------------------------===//
538
Steve Naroffb29b4272008-04-14 22:03:09 +0000539void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000540 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
541 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
542 const char *MainBufStart = MainBuf.first;
543 const char *MainBufEnd = MainBuf.second;
544 size_t ImportLen = strlen("import");
545 size_t IncludeLen = strlen("include");
546
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000547 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000548 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
549 if (*BufPtr == '#') {
550 if (++BufPtr == MainBufEnd)
551 return;
552 while (*BufPtr == ' ' || *BufPtr == '\t')
553 if (++BufPtr == MainBufEnd)
554 return;
555 if (!strncmp(BufPtr, "import", ImportLen)) {
556 // replace import with include
557 SourceLocation ImportLoc =
558 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000559 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000560 BufPtr += ImportLen;
561 }
562 }
563 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000564}
565
Steve Naroffb29b4272008-04-14 22:03:09 +0000566void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000567 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
568 const char *MainBufStart = MainBuf.first;
569 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000570
Chris Lattnerf04da132007-10-24 17:06:59 +0000571 // Loop over the whole file, looking for tabs.
572 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
573 if (*BufPtr != '\t')
574 continue;
575
576 // Okay, we found a tab. This tab will turn into at least one character,
577 // but it depends on which 'virtual column' it is in. Compute that now.
578 unsigned VCol = 0;
579 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
580 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
581 ++VCol;
582
583 // Okay, now that we know the virtual column, we know how many spaces to
584 // insert. We assume 8-character tab-stops.
585 unsigned Spaces = 8-(VCol & 7);
586
587 // Get the location of the tab.
588 SourceLocation TabLoc =
589 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
590
591 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000592 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000593 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000594}
595
Steve Naroffeb0646c2008-12-02 15:48:25 +0000596static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
597 ObjCIvarDecl *OID) {
598 std::string S;
599 S = "((struct ";
600 S += ClassDecl->getIdentifier()->getName();
601 S += "_IMPL *)self)->";
602 S += OID->getNameAsCString();
603 return S;
604}
605
Steve Naroffa0876e82008-12-02 17:36:43 +0000606void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
607 ObjCImplementationDecl *IMD,
608 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000609 SourceLocation startLoc = PID->getLocStart();
610 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000611 const char *startBuf = SM->getCharacterData(startLoc);
612 assert((*startBuf == '@') && "bogus @synthesize location");
613 const char *semiBuf = strchr(startBuf, ';');
614 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
615 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
616
617 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
618 return; // FIXME: is this correct?
619
620 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000621 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000622 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000623 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000624
625 if (!OID)
626 return;
627
628 std::string Getr;
629 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
630 Getr += "{ ";
631 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000632 // FIXME: deal with code generation implications for various property
633 // attributes (copy, retain, nonatomic).
634 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000635 Getr += "return " + getIvarAccessString(ClassDecl, OID);
636 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000637 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000638
639 // Add the rewritten getter to trigger meta data generation. An alternate, and
640 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
641 // with properties explicitly. The following addInstanceMethod() required far
642 // less code change (and actually models what the rewriter is doing).
643 if (IMD)
644 IMD->addInstanceMethod(PD->getGetterMethodDecl());
645 else
646 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000647
648 if (PD->isReadOnly())
649 return;
650
651 // Generate the 'setter' function.
652 std::string Setr;
653 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000654 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000655 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000656 // FIXME: deal with code generation implications for various property
657 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000658 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000659 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
660 Setr += OID->getNameAsCString();
661 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000662 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000663
664 // Add the rewritten setter to trigger meta data generation.
665 if (IMD)
666 IMD->addInstanceMethod(PD->getSetterMethodDecl());
667 else
668 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000669}
Chris Lattner8a12c272007-10-11 18:38:32 +0000670
Steve Naroffb29b4272008-04-14 22:03:09 +0000671void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000672 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000673 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000674
675 // Get the start location and compute the semi location.
676 SourceLocation startLoc = ClassDecl->getLocation();
677 const char *startBuf = SM->getCharacterData(startLoc);
678 const char *semiPtr = strchr(startBuf, ';');
679
680 // Translate to typedef's that forward reference structs with the same name
681 // as the class. As a convenience, we include the original declaration
682 // as a comment.
683 std::string typedefString;
684 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000685 typedefString.append(startBuf, semiPtr-startBuf+1);
686 typedefString += "\n";
687 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000688 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000689 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000690 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000691 typedefString += "\n";
692 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000693 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000694 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000695 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000696 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000697 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000698 }
699
700 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000701 ReplaceText(startLoc, semiPtr-startBuf+1,
702 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000703}
704
Steve Naroffb29b4272008-04-14 22:03:09 +0000705void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000706 SourceLocation LocStart = Method->getLocStart();
707 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000708
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000709 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000710 InsertText(LocStart, "#if 0\n", 6);
711 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000712 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000713 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000714 }
715}
716
Steve Naroffb29b4272008-04-14 22:03:09 +0000717void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000718{
Chris Lattner55d13b42008-03-16 21:23:50 +0000719 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000720 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000721 SourceLocation Loc = Property->getLocation();
722
Chris Lattneraadaf782008-01-31 19:51:04 +0000723 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000724
725 // FIXME: handle properties that are declared across multiple lines.
726 }
727}
728
Steve Naroffb29b4272008-04-14 22:03:09 +0000729void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000730 SourceLocation LocStart = CatDecl->getLocStart();
731
732 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000733 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000734
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000735 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000736 E = CatDecl->instmeth_end(); I != E; ++I)
737 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000738 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000739 E = CatDecl->classmeth_end(); I != E; ++I)
740 RewriteMethodDeclaration(*I);
741
Steve Naroff423cb562007-10-30 13:30:57 +0000742 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000743 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000744}
745
Steve Naroffb29b4272008-04-14 22:03:09 +0000746void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000747 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000748
Steve Naroff752d6ef2007-10-30 16:42:30 +0000749 SourceLocation LocStart = PDecl->getLocStart();
750
751 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000752 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000753
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000754 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000755 E = PDecl->instmeth_end(); I != E; ++I)
756 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000757 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000758 E = PDecl->classmeth_end(); I != E; ++I)
759 RewriteMethodDeclaration(*I);
760
Steve Naroff752d6ef2007-10-30 16:42:30 +0000761 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000762 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000763 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000764
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000765 // Must comment out @optional/@required
766 const char *startBuf = SM->getCharacterData(LocStart);
767 const char *endBuf = SM->getCharacterData(LocEnd);
768 for (const char *p = startBuf; p < endBuf; p++) {
769 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
770 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000771 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000772 ReplaceText(OptionalLoc, strlen("@optional"),
773 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000774
775 }
776 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
777 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000778 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000779 ReplaceText(OptionalLoc, strlen("@required"),
780 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000781
782 }
783 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000784}
785
Steve Naroffb29b4272008-04-14 22:03:09 +0000786void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000787 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000788 if (LocStart.isInvalid())
789 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000790 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000791 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000792}
793
Steve Naroffb29b4272008-04-14 22:03:09 +0000794void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000795 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000796 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000797 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000798 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000799 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000800 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000801 else if (OMD->getResultType()->isFunctionPointerType()) {
802 // needs special handling, since pointer-to-functions have special
803 // syntax (where a decaration models use).
804 QualType retType = OMD->getResultType();
805 if (const PointerType* PT = retType->getAsPointerType()) {
806 QualType PointeeTy = PT->getPointeeType();
807 if ((FPRetType = PointeeTy->getAsFunctionType())) {
808 ResultStr += FPRetType->getResultType().getAsString();
809 ResultStr += "(*";
810 }
811 }
812 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000813 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000814 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000815
816 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000817 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000818
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000819 if (OMD->isInstance())
820 NameStr += "_I_";
821 else
822 NameStr += "_C_";
823
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000824 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000825 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000826
827 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000828 if (ObjCCategoryImplDecl *CID =
829 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000830 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000831 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000832 }
Steve Naroff563b8282008-04-04 22:23:44 +0000833 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000834 {
835 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000836 int len = selString.size();
837 for (int i = 0; i < len; i++)
838 if (selString[i] == ':')
839 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000840 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000841 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000842 // Remember this name for metadata emission
843 MethodInternalNames[OMD] = NameStr;
844 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000845
846 // Rewrite arguments
847 ResultStr += "(";
848
849 // invisible arguments
850 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000851 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000852 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000853 if (!LangOpts.Microsoft) {
854 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
855 ResultStr += "struct ";
856 }
857 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000858 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000859 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000860 }
861 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000862 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000863
864 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000865 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000866 ResultStr += " _cmd";
867
868 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000869 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000870 ParmVarDecl *PDecl = OMD->getParamDecl(i);
871 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000872 if (PDecl->getType()->isObjCQualifiedIdType()) {
873 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000874 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000875 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000876 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000877 if (isBlockPointerType(PDecl->getType())) {
878 // Make sure we convert "t (^)(...)" to "t (*)(...)".
879 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
880 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
881 } else
882 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000883 ResultStr += Name;
884 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000885 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000886 if (OMD->isVariadic())
887 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000888 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000889
Steve Naroff76e429d2008-07-16 14:40:40 +0000890 if (FPRetType) {
891 ResultStr += ")"; // close the precedence "scope" for "*".
892
893 // Now, emit the argument types (if any).
894 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
895 ResultStr += "(";
896 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
897 if (i) ResultStr += ", ";
898 std::string ParamStr = FT->getArgType(i).getAsString();
899 ResultStr += ParamStr;
900 }
901 if (FT->isVariadic()) {
902 if (FT->getNumArgs()) ResultStr += ", ";
903 ResultStr += "...";
904 }
905 ResultStr += ")";
906 } else {
907 ResultStr += "()";
908 }
909 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000910}
Steve Naroffb29b4272008-04-14 22:03:09 +0000911void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000912 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
913 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000914
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000915 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000916 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000917 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000918 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000919
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000920 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000921 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
922 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000923 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000924 ObjCMethodDecl *OMD = *I;
925 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000926 SourceLocation LocStart = OMD->getLocStart();
927 SourceLocation LocEnd = OMD->getBody()->getLocStart();
928
929 const char *startBuf = SM->getCharacterData(LocStart);
930 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000931 ReplaceText(LocStart, endBuf-startBuf,
932 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000933 }
934
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000935 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000936 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
937 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000938 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000939 ObjCMethodDecl *OMD = *I;
940 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000941 SourceLocation LocStart = OMD->getLocStart();
942 SourceLocation LocEnd = OMD->getBody()->getLocStart();
943
944 const char *startBuf = SM->getCharacterData(LocStart);
945 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000946 ReplaceText(LocStart, endBuf-startBuf,
947 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000948 }
Steve Naroffd40910b2008-12-01 20:33:01 +0000949 for (ObjCCategoryImplDecl::propimpl_iterator
950 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
951 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +0000952 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +0000953 }
954
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000955 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000956 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000957 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000958 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000959}
960
Steve Naroffb29b4272008-04-14 22:03:09 +0000961void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000962 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000963 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000964 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000965 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000966 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000967 ResultStr += "\n";
968 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000969 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000970 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000971 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000972 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000973 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000974 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000975 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000976 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000977 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000978
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000979 RewriteProperties(ClassDecl->getNumPropertyDecl(),
980 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000981 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000982 E = ClassDecl->instmeth_end(); I != E; ++I)
983 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000984 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000985 E = ClassDecl->classmeth_end(); I != E; ++I)
986 RewriteMethodDeclaration(*I);
987
Steve Naroff2feac5e2007-10-30 03:43:13 +0000988 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000989 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000990}
991
Steve Naroff15f081d2008-12-03 00:56:33 +0000992Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp,
993 ObjCPropertyRefExpr *PRE) {
994 // FIXME: Fill in the transform.
995 return BinOp;
996}
997
998Stmt *RewriteObjC::RewritePropertyRefExpr(ObjCPropertyRefExpr *PropRefExpr) {
999 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1000 // This allows us to reuse all the fun and games in SynthMessageExpr().
1001 ObjCMessageExpr *MsgExpr;
1002 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1003
1004 MsgExpr = new ObjCMessageExpr(PropRefExpr->getBase(),
1005 PDecl->getGetterName(), PDecl->getType(),
1006 PDecl->getGetterMethodDecl(),
1007 SourceLocation(), SourceLocation(),
1008 0, 0);
1009
1010 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1011
1012 // Now do the actual rewrite.
1013 ReplaceStmt(PropRefExpr, ReplacingStmt);
1014 PropMsgExprs[ReplacingStmt] = PropRefExpr;
1015
1016 // delete PropRefExpr; elsewhere...
1017 delete MsgExpr;
1018 return ReplacingStmt;
1019}
1020
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001021Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1022 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001023 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001024 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001025 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001026 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1027 // lookup which class implements the instance variable.
1028 ObjCInterfaceDecl *clsDeclared = 0;
1029 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1030 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1031
1032 // Synthesize an explicit cast to gain access to the ivar.
1033 std::string RecName = clsDeclared->getIdentifier()->getName();
1034 RecName += "_IMPL";
1035 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001036 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001037 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001038 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1039 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001040 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001041 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001042 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001043 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1044 IV->getBase()->getLocEnd(),
1045 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001046 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001047 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001048 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1049 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001050 ReplaceStmt(IV, ME);
1051 delete IV;
1052 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001053 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001054
1055 ReplaceStmt(IV->getBase(), PE);
1056 // Cannot delete IV->getBase(), since PE points to it.
1057 // Replace the old base with the cast. This is important when doing
1058 // embedded rewrites. For example, [newInv->_container addObject:0].
1059 IV->setBase(PE);
1060 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001061 }
Steve Naroff84472a82008-04-18 21:55:08 +00001062 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001063 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1064
1065 // Explicit ivar refs need to have a cast inserted.
1066 // FIXME: consider sharing some of this code with the code above.
1067 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001068 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001069 // lookup which class implements the instance variable.
1070 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001071 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001072 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1073
1074 // Synthesize an explicit cast to gain access to the ivar.
1075 std::string RecName = clsDeclared->getIdentifier()->getName();
1076 RecName += "_IMPL";
1077 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001078 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001079 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001080 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1081 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001082 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001083 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001084 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001085 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1086 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001087 ReplaceStmt(IV->getBase(), PE);
1088 // Cannot delete IV->getBase(), since PE points to it.
1089 // Replace the old base with the cast. This is important when doing
1090 // embedded rewrites. For example, [newInv->_container addObject:0].
1091 IV->setBase(PE);
1092 return IV;
1093 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001094 }
Steve Naroff84472a82008-04-18 21:55:08 +00001095 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001096}
1097
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001098/// SynthCountByEnumWithState - To print:
1099/// ((unsigned int (*)
1100/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1101/// (void *)objc_msgSend)((id)l_collection,
1102/// sel_registerName(
1103/// "countByEnumeratingWithState:objects:count:"),
1104/// &enumState,
1105/// (id *)items, (unsigned int)16)
1106///
Steve Naroffb29b4272008-04-14 22:03:09 +00001107void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001108 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1109 "id *, unsigned int))(void *)objc_msgSend)";
1110 buf += "\n\t\t";
1111 buf += "((id)l_collection,\n\t\t";
1112 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1113 buf += "\n\t\t";
1114 buf += "&enumState, "
1115 "(id *)items, (unsigned int)16)";
1116}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001117
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001118/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1119/// statement to exit to its outer synthesized loop.
1120///
Steve Naroffb29b4272008-04-14 22:03:09 +00001121Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001122 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1123 return S;
1124 // replace break with goto __break_label
1125 std::string buf;
1126
1127 SourceLocation startLoc = S->getLocStart();
1128 buf = "goto __break_label_";
1129 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001130 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001131
1132 return 0;
1133}
1134
1135/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1136/// statement to continue with its inner synthesized loop.
1137///
Steve Naroffb29b4272008-04-14 22:03:09 +00001138Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001139 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1140 return S;
1141 // replace continue with goto __continue_label
1142 std::string buf;
1143
1144 SourceLocation startLoc = S->getLocStart();
1145 buf = "goto __continue_label_";
1146 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001147 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001148
1149 return 0;
1150}
1151
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001152/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001153/// It rewrites:
1154/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001155
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001156/// Into:
1157/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001158/// type elem;
1159/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001160/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001161/// id l_collection = (id)collection;
1162/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1163/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001164/// if (limit) {
1165/// unsigned long startMutations = *enumState.mutationsPtr;
1166/// do {
1167/// unsigned long counter = 0;
1168/// do {
1169/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001170/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001171/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001172/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001173/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001174/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001175/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1176/// objects:items count:16]);
1177/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001178/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001179/// }
1180/// else
1181/// elem = nil;
1182/// }
1183///
Steve Naroffb29b4272008-04-14 22:03:09 +00001184Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001185 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001186 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1187 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1188 "ObjCForCollectionStmt Statement stack mismatch");
1189 assert(!ObjCBcLabelNo.empty() &&
1190 "ObjCForCollectionStmt - Label No stack empty");
1191
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001192 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001193 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001194 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001195 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001196 std::string buf;
1197 buf = "\n{\n\t";
1198 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1199 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001200 ScopedDecl* D = DS->getSolitaryDecl();
1201 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001202 elementTypeAsString = ElementType.getAsString();
1203 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001204 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001205 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001206 buf += elementName;
1207 buf += ";\n\t";
1208 }
Chris Lattner06767512008-04-08 05:52:18 +00001209 else {
1210 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001211 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001212 elementTypeAsString
1213 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001214 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001215
1216 // struct __objcFastEnumerationState enumState = { 0 };
1217 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1218 // id items[16];
1219 buf += "id items[16];\n\t";
1220 // id l_collection = (id)
1221 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001222 // Find start location of 'collection' the hard way!
1223 const char *startCollectionBuf = startBuf;
1224 startCollectionBuf += 3; // skip 'for'
1225 startCollectionBuf = strchr(startCollectionBuf, '(');
1226 startCollectionBuf++; // skip '('
1227 // find 'in' and skip it.
1228 while (*startCollectionBuf != ' ' ||
1229 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1230 (*(startCollectionBuf+3) != ' ' &&
1231 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1232 startCollectionBuf++;
1233 startCollectionBuf += 3;
1234
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001235 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001236 ReplaceText(startLoc, startCollectionBuf - startBuf,
1237 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001238 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001239 SourceLocation rightParenLoc = S->getRParenLoc();
1240 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1241 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001242 buf = ";\n\t";
1243
1244 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1245 // objects:items count:16];
1246 // which is synthesized into:
1247 // unsigned int limit =
1248 // ((unsigned int (*)
1249 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1250 // (void *)objc_msgSend)((id)l_collection,
1251 // sel_registerName(
1252 // "countByEnumeratingWithState:objects:count:"),
1253 // (struct __objcFastEnumerationState *)&state,
1254 // (id *)items, (unsigned int)16);
1255 buf += "unsigned long limit =\n\t\t";
1256 SynthCountByEnumWithState(buf);
1257 buf += ";\n\t";
1258 /// if (limit) {
1259 /// unsigned long startMutations = *enumState.mutationsPtr;
1260 /// do {
1261 /// unsigned long counter = 0;
1262 /// do {
1263 /// if (startMutations != *enumState.mutationsPtr)
1264 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001265 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001266 buf += "if (limit) {\n\t";
1267 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1268 buf += "do {\n\t\t";
1269 buf += "unsigned long counter = 0;\n\t\t";
1270 buf += "do {\n\t\t\t";
1271 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1272 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1273 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001274 buf += " = (";
1275 buf += elementTypeAsString;
1276 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001277 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001278 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001279
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001280 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001281 /// } while (counter < limit);
1282 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1283 /// objects:items count:16]);
1284 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001285 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001286 /// }
1287 /// else
1288 /// elem = nil;
1289 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001290 ///
1291 buf = ";\n\t";
1292 buf += "__continue_label_";
1293 buf += utostr(ObjCBcLabelNo.back());
1294 buf += ": ;";
1295 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001296 buf += "} while (counter < limit);\n\t";
1297 buf += "} while (limit = ";
1298 SynthCountByEnumWithState(buf);
1299 buf += ");\n\t";
1300 buf += elementName;
1301 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001302 buf += "__break_label_";
1303 buf += utostr(ObjCBcLabelNo.back());
1304 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001305 buf += "}\n\t";
1306 buf += "else\n\t\t";
1307 buf += elementName;
1308 buf += " = nil;\n";
1309 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001310
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001311 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001312 if (isa<CompoundStmt>(S->getBody())) {
1313 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1314 InsertText(endBodyLoc, buf.c_str(), buf.size());
1315 } else {
1316 /* Need to treat single statements specially. For example:
1317 *
1318 * for (A *a in b) if (stuff()) break;
1319 * for (A *a in b) xxxyy;
1320 *
1321 * The following code simply scans ahead to the semi to find the actual end.
1322 */
1323 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1324 const char *semiBuf = strchr(stmtBuf, ';');
1325 assert(semiBuf && "Can't find ';'");
1326 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1327 InsertText(endBodyLoc, buf.c_str(), buf.size());
1328 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001329 Stmts.pop_back();
1330 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001331 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001332}
1333
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001334/// RewriteObjCSynchronizedStmt -
1335/// This routine rewrites @synchronized(expr) stmt;
1336/// into:
1337/// objc_sync_enter(expr);
1338/// @try stmt @finally { objc_sync_exit(expr); }
1339///
Steve Naroffb29b4272008-04-14 22:03:09 +00001340Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001341 // Get the start location and compute the semi location.
1342 SourceLocation startLoc = S->getLocStart();
1343 const char *startBuf = SM->getCharacterData(startLoc);
1344
1345 assert((*startBuf == '@') && "bogus @synchronized location");
1346
1347 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001348 buf = "objc_sync_enter((id)";
1349 const char *lparenBuf = startBuf;
1350 while (*lparenBuf != '(') lparenBuf++;
1351 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001352 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1353 // the sync expression is typically a message expression that's already
1354 // been rewritten! (which implies the SourceLocation's are invalid).
1355 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001356 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001357 while (*endBuf != ')') endBuf--;
1358 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001359 buf = ");\n";
1360 // declare a new scope with two variables, _stack and _rethrow.
1361 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1362 buf += "int buf[18/*32-bit i386*/];\n";
1363 buf += "char *pointers[4];} _stack;\n";
1364 buf += "id volatile _rethrow = 0;\n";
1365 buf += "objc_exception_try_enter(&_stack);\n";
1366 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001367 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001368 startLoc = S->getSynchBody()->getLocEnd();
1369 startBuf = SM->getCharacterData(startLoc);
1370
Steve Naroffc7089f12008-08-19 13:04:19 +00001371 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001372 SourceLocation lastCurlyLoc = startLoc;
1373 buf = "}\nelse {\n";
1374 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1375 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001376 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001377 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001378 S->getSynchExpr(),
1379 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001380 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001381 std::string syncExprBufS;
1382 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001383 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001384 buf += syncExprBuf.str();
1385 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001386 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1387 buf += "}\n";
1388 buf += "}";
1389
Chris Lattneraadaf782008-01-31 19:51:04 +00001390 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001391 return 0;
1392}
1393
Steve Naroffb29b4272008-04-14 22:03:09 +00001394Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001395 // Get the start location and compute the semi location.
1396 SourceLocation startLoc = S->getLocStart();
1397 const char *startBuf = SM->getCharacterData(startLoc);
1398
1399 assert((*startBuf == '@') && "bogus @try location");
1400
1401 std::string buf;
1402 // declare a new scope with two variables, _stack and _rethrow.
1403 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1404 buf += "int buf[18/*32-bit i386*/];\n";
1405 buf += "char *pointers[4];} _stack;\n";
1406 buf += "id volatile _rethrow = 0;\n";
1407 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001408 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001409
Chris Lattneraadaf782008-01-31 19:51:04 +00001410 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001411
1412 startLoc = S->getTryBody()->getLocEnd();
1413 startBuf = SM->getCharacterData(startLoc);
1414
1415 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001416
Steve Naroff75730982007-11-07 04:08:17 +00001417 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001418 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1419 if (catchList) {
1420 startLoc = startLoc.getFileLocWithOffset(1);
1421 buf = " /* @catch begin */ else {\n";
1422 buf += " id _caught = objc_exception_extract(&_stack);\n";
1423 buf += " objc_exception_try_enter (&_stack);\n";
1424 buf += " if (_setjmp(_stack.buf))\n";
1425 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1426 buf += " else { /* @catch continue */";
1427
1428 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001429 } else { /* no catch list */
1430 buf = "}\nelse {\n";
1431 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1432 buf += "}";
1433 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001434 }
Steve Naroff75730982007-11-07 04:08:17 +00001435 bool sawIdTypedCatch = false;
1436 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001437 while (catchList) {
1438 Stmt *catchStmt = catchList->getCatchParamStmt();
1439
1440 if (catchList == S->getCatchStmts())
1441 buf = "if ("; // we are generating code for the first catch clause
1442 else
1443 buf = "else if (";
1444 startLoc = catchList->getLocStart();
1445 startBuf = SM->getCharacterData(startLoc);
1446
1447 assert((*startBuf == '@') && "bogus @catch location");
1448
1449 const char *lParenLoc = strchr(startBuf, '(');
1450
Steve Naroffbe4b3332008-02-01 22:08:12 +00001451 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001452 // Now rewrite the body...
1453 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001454 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1455 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001456 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1457 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001458 assert((*bodyBuf == '{') && "bogus @catch body location");
1459
1460 buf += "1) { id _tmp = _caught;";
1461 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1462 buf.c_str(), buf.size());
1463 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001464 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001465 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001466 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001467 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001468 sawIdTypedCatch = true;
1469 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001470 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001471
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001472 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001473 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001474 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001475 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001476 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001477 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001478 }
1479 }
1480 // Now rewrite the body...
1481 lastCatchBody = catchList->getCatchBody();
1482 SourceLocation rParenLoc = catchList->getRParenLoc();
1483 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1484 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1485 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1486 assert((*rParenBuf == ')') && "bogus @catch paren location");
1487 assert((*bodyBuf == '{') && "bogus @catch body location");
1488
1489 buf = " = _caught;";
1490 // Here we replace ") {" with "= _caught;" (which initializes and
1491 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001492 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001493 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001494 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001495 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001496 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001497 catchList = catchList->getNextCatchStmt();
1498 }
1499 // Complete the catch list...
1500 if (lastCatchBody) {
1501 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001502 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1503 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001504
Steve Naroff378f47a2008-09-11 15:29:03 +00001505 // Insert the last (implicit) else clause *before* the right curly brace.
1506 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1507 buf = "} /* last catch end */\n";
1508 buf += "else {\n";
1509 buf += " _rethrow = _caught;\n";
1510 buf += " objc_exception_try_exit(&_stack);\n";
1511 buf += "} } /* @catch end */\n";
1512 if (!S->getFinallyStmt())
1513 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001514 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001515
1516 // Set lastCurlyLoc
1517 lastCurlyLoc = lastCatchBody->getLocEnd();
1518 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001519 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001520 startLoc = finalStmt->getLocStart();
1521 startBuf = SM->getCharacterData(startLoc);
1522 assert((*startBuf == '@') && "bogus @finally start");
1523
1524 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001525 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001526
1527 Stmt *body = finalStmt->getFinallyBody();
1528 SourceLocation startLoc = body->getLocStart();
1529 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001530 assert(*SM->getCharacterData(startLoc) == '{' &&
1531 "bogus @finally body location");
1532 assert(*SM->getCharacterData(endLoc) == '}' &&
1533 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001534
1535 startLoc = startLoc.getFileLocWithOffset(1);
1536 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001537 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001538 endLoc = endLoc.getFileLocWithOffset(-1);
1539 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001540 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001541
1542 // Set lastCurlyLoc
1543 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001544 } else { /* no finally clause - make sure we synthesize an implicit one */
1545 buf = "{ /* implicit finally clause */\n";
1546 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1547 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1548 buf += "}";
1549 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001550 }
1551 // Now emit the final closing curly brace...
1552 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1553 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001554 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001555 return 0;
1556}
1557
Steve Naroffb29b4272008-04-14 22:03:09 +00001558Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001559 return 0;
1560}
1561
Steve Naroffb29b4272008-04-14 22:03:09 +00001562Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001563 return 0;
1564}
1565
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001566// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001567// the throw expression is typically a message expression that's already
1568// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001569Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001570 // Get the start location and compute the semi location.
1571 SourceLocation startLoc = S->getLocStart();
1572 const char *startBuf = SM->getCharacterData(startLoc);
1573
1574 assert((*startBuf == '@') && "bogus @throw location");
1575
1576 std::string buf;
1577 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001578 if (S->getThrowExpr())
1579 buf = "objc_exception_throw(";
1580 else // add an implicit argument
1581 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001582
1583 // handle "@ throw" correctly.
1584 const char *wBuf = strchr(startBuf, 'w');
1585 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1586 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1587
Steve Naroff2bd03922007-11-07 15:32:26 +00001588 const char *semiBuf = strchr(startBuf, ';');
1589 assert((*semiBuf == ';') && "@throw: can't find ';'");
1590 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1591 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001592 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001593 return 0;
1594}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001595
Steve Naroffb29b4272008-04-14 22:03:09 +00001596Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001597 // Create a new string expression.
1598 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001599 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001600 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001601 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1602 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001603 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001604 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001605
Chris Lattner07506182007-11-30 22:53:43 +00001606 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001607 delete Exp;
1608 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001609}
1610
Steve Naroffb29b4272008-04-14 22:03:09 +00001611Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001612 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1613 // Create a call to sel_registerName("selName").
1614 llvm::SmallVector<Expr*, 8> SelExprs;
1615 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001616 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1617 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001618 false, argType, SourceLocation(),
1619 SourceLocation()));
1620 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1621 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001622 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001623 delete Exp;
1624 return SelExp;
1625}
1626
Steve Naroffb29b4272008-04-14 22:03:09 +00001627CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001628 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001629 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001630 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001631
1632 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001633 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001634
1635 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001636 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001637 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1638 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001639
1640 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001641
Steve Naroff934f2762007-10-24 22:48:43 +00001642 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1643}
1644
Steve Naroffd5255f52007-11-01 13:24:47 +00001645static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1646 const char *&startRef, const char *&endRef) {
1647 while (startBuf < endBuf) {
1648 if (*startBuf == '<')
1649 startRef = startBuf; // mark the start.
1650 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001651 if (startRef && *startRef == '<') {
1652 endRef = startBuf; // mark the end.
1653 return true;
1654 }
1655 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001656 }
1657 startBuf++;
1658 }
1659 return false;
1660}
1661
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001662static void scanToNextArgument(const char *&argRef) {
1663 int angle = 0;
1664 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1665 if (*argRef == '<')
1666 angle++;
1667 else if (*argRef == '>')
1668 angle--;
1669 argRef++;
1670 }
1671 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1672}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001673
Steve Naroffb29b4272008-04-14 22:03:09 +00001674bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001675
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001676 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001677 return true;
1678
Steve Naroffd5255f52007-11-01 13:24:47 +00001679 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001680 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001681 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001682 return true; // we have "Class <Protocol> *".
1683 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001684 return false;
1685}
1686
Steve Naroff4f95b752008-07-29 18:15:38 +00001687void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1688 QualType Type = E->getType();
1689 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001690 SourceLocation Loc, EndLoc;
1691
1692 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1693 Loc = ECE->getLParenLoc();
1694 EndLoc = ECE->getRParenLoc();
1695 } else {
1696 Loc = E->getLocStart();
1697 EndLoc = E->getLocEnd();
1698 }
1699 // This will defend against trying to rewrite synthesized expressions.
1700 if (Loc.isInvalid() || EndLoc.isInvalid())
1701 return;
1702
Steve Naroff4f95b752008-07-29 18:15:38 +00001703 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001704 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001705 const char *startRef = 0, *endRef = 0;
1706 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1707 // Get the locations of the startRef, endRef.
1708 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1709 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1710 // Comment out the protocol references.
1711 InsertText(LessLoc, "/*", 2);
1712 InsertText(GreaterLoc, "*/", 2);
1713 }
1714 }
1715}
1716
Steve Naroffb29b4272008-04-14 22:03:09 +00001717void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001718 SourceLocation Loc;
1719 QualType Type;
1720 const FunctionTypeProto *proto = 0;
1721 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1722 Loc = VD->getLocation();
1723 Type = VD->getType();
1724 }
1725 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1726 Loc = FD->getLocation();
1727 // Check for ObjC 'id' and class types that have been adorned with protocol
1728 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1729 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1730 assert(funcType && "missing function type");
1731 proto = dyn_cast<FunctionTypeProto>(funcType);
1732 if (!proto)
1733 return;
1734 Type = proto->getResultType();
1735 }
1736 else
1737 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001738
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001739 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001740 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001741
1742 const char *endBuf = SM->getCharacterData(Loc);
1743 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001744 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001745 startBuf--; // scan backward (from the decl location) for return type.
1746 const char *startRef = 0, *endRef = 0;
1747 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1748 // Get the locations of the startRef, endRef.
1749 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1750 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1751 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001752 InsertText(LessLoc, "/*", 2);
1753 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001754 }
1755 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001756 if (!proto)
1757 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001758 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001759 const char *startBuf = SM->getCharacterData(Loc);
1760 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001761 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1762 if (needToScanForQualifiers(proto->getArgType(i))) {
1763 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001764
Steve Naroffd5255f52007-11-01 13:24:47 +00001765 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001766 // scan forward (from the decl location) for argument types.
1767 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001768 const char *startRef = 0, *endRef = 0;
1769 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1770 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001771 SourceLocation LessLoc =
1772 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1773 SourceLocation GreaterLoc =
1774 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001775 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001776 InsertText(LessLoc, "/*", 2);
1777 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001778 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001779 startBuf = ++endBuf;
1780 }
1781 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001782 // If the function name is derived from a macro expansion, then the
1783 // argument buffer will not follow the name. Need to speak with Chris.
1784 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001785 startBuf++; // scan forward (from the decl location) for argument types.
1786 startBuf++;
1787 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001788 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001789}
1790
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001791// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001792void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001793 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1794 llvm::SmallVector<QualType, 16> ArgTys;
1795 ArgTys.push_back(Context->getPointerType(
1796 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001797 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001798 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001799 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001800 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001801 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001802 SelGetUidIdent, getFuncType,
1803 FunctionDecl::Extern, false, 0);
1804}
1805
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001806// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001807void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001808 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1809 llvm::SmallVector<QualType, 16> ArgTys;
1810 ArgTys.push_back(Context->getPointerType(
1811 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001812 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001813 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001814 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001815 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001816 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001817 SelGetProtoIdent, getFuncType,
1818 FunctionDecl::Extern, false, 0);
1819}
1820
Steve Naroffb29b4272008-04-14 22:03:09 +00001821void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001822 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001823 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001824 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001825 return;
1826 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001827 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001828}
1829
Steve Naroffc0a123c2008-03-11 17:37:02 +00001830// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001831void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001832 if (SuperContructorFunctionDecl)
1833 return;
1834 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1835 llvm::SmallVector<QualType, 16> ArgTys;
1836 QualType argT = Context->getObjCIdType();
1837 assert(!argT.isNull() && "Can't find 'id' type");
1838 ArgTys.push_back(argT);
1839 ArgTys.push_back(argT);
1840 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1841 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001842 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001843 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001844 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001845 msgSendIdent, msgSendType,
1846 FunctionDecl::Extern, false, 0);
1847}
1848
Steve Naroff09b266e2007-10-30 23:14:51 +00001849// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001850void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001851 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1852 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001853 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001854 assert(!argT.isNull() && "Can't find 'id' type");
1855 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001856 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001857 assert(!argT.isNull() && "Can't find 'SEL' type");
1858 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001859 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001860 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001861 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001862 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001863 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001864 msgSendIdent, msgSendType,
1865 FunctionDecl::Extern, false, 0);
1866}
1867
Steve Naroff874e2322007-11-15 10:28:18 +00001868// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001869void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001870 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1871 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001872 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001873 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001874 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001875 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1876 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1877 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001878 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001879 assert(!argT.isNull() && "Can't find 'SEL' type");
1880 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001881 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001882 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001883 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001884 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001885 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001886 msgSendIdent, msgSendType,
1887 FunctionDecl::Extern, false, 0);
1888}
1889
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001890// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001891void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001892 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1893 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001894 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001895 assert(!argT.isNull() && "Can't find 'id' type");
1896 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001897 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001898 assert(!argT.isNull() && "Can't find 'SEL' type");
1899 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001900 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001901 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001902 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001903 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001904 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001905 msgSendIdent, msgSendType,
1906 FunctionDecl::Extern, false, 0);
1907}
1908
1909// SynthMsgSendSuperStretFunctionDecl -
1910// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001911void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001912 IdentifierInfo *msgSendIdent =
1913 &Context->Idents.get("objc_msgSendSuper_stret");
1914 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001915 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001916 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001917 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001918 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1919 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1920 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001921 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001922 assert(!argT.isNull() && "Can't find 'SEL' type");
1923 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001924 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001925 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001926 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001927 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001928 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001929 msgSendIdent, msgSendType,
1930 FunctionDecl::Extern, false, 0);
1931}
1932
Steve Naroff1284db82008-05-08 22:02:18 +00001933// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001934void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001935 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1936 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001937 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001938 assert(!argT.isNull() && "Can't find 'id' type");
1939 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001940 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001941 assert(!argT.isNull() && "Can't find 'SEL' type");
1942 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001943 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001944 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001945 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001946 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001947 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001948 msgSendIdent, msgSendType,
1949 FunctionDecl::Extern, false, 0);
1950}
1951
Steve Naroff09b266e2007-10-30 23:14:51 +00001952// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001953void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001954 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1955 llvm::SmallVector<QualType, 16> ArgTys;
1956 ArgTys.push_back(Context->getPointerType(
1957 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001958 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001959 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001960 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001961 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001962 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001963 getClassIdent, getClassType,
1964 FunctionDecl::Extern, false, 0);
1965}
1966
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001967// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001968void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001969 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1970 llvm::SmallVector<QualType, 16> ArgTys;
1971 ArgTys.push_back(Context->getPointerType(
1972 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001973 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001974 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001975 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001976 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001977 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001978 getClassIdent, getClassType,
1979 FunctionDecl::Extern, false, 0);
1980}
1981
Steve Naroffb29b4272008-04-14 22:03:09 +00001982Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001983 QualType strType = getConstantStringStructType();
1984
1985 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001986
1987 std::string tmpName = InFileName;
1988 unsigned i;
1989 for (i=0; i < tmpName.length(); i++) {
1990 char c = tmpName.at(i);
1991 // replace any non alphanumeric characters with '_'.
1992 if (!isalpha(c) && (c < '0' || c > '9'))
1993 tmpName[i] = '_';
1994 }
1995 S += tmpName;
1996 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001997 S += utostr(NumObjCStringLiterals++);
1998
Steve Naroffba92b2e2008-03-27 22:29:16 +00001999 Preamble += "static __NSConstantStringImpl " + S;
2000 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2001 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002002 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002003 std::string prettyBufS;
2004 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002005 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002006 Preamble += prettyBuf.str();
2007 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002008 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002009 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002010
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002011 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002012 &Context->Idents.get(S.c_str()), strType,
2013 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002014 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2015 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2016 Context->getPointerType(DRE->getType()),
2017 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002018 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002019 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002020 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002021 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00002022 delete Exp;
2023 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002024}
2025
Steve Naroffb29b4272008-04-14 22:03:09 +00002026ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002027 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002028 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002029
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002030 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2031 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002032 assert(PT);
2033 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2034 return IT->getDecl();
2035 }
2036 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002037}
2038
2039// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002040QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002041 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002042 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002043 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002044 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002045 QualType FieldTypes[2];
2046
2047 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002048 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002049 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002050 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002051 // Create fields
2052 FieldDecl *FieldDecls[2];
2053
2054 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002055 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002056 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002057
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002058 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002059 }
2060 return Context->getTagDeclType(SuperStructDecl);
2061}
2062
Steve Naroffb29b4272008-04-14 22:03:09 +00002063QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002064 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002065 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002066 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002067 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002068 QualType FieldTypes[4];
2069
2070 // struct objc_object *receiver;
2071 FieldTypes[0] = Context->getObjCIdType();
2072 // int flags;
2073 FieldTypes[1] = Context->IntTy;
2074 // char *str;
2075 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2076 // long length;
2077 FieldTypes[3] = Context->LongTy;
2078 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002079 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002080
2081 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002082 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002083 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002084
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002085 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002086 }
2087 return Context->getTagDeclType(ConstantStringDecl);
2088}
2089
Steve Naroffb29b4272008-04-14 22:03:09 +00002090Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002091 if (!SelGetUidFunctionDecl)
2092 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002093 if (!MsgSendFunctionDecl)
2094 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002095 if (!MsgSendSuperFunctionDecl)
2096 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002097 if (!MsgSendStretFunctionDecl)
2098 SynthMsgSendStretFunctionDecl();
2099 if (!MsgSendSuperStretFunctionDecl)
2100 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002101 if (!MsgSendFpretFunctionDecl)
2102 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002103 if (!GetClassFunctionDecl)
2104 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002105 if (!GetMetaClassFunctionDecl)
2106 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002107
Steve Naroff874e2322007-11-15 10:28:18 +00002108 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002109 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2110 // May need to use objc_msgSend_stret() as well.
2111 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002112 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002113 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002114 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002115 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002116 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002117 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002118 }
Steve Naroff874e2322007-11-15 10:28:18 +00002119
Steve Naroff934f2762007-10-24 22:48:43 +00002120 // Synthesize a call to objc_msgSend().
2121 llvm::SmallVector<Expr*, 8> MsgExprs;
2122 IdentifierInfo *clsName = Exp->getClassName();
2123
2124 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2125 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002126 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2127 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002128 if (!strcmp(clsName->getName(), "super")) {
2129 MsgSendFlavor = MsgSendSuperFunctionDecl;
2130 if (MsgSendStretFlavor)
2131 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2132 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2133
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002134 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002135 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002136
2137 llvm::SmallVector<Expr*, 4> InitExprs;
2138
2139 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002140 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002141 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002142 Context->getObjCIdType(),
2143 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002144 llvm::SmallVector<Expr*, 8> ClsExprs;
2145 QualType argType = Context->getPointerType(Context->CharTy);
2146 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2147 SuperDecl->getIdentifier()->getLength(),
2148 false, argType, SourceLocation(),
2149 SourceLocation()));
2150 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2151 &ClsExprs[0],
2152 ClsExprs.size());
2153 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002154 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002155 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002156 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002157 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002158 // struct objc_super
2159 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002160 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002161
Steve Naroff23f41272008-03-11 18:14:26 +00002162 if (LangOpts.Microsoft) {
2163 SynthSuperContructorFunctionDecl();
2164 // Simulate a contructor call...
2165 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2166 superType, SourceLocation());
2167 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2168 superType, SourceLocation());
2169 } else {
2170 // (struct objc_super) { <exprs from above> }
2171 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2172 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002173 SourceLocation(), false);
2174 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2175 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002176 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002177 // struct objc_super *
2178 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2179 Context->getPointerType(SuperRep->getType()),
2180 SourceLocation());
2181 MsgExprs.push_back(Unop);
2182 } else {
2183 llvm::SmallVector<Expr*, 8> ClsExprs;
2184 QualType argType = Context->getPointerType(Context->CharTy);
2185 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2186 clsName->getLength(),
2187 false, argType, SourceLocation(),
2188 SourceLocation()));
2189 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2190 &ClsExprs[0],
2191 ClsExprs.size());
2192 MsgExprs.push_back(Cls);
2193 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002194 } else { // instance message.
2195 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002196
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002197 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002198 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002199 if (MsgSendStretFlavor)
2200 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002201 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2202
2203 llvm::SmallVector<Expr*, 4> InitExprs;
2204
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002205 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002206 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002207 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002208 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002209 SourceLocation()),
2210 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002211 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002212
2213 llvm::SmallVector<Expr*, 8> ClsExprs;
2214 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002215 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2216 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002217 false, argType, SourceLocation(),
2218 SourceLocation()));
2219 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002220 &ClsExprs[0],
2221 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002222 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002223 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002224 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002225 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002226 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002227 // struct objc_super
2228 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002229 Expr *SuperRep;
2230
2231 if (LangOpts.Microsoft) {
2232 SynthSuperContructorFunctionDecl();
2233 // Simulate a contructor call...
2234 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2235 superType, SourceLocation());
2236 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2237 superType, SourceLocation());
2238 } else {
2239 // (struct objc_super) { <exprs from above> }
2240 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2241 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002242 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002243 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2244 }
Steve Naroff874e2322007-11-15 10:28:18 +00002245 // struct objc_super *
2246 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2247 Context->getPointerType(SuperRep->getType()),
2248 SourceLocation());
2249 MsgExprs.push_back(Unop);
2250 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002251 // Remove all type-casts because it may contain objc-style types; e.g.
2252 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002253 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002254 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002255 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002256 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002257 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002258 MsgExprs.push_back(recExpr);
2259 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002260 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002261 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002262 llvm::SmallVector<Expr*, 8> SelExprs;
2263 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002264 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2265 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002266 false, argType, SourceLocation(),
2267 SourceLocation()));
2268 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2269 &SelExprs[0], SelExprs.size());
2270 MsgExprs.push_back(SelExp);
2271
2272 // Now push any user supplied arguments.
2273 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002274 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002275 // Make all implicit casts explicit...ICE comes in handy:-)
2276 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2277 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002278 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002279 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002280 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002281 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002282 }
2283 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002284 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002285 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002286 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002287 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002288 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002289 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002290 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002291 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002292 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002293 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002294 // We've transferred the ownership to MsgExprs. Null out the argument in
2295 // the original expression, since we will delete it below.
2296 Exp->setArg(i, 0);
2297 }
Steve Naroffab972d32007-11-04 22:37:50 +00002298 // Generate the funky cast.
2299 CastExpr *cast;
2300 llvm::SmallVector<QualType, 8> ArgTypes;
2301 QualType returnType;
2302
2303 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002304 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2305 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2306 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002307 ArgTypes.push_back(Context->getObjCIdType());
2308 ArgTypes.push_back(Context->getObjCSelType());
2309 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002310 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002311 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002312 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2313 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002314 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002315 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2316 if (isBlockPointerType(t)) {
2317 const BlockPointerType *BPT = t->getAsBlockPointerType();
2318 t = Context->getPointerType(BPT->getPointeeType());
2319 }
Steve Naroff352336b2007-11-05 14:36:37 +00002320 ArgTypes.push_back(t);
2321 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002322 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2323 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002324 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002325 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002326 }
2327 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002328 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002329
2330 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002331 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2332 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002333
2334 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2335 // If we don't do this cast, we get the following bizarre warning/note:
2336 // xx.m:13: warning: function called through a non-compatible type
2337 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002338 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002339 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002340 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002341
Steve Naroffab972d32007-11-04 22:37:50 +00002342 // Now do the "normal" pointer to function cast.
2343 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002344 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002345 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002346 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002347 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002348 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002349
2350 // Don't forget the parens to enforce the proper binding.
2351 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2352
2353 const FunctionType *FT = msgSendType->getAsFunctionType();
2354 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2355 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002356 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002357 if (MsgSendStretFlavor) {
2358 // We have the method which returns a struct/union. Must also generate
2359 // call to objc_msgSend_stret and hang both varieties on a conditional
2360 // expression which dictate which one to envoke depending on size of
2361 // method's return type.
2362
2363 // Create a reference to the objc_msgSend_stret() declaration.
2364 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2365 SourceLocation());
2366 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002367 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002368 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002369 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002370 // Now do the "normal" pointer to function cast.
2371 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002372 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002373 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002374 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002375 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002376
2377 // Don't forget the parens to enforce the proper binding.
2378 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2379
2380 FT = msgSendType->getAsFunctionType();
2381 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2382 FT->getResultType(), SourceLocation());
2383
2384 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002385 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2386 returnType.getAsOpaquePtr(),
2387 Context->getSizeType(),
2388 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002389 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2390 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2391 // For X86 it is more complicated and some kind of target specific routine
2392 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002393 unsigned IntSize =
2394 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002395 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2396 Context->IntTy,
2397 SourceLocation());
2398 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2399 BinaryOperator::LE,
2400 Context->IntTy,
2401 SourceLocation());
2402 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2403 ConditionalOperator *CondExpr =
2404 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002405 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002406 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002407 return ReplacingStmt;
2408}
2409
Steve Naroffb29b4272008-04-14 22:03:09 +00002410Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002411 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002412
Steve Naroff934f2762007-10-24 22:48:43 +00002413 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002414 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002415
Chris Lattnere64b7772007-10-24 16:57:36 +00002416 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002417 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002418}
2419
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002420/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2421/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002422Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002423 if (!GetProtocolFunctionDecl)
2424 SynthGetProtocolFunctionDecl();
2425 // Create a call to objc_getProtocol("ProtocolName").
2426 llvm::SmallVector<Expr*, 8> ProtoExprs;
2427 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002428 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2429 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002430 false, argType, SourceLocation(),
2431 SourceLocation()));
2432 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2433 &ProtoExprs[0],
2434 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002435 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002436 delete Exp;
2437 return ProtoExp;
2438
2439}
2440
Steve Naroffbaf58c32008-05-31 14:15:04 +00002441bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2442 const char *endBuf) {
2443 while (startBuf < endBuf) {
2444 if (*startBuf == '#') {
2445 // Skip whitespace.
2446 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2447 ;
2448 if (!strncmp(startBuf, "if", strlen("if")) ||
2449 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2450 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2451 !strncmp(startBuf, "define", strlen("define")) ||
2452 !strncmp(startBuf, "undef", strlen("undef")) ||
2453 !strncmp(startBuf, "else", strlen("else")) ||
2454 !strncmp(startBuf, "elif", strlen("elif")) ||
2455 !strncmp(startBuf, "endif", strlen("endif")) ||
2456 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2457 !strncmp(startBuf, "include", strlen("include")) ||
2458 !strncmp(startBuf, "import", strlen("import")) ||
2459 !strncmp(startBuf, "include_next", strlen("include_next")))
2460 return true;
2461 }
2462 startBuf++;
2463 }
2464 return false;
2465}
2466
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002467/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002468/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002469void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002470 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002471 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002472 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002473 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002474 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002475 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002476 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002477 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002478 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002479 SourceLocation LocStart = CDecl->getLocStart();
2480 SourceLocation LocEnd = CDecl->getLocEnd();
2481
2482 const char *startBuf = SM->getCharacterData(LocStart);
2483 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002484
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002485 // If no ivars and no root or if its root, directly or indirectly,
2486 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002487 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2488 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002489 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002490 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002491 return;
2492 }
2493
2494 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002495 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002496 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002497 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002498 if (LangOpts.Microsoft)
2499 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002500
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002501 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002502 const char *cursor = strchr(startBuf, '{');
2503 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002504 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002505 // If the buffer contains preprocessor directives, we do more fine-grained
2506 // rewrites. This is intended to fix code that looks like (which occurs in
2507 // NSURL.h, for example):
2508 //
2509 // #ifdef XYZ
2510 // @interface Foo : NSObject
2511 // #else
2512 // @interface FooBar : NSObject
2513 // #endif
2514 // {
2515 // int i;
2516 // }
2517 // @end
2518 //
2519 // This clause is segregated to avoid breaking the common case.
2520 if (BufferContainsPPDirectives(startBuf, cursor)) {
2521 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2522 CDecl->getClassLoc();
2523 const char *endHeader = SM->getCharacterData(L);
2524 endHeader += Lexer::MeasureTokenLength(L, *SM);
2525
Chris Lattner3db6cae2008-07-21 18:19:38 +00002526 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002527 // advance to the end of the referenced protocols.
2528 while (endHeader < cursor && *endHeader != '>') endHeader++;
2529 endHeader++;
2530 }
2531 // rewrite the original header
2532 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2533 } else {
2534 // rewrite the original header *without* disturbing the '{'
2535 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2536 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002537 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002538 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002539 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002540 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002541 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002542 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002543
2544 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002545 SourceLocation OnePastCurly =
2546 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2547 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002548 }
2549 cursor++; // past '{'
2550
2551 // Now comment out any visibility specifiers.
2552 while (cursor < endBuf) {
2553 if (*cursor == '@') {
2554 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002555 // Skip whitespace.
2556 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2557 /*scan*/;
2558
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002559 // FIXME: presence of @public, etc. inside comment results in
2560 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002561 if (!strncmp(cursor, "public", strlen("public")) ||
2562 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002563 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002564 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002565 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002566 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002567 // FIXME: If there are cases where '<' is used in ivar declaration part
2568 // of user code, then scan the ivar list and use needToScanForQualifiers
2569 // for type checking.
2570 else if (*cursor == '<') {
2571 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002572 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002573 cursor = strchr(cursor, '>');
2574 cursor++;
2575 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002576 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002577 } else if (*cursor == '^') { // rewrite block specifier.
2578 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2579 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002580 }
Steve Narofffea763e82007-11-14 19:25:57 +00002581 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002582 }
Steve Narofffea763e82007-11-14 19:25:57 +00002583 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002584 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002585 } else { // we don't have any instance variables - insert super struct.
2586 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2587 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002588 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002589 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002590 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002591 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002592 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002593 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002594 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002595 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002596 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002597}
2598
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002599// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002600/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002601void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002602 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002603 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002604 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002605 const char *ClassName,
2606 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002607 if (MethodBegin == MethodEnd) return;
2608
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002609 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002610 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002611 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002612 SEL _cmd;
2613 char *method_types;
2614 void *_imp;
2615 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002616 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002617 Result += "\nstruct _objc_method {\n";
2618 Result += "\tSEL _cmd;\n";
2619 Result += "\tchar *method_types;\n";
2620 Result += "\tvoid *_imp;\n";
2621 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002622
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002623 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002624 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002625
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002626 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002627
2628 /* struct {
2629 struct _objc_method_list *next_method;
2630 int method_count;
2631 struct _objc_method method_list[];
2632 }
2633 */
2634 Result += "\nstatic struct {\n";
2635 Result += "\tstruct _objc_method_list *next_method;\n";
2636 Result += "\tint method_count;\n";
2637 Result += "\tstruct _objc_method method_list[";
2638 Result += utostr(MethodEnd-MethodBegin);
2639 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002640 Result += prefix;
2641 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2642 Result += "_METHODS_";
2643 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002644 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002645 Result += IsInstanceMethod ? "inst" : "cls";
2646 Result += "_meth\")))= ";
2647 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002648
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002649 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002650 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002651 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002652 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002653 Result += "\", \"";
2654 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002655 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002656 Result += MethodInternalNames[*MethodBegin];
2657 Result += "}\n";
2658 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2659 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002660 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002661 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002662 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002663 Result += "\", \"";
2664 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002665 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002666 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002667 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002668 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002669 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002670}
2671
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002672/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002673void RewriteObjC::
2674RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2675 const char *prefix,
2676 const char *ClassName,
2677 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002678 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002679 if (Protocols.empty()) return;
2680
2681 for (unsigned i = 0; i != Protocols.size(); i++) {
2682 ObjCProtocolDecl *PDecl = Protocols[i];
2683 // Output struct protocol_methods holder of method selector and type.
2684 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2685 /* struct protocol_methods {
2686 SEL _cmd;
2687 char *method_types;
2688 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002689 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002690 Result += "\nstruct protocol_methods {\n";
2691 Result += "\tSEL _cmd;\n";
2692 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002693 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002694
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002695 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002696 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002697 // Do not synthesize the protocol more than once.
2698 if (ObjCSynthesizedProtocols.count(PDecl))
2699 continue;
2700
2701 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2702 unsigned NumMethods = PDecl->getNumInstanceMethods();
2703 /* struct _objc_protocol_method_list {
2704 int protocol_method_count;
2705 struct protocol_methods protocols[];
2706 }
2707 */
2708 Result += "\nstatic struct {\n";
2709 Result += "\tint protocol_method_count;\n";
2710 Result += "\tstruct protocol_methods protocols[";
2711 Result += utostr(NumMethods);
2712 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002713 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002714 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2715 "{\n\t" + utostr(NumMethods) + "\n";
2716
2717 // Output instance methods declared in this protocol.
2718 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2719 E = PDecl->instmeth_end(); I != E; ++I) {
2720 if (I == PDecl->instmeth_begin())
2721 Result += "\t ,{{(SEL)\"";
2722 else
2723 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002724 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002725 std::string MethodTypeString;
2726 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2727 Result += "\", \"";
2728 Result += MethodTypeString;
2729 Result += "\"}\n";
2730 }
2731 Result += "\t }\n};\n";
2732 }
2733
2734 // Output class methods declared in this protocol.
2735 int NumMethods = PDecl->getNumClassMethods();
2736 if (NumMethods > 0) {
2737 /* struct _objc_protocol_method_list {
2738 int protocol_method_count;
2739 struct protocol_methods protocols[];
2740 }
2741 */
2742 Result += "\nstatic struct {\n";
2743 Result += "\tint protocol_method_count;\n";
2744 Result += "\tstruct protocol_methods protocols[";
2745 Result += utostr(NumMethods);
2746 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002747 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002748 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2749 "{\n\t";
2750 Result += utostr(NumMethods);
2751 Result += "\n";
2752
2753 // Output instance methods declared in this protocol.
2754 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2755 E = PDecl->classmeth_end(); I != E; ++I) {
2756 if (I == PDecl->classmeth_begin())
2757 Result += "\t ,{{(SEL)\"";
2758 else
2759 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002760 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002761 std::string MethodTypeString;
2762 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2763 Result += "\", \"";
2764 Result += MethodTypeString;
2765 Result += "\"}\n";
2766 }
2767 Result += "\t }\n};\n";
2768 }
2769
2770 // Output:
2771 /* struct _objc_protocol {
2772 // Objective-C 1.0 extensions
2773 struct _objc_protocol_extension *isa;
2774 char *protocol_name;
2775 struct _objc_protocol **protocol_list;
2776 struct _objc_protocol_method_list *instance_methods;
2777 struct _objc_protocol_method_list *class_methods;
2778 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002779 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002780 static bool objc_protocol = false;
2781 if (!objc_protocol) {
2782 Result += "\nstruct _objc_protocol {\n";
2783 Result += "\tstruct _objc_protocol_extension *isa;\n";
2784 Result += "\tchar *protocol_name;\n";
2785 Result += "\tstruct _objc_protocol **protocol_list;\n";
2786 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2787 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2788 Result += "};\n";
2789
2790 objc_protocol = true;
2791 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002792
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002793 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002794 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002795 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2796 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002797 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002798 Result += "\", 0, ";
2799 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2800 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002801 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002802 Result += ", ";
2803 }
2804 else
2805 Result += "0, ";
2806 if (PDecl->getNumClassMethods() > 0) {
2807 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002808 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002809 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002810 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002811 else
2812 Result += "0\n";
2813 Result += "};\n";
2814
2815 // Mark this protocol as having been generated.
2816 if (!ObjCSynthesizedProtocols.insert(PDecl))
2817 assert(false && "protocol already synthesized");
2818 }
2819 // Output the top lovel protocol meta-data for the class.
2820 /* struct _objc_protocol_list {
2821 struct _objc_protocol_list *next;
2822 int protocol_count;
2823 struct _objc_protocol *class_protocols[];
2824 }
2825 */
2826 Result += "\nstatic struct {\n";
2827 Result += "\tstruct _objc_protocol_list *next;\n";
2828 Result += "\tint protocol_count;\n";
2829 Result += "\tstruct _objc_protocol *class_protocols[";
2830 Result += utostr(Protocols.size());
2831 Result += "];\n} _OBJC_";
2832 Result += prefix;
2833 Result += "_PROTOCOLS_";
2834 Result += ClassName;
2835 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2836 "{\n\t0, ";
2837 Result += utostr(Protocols.size());
2838 Result += "\n";
2839
2840 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002841 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002842 Result += " \n";
2843
2844 for (unsigned i = 1; i != Protocols.size(); i++) {
2845 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002846 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002847 Result += "\n";
2848 }
2849 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002850}
2851
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002852/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002853/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002854void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002855 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002856 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002857 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002858 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002859 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2860 CDecl = CDecl->getNextClassCategory())
2861 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2862 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002863
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002864 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002865 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002866 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002867
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002868 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002869 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002870 true, "CATEGORY_", FullCategoryName.c_str(),
2871 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002872
2873 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002874 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002875 false, "CATEGORY_", FullCategoryName.c_str(),
2876 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002877
2878 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002879 // Null CDecl is case of a category implementation with no category interface
2880 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002881 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002882 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002883
2884 /* struct _objc_category {
2885 char *category_name;
2886 char *class_name;
2887 struct _objc_method_list *instance_methods;
2888 struct _objc_method_list *class_methods;
2889 struct _objc_protocol_list *protocols;
2890 // Objective-C 1.0 extensions
2891 uint32_t size; // sizeof (struct _objc_category)
2892 struct _objc_property_list *instance_properties; // category's own
2893 // @property decl.
2894 };
2895 */
2896
2897 static bool objc_category = false;
2898 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002899 Result += "\nstruct _objc_category {\n";
2900 Result += "\tchar *category_name;\n";
2901 Result += "\tchar *class_name;\n";
2902 Result += "\tstruct _objc_method_list *instance_methods;\n";
2903 Result += "\tstruct _objc_method_list *class_methods;\n";
2904 Result += "\tstruct _objc_protocol_list *protocols;\n";
2905 Result += "\tunsigned int size;\n";
2906 Result += "\tstruct _objc_property_list *instance_properties;\n";
2907 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002908 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002909 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002910 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2911 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002912 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002913 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002914 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002915 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002916 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002917
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002918 if (IDecl->getNumInstanceMethods() > 0) {
2919 Result += "\t, (struct _objc_method_list *)"
2920 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2921 Result += FullCategoryName;
2922 Result += "\n";
2923 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002924 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002925 Result += "\t, 0\n";
2926 if (IDecl->getNumClassMethods() > 0) {
2927 Result += "\t, (struct _objc_method_list *)"
2928 "&_OBJC_CATEGORY_CLASS_METHODS_";
2929 Result += FullCategoryName;
2930 Result += "\n";
2931 }
2932 else
2933 Result += "\t, 0\n";
2934
Chris Lattner780f3292008-07-21 21:32:27 +00002935 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002936 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2937 Result += FullCategoryName;
2938 Result += "\n";
2939 }
2940 else
2941 Result += "\t, 0\n";
2942 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002943}
2944
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002945/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2946/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002947void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002948 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002949 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002950 if (ivar->isBitField()) {
2951 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2952 // place all bitfields at offset 0.
2953 Result += "0";
2954 } else {
2955 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002956 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002957 if (LangOpts.Microsoft)
2958 Result += "_IMPL";
2959 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002960 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002961 Result += ")";
2962 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002963}
2964
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002965//===----------------------------------------------------------------------===//
2966// Meta Data Emission
2967//===----------------------------------------------------------------------===//
2968
Steve Naroffb29b4272008-04-14 22:03:09 +00002969void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002970 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002971 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002972
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002973 // Explictly declared @interface's are already synthesized.
2974 if (CDecl->ImplicitInterfaceDecl()) {
2975 // FIXME: Implementation of a class with no @interface (legacy) doese not
2976 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002977 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002978 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002979
Chris Lattnerbe6df082007-12-12 07:56:42 +00002980 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002981 unsigned NumIvars = !IDecl->ivar_empty()
2982 ? IDecl->ivar_size()
2983 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002984 if (NumIvars > 0) {
2985 static bool objc_ivar = false;
2986 if (!objc_ivar) {
2987 /* struct _objc_ivar {
2988 char *ivar_name;
2989 char *ivar_type;
2990 int ivar_offset;
2991 };
2992 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002993 Result += "\nstruct _objc_ivar {\n";
2994 Result += "\tchar *ivar_name;\n";
2995 Result += "\tchar *ivar_type;\n";
2996 Result += "\tint ivar_offset;\n";
2997 Result += "};\n";
2998
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002999 objc_ivar = true;
3000 }
3001
Steve Naroff946a6932008-03-11 00:12:29 +00003002 /* struct {
3003 int ivar_count;
3004 struct _objc_ivar ivar_list[nIvars];
3005 };
3006 */
3007 Result += "\nstatic struct {\n";
3008 Result += "\tint ivar_count;\n";
3009 Result += "\tstruct _objc_ivar ivar_list[";
3010 Result += utostr(NumIvars);
3011 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003012 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003013 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003014 "{\n\t";
3015 Result += utostr(NumIvars);
3016 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003017
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003018 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003019 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003020 IVI = IDecl->ivar_begin();
3021 IVE = IDecl->ivar_end();
3022 } else {
3023 IVI = CDecl->ivar_begin();
3024 IVE = CDecl->ivar_end();
3025 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003026 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003027 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003028 Result += "\", \"";
3029 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003030 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003031 Result += StrEncoding;
3032 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003033 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003034 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003035 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003036 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003037 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003038 Result += "\", \"";
3039 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003040 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003041 Result += StrEncoding;
3042 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003043 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003044 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003045 }
3046
3047 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003048 }
3049
3050 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003051 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003052 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003053
3054 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003055 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003056 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003057
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003058 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003059 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003060 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003061
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003062
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003063 // Declaration of class/meta-class metadata
3064 /* struct _objc_class {
3065 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003066 const char *super_class_name;
3067 char *name;
3068 long version;
3069 long info;
3070 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003071 struct _objc_ivar_list *ivars;
3072 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003073 struct objc_cache *cache;
3074 struct objc_protocol_list *protocols;
3075 const char *ivar_layout;
3076 struct _objc_class_ext *ext;
3077 };
3078 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003079 static bool objc_class = false;
3080 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003081 Result += "\nstruct _objc_class {\n";
3082 Result += "\tstruct _objc_class *isa;\n";
3083 Result += "\tconst char *super_class_name;\n";
3084 Result += "\tchar *name;\n";
3085 Result += "\tlong version;\n";
3086 Result += "\tlong info;\n";
3087 Result += "\tlong instance_size;\n";
3088 Result += "\tstruct _objc_ivar_list *ivars;\n";
3089 Result += "\tstruct _objc_method_list *methods;\n";
3090 Result += "\tstruct objc_cache *cache;\n";
3091 Result += "\tstruct _objc_protocol_list *protocols;\n";
3092 Result += "\tconst char *ivar_layout;\n";
3093 Result += "\tstruct _objc_class_ext *ext;\n";
3094 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003095 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003096 }
3097
3098 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003099 ObjCInterfaceDecl *RootClass = 0;
3100 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003101 while (SuperClass) {
3102 RootClass = SuperClass;
3103 SuperClass = SuperClass->getSuperClass();
3104 }
3105 SuperClass = CDecl->getSuperClass();
3106
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003107 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003108 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003109 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003110 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003111 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003112 Result += "\"";
3113
3114 if (SuperClass) {
3115 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003116 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003117 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003118 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003119 Result += "\"";
3120 }
3121 else {
3122 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003123 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003124 Result += "\"";
3125 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003126 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003127 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003128 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003129 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003130 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003131 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003132 Result += "\n";
3133 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003134 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003135 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003136 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003137 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003138 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003139 Result += ",0,0\n";
3140 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003141 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003142 Result += "\t,0,0,0,0\n";
3143 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003144
3145 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003146 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003147 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003148 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003149 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003150 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003151 if (SuperClass) {
3152 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003153 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003154 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003155 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003156 Result += "\"";
3157 }
3158 else {
3159 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003160 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003161 Result += "\"";
3162 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003163 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003164 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003165 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003166 Result += ",0";
3167 else {
3168 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003169 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003170 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003171 if (LangOpts.Microsoft)
3172 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003173 Result += ")";
3174 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003175 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003176 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003177 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003178 Result += "\n\t";
3179 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003180 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003181 Result += ",0";
3182 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003183 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003184 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003185 Result += ", 0\n\t";
3186 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003187 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003188 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003189 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003190 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003191 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003192 Result += ", 0,0\n";
3193 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003194 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003195 Result += ",0,0,0\n";
3196 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003197}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003198
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003199/// RewriteImplementations - This routine rewrites all method implementations
3200/// and emits meta-data.
3201
Steve Narofface66252008-11-13 20:07:04 +00003202void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003203 int ClsDefCount = ClassImplementation.size();
3204 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003205
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003206 // Rewrite implemented methods
3207 for (int i = 0; i < ClsDefCount; i++)
3208 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003209
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003210 for (int i = 0; i < CatDefCount; i++)
3211 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003212}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003213
Steve Narofface66252008-11-13 20:07:04 +00003214void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3215 int ClsDefCount = ClassImplementation.size();
3216 int CatDefCount = CategoryImplementation.size();
3217
Steve Naroff5df5b762008-05-07 21:23:49 +00003218 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003219 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003220 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003221 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003222 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003223
3224 // For each implemented category, write out all its meta data.
3225 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003226 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003227
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003228 // Write objc_symtab metadata
3229 /*
3230 struct _objc_symtab
3231 {
3232 long sel_ref_cnt;
3233 SEL *refs;
3234 short cls_def_cnt;
3235 short cat_def_cnt;
3236 void *defs[cls_def_cnt + cat_def_cnt];
3237 };
3238 */
3239
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003240 Result += "\nstruct _objc_symtab {\n";
3241 Result += "\tlong sel_ref_cnt;\n";
3242 Result += "\tSEL *refs;\n";
3243 Result += "\tshort cls_def_cnt;\n";
3244 Result += "\tshort cat_def_cnt;\n";
3245 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3246 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003247
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003248 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003249 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003250 Result += "\t0, 0, " + utostr(ClsDefCount)
3251 + ", " + utostr(CatDefCount) + "\n";
3252 for (int i = 0; i < ClsDefCount; i++) {
3253 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003254 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003255 Result += "\n";
3256 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003257
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003258 for (int i = 0; i < CatDefCount; i++) {
3259 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003260 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003261 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003262 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003263 Result += "\n";
3264 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003265
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003266 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003267
3268 // Write objc_module metadata
3269
3270 /*
3271 struct _objc_module {
3272 long version;
3273 long size;
3274 const char *name;
3275 struct _objc_symtab *symtab;
3276 }
3277 */
3278
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003279 Result += "\nstruct _objc_module {\n";
3280 Result += "\tlong version;\n";
3281 Result += "\tlong size;\n";
3282 Result += "\tconst char *name;\n";
3283 Result += "\tstruct _objc_symtab *symtab;\n";
3284 Result += "};\n\n";
3285 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003286 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003287 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3288 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003289 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003290
3291 if (LangOpts.Microsoft) {
3292 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003293 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003294 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3295 Result += "&_OBJC_MODULES;\n";
3296 Result += "#pragma data_seg(pop)\n\n";
3297 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003298}
Chris Lattner311ff022007-10-16 22:36:42 +00003299
Steve Naroff54055232008-10-27 17:20:55 +00003300std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3301 const char *funcName,
3302 std::string Tag) {
3303 const FunctionType *AFT = CE->getFunctionType();
3304 QualType RT = AFT->getResultType();
3305 std::string StructRef = "struct " + Tag;
3306 std::string S = "static " + RT.getAsString() + " __" +
3307 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003308
Steve Naroff54055232008-10-27 17:20:55 +00003309 BlockDecl *BD = CE->getBlockDecl();
3310
3311 if (isa<FunctionTypeNoProto>(AFT)) {
3312 S += "()";
3313 } else if (BD->param_empty()) {
3314 S += "(" + StructRef + " *__cself)";
3315 } else {
3316 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3317 assert(FT && "SynthesizeBlockFunc: No function proto");
3318 S += '(';
3319 // first add the implicit argument.
3320 S += StructRef + " *__cself, ";
3321 std::string ParamStr;
3322 for (BlockDecl::param_iterator AI = BD->param_begin(),
3323 E = BD->param_end(); AI != E; ++AI) {
3324 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003325 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003326 (*AI)->getType().getAsStringInternal(ParamStr);
3327 S += ParamStr;
3328 }
3329 if (FT->isVariadic()) {
3330 if (!BD->param_empty()) S += ", ";
3331 S += "...";
3332 }
3333 S += ')';
3334 }
3335 S += " {\n";
3336
3337 // Create local declarations to avoid rewriting all closure decl ref exprs.
3338 // First, emit a declaration for all "by ref" decls.
3339 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3340 E = BlockByRefDecls.end(); I != E; ++I) {
3341 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003342 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003343 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003344 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003345 }
3346 // Next, emit a declaration for all "by copy" declarations.
3347 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3348 E = BlockByCopyDecls.end(); I != E; ++I) {
3349 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003350 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003351 // Handle nested closure invocation. For example:
3352 //
3353 // void (^myImportedClosure)(void);
3354 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3355 //
3356 // void (^anotherClosure)(void);
3357 // anotherClosure = ^(void) {
3358 // myImportedClosure(); // import and invoke the closure
3359 // };
3360 //
3361 if (isBlockPointerType((*I)->getType()))
3362 S += "struct __block_impl *";
3363 else
3364 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003365 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003366 }
3367 std::string RewrittenStr = RewrittenBlockExprs[CE];
3368 const char *cstr = RewrittenStr.c_str();
3369 while (*cstr++ != '{') ;
3370 S += cstr;
3371 S += "\n";
3372 return S;
3373}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003374
Steve Naroff54055232008-10-27 17:20:55 +00003375std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3376 const char *funcName,
3377 std::string Tag) {
3378 std::string StructRef = "struct " + Tag;
3379 std::string S = "static void __";
3380
3381 S += funcName;
3382 S += "_block_copy_" + utostr(i);
3383 S += "(" + StructRef;
3384 S += "*dst, " + StructRef;
3385 S += "*src) {";
3386 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3387 E = ImportedBlockDecls.end(); I != E; ++I) {
3388 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003389 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003390 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003391 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003392 S += ");}";
3393 }
3394 S += "\nstatic void __";
3395 S += funcName;
3396 S += "_block_dispose_" + utostr(i);
3397 S += "(" + StructRef;
3398 S += "*src) {";
3399 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3400 E = ImportedBlockDecls.end(); I != E; ++I) {
3401 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003402 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003403 S += ");";
3404 }
3405 S += "}\n";
3406 return S;
3407}
3408
3409std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3410 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003411 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003412 std::string Constructor = " " + Tag;
3413
3414 S += " {\n struct __block_impl impl;\n";
3415
3416 if (hasCopyDisposeHelpers)
3417 S += " void *copy;\n void *dispose;\n";
3418
3419 Constructor += "(void *fp";
3420
3421 if (hasCopyDisposeHelpers)
3422 Constructor += ", void *copyHelp, void *disposeHelp";
3423
3424 if (BlockDeclRefs.size()) {
3425 // Output all "by copy" declarations.
3426 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3427 E = BlockByCopyDecls.end(); I != E; ++I) {
3428 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003429 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003430 std::string ArgName = "_" + FieldName;
3431 // Handle nested closure invocation. For example:
3432 //
3433 // void (^myImportedBlock)(void);
3434 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3435 //
3436 // void (^anotherBlock)(void);
3437 // anotherBlock = ^(void) {
3438 // myImportedBlock(); // import and invoke the closure
3439 // };
3440 //
3441 if (isBlockPointerType((*I)->getType())) {
3442 S += "struct __block_impl *";
3443 Constructor += ", void *" + ArgName;
3444 } else {
3445 (*I)->getType().getAsStringInternal(FieldName);
3446 (*I)->getType().getAsStringInternal(ArgName);
3447 Constructor += ", " + ArgName;
3448 }
3449 S += FieldName + ";\n";
3450 }
3451 // Output all "by ref" declarations.
3452 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3453 E = BlockByRefDecls.end(); I != E; ++I) {
3454 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003455 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003456 std::string ArgName = "_" + FieldName;
3457 // Handle nested closure invocation. For example:
3458 //
3459 // void (^myImportedBlock)(void);
3460 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3461 //
3462 // void (^anotherBlock)(void);
3463 // anotherBlock = ^(void) {
3464 // myImportedBlock(); // import and invoke the closure
3465 // };
3466 //
3467 if (isBlockPointerType((*I)->getType())) {
3468 S += "struct __block_impl *";
3469 Constructor += ", void *" + ArgName;
3470 } else {
3471 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3472 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3473 Constructor += ", " + ArgName;
3474 }
3475 S += FieldName + "; // by ref\n";
3476 }
3477 // Finish writing the constructor.
3478 // FIXME: handle NSConcreteGlobalBlock.
3479 Constructor += ", int flags=0) {\n";
3480 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3481 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3482
3483 if (hasCopyDisposeHelpers)
3484 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3485
3486 // Initialize all "by copy" arguments.
3487 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3488 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003489 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003490 Constructor += " ";
3491 if (isBlockPointerType((*I)->getType()))
3492 Constructor += Name + " = (struct __block_impl *)_";
3493 else
3494 Constructor += Name + " = _";
3495 Constructor += Name + ";\n";
3496 }
3497 // Initialize all "by ref" arguments.
3498 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3499 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003500 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003501 Constructor += " ";
3502 if (isBlockPointerType((*I)->getType()))
3503 Constructor += Name + " = (struct __block_impl *)_";
3504 else
3505 Constructor += Name + " = _";
3506 Constructor += Name + ";\n";
3507 }
3508 } else {
3509 // Finish writing the constructor.
3510 // FIXME: handle NSConcreteGlobalBlock.
3511 Constructor += ", int flags=0) {\n";
3512 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3513 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3514 if (hasCopyDisposeHelpers)
3515 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3516 }
3517 Constructor += " ";
3518 Constructor += "}\n";
3519 S += Constructor;
3520 S += "};\n";
3521 return S;
3522}
3523
3524void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3525 const char *FunName) {
3526 // Insert closures that were part of the function.
3527 for (unsigned i = 0; i < Blocks.size(); i++) {
3528
3529 CollectBlockDeclRefInfo(Blocks[i]);
3530
3531 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3532
3533 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3534 ImportedBlockDecls.size() > 0);
3535
3536 InsertText(FunLocStart, CI.c_str(), CI.size());
3537
3538 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3539
3540 InsertText(FunLocStart, CF.c_str(), CF.size());
3541
3542 if (ImportedBlockDecls.size()) {
3543 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3544 InsertText(FunLocStart, HF.c_str(), HF.size());
3545 }
3546
3547 BlockDeclRefs.clear();
3548 BlockByRefDecls.clear();
3549 BlockByCopyDecls.clear();
3550 BlockCallExprs.clear();
3551 ImportedBlockDecls.clear();
3552 }
3553 Blocks.clear();
3554 RewrittenBlockExprs.clear();
3555}
3556
3557void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3558 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003559 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003560
3561 SynthesizeBlockLiterals(FunLocStart, FuncName);
3562}
3563
3564void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003565 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3566 //SourceLocation FunLocStart = MD->getLocStart();
3567 // FIXME: This hack works around a bug in Rewrite.InsertText().
3568 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003569 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003570 // Convert colons to underscores.
3571 std::string::size_type loc = 0;
3572 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3573 FuncName.replace(loc, 1, "_");
3574
3575 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3576}
3577
3578void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3579 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3580 CI != E; ++CI)
3581 if (*CI) {
3582 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3583 GetBlockDeclRefExprs(CBE->getBody());
3584 else
3585 GetBlockDeclRefExprs(*CI);
3586 }
3587 // Handle specific things.
3588 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3589 // FIXME: Handle enums.
3590 if (!isa<FunctionDecl>(CDRE->getDecl()))
3591 BlockDeclRefs.push_back(CDRE);
3592 return;
3593}
3594
3595void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3596 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3597 CI != E; ++CI)
3598 if (*CI) {
3599 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3600 GetBlockCallExprs(CBE->getBody());
3601 else
3602 GetBlockCallExprs(*CI);
3603 }
3604
3605 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3606 if (CE->getCallee()->getType()->isBlockPointerType()) {
3607 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3608 }
3609 }
3610 return;
3611}
3612
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003613Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003614 // Navigate to relevant type information.
3615 const char *closureName = 0;
3616 const BlockPointerType *CPT = 0;
3617
3618 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003619 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003620 CPT = DRE->getType()->getAsBlockPointerType();
3621 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003622 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003623 CPT = CDRE->getType()->getAsBlockPointerType();
3624 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003625 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003626 CPT = MExpr->getType()->getAsBlockPointerType();
3627 } else {
3628 assert(1 && "RewriteBlockClass: Bad type");
3629 }
3630 assert(CPT && "RewriteBlockClass: Bad type");
3631 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3632 assert(FT && "RewriteBlockClass: Bad type");
3633 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3634 // FTP will be null for closures that don't take arguments.
3635
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003636 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3637 SourceLocation(),
3638 &Context->Idents.get("__block_impl"));
3639 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003640
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003641 // Generate a funky cast.
3642 llvm::SmallVector<QualType, 8> ArgTypes;
3643
3644 // Push the block argument type.
3645 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003646 if (FTP) {
3647 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003648 E = FTP->arg_type_end(); I && (I != E); ++I) {
3649 QualType t = *I;
3650 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3651 if (isBlockPointerType(t)) {
3652 const BlockPointerType *BPT = t->getAsBlockPointerType();
3653 t = Context->getPointerType(BPT->getPointeeType());
3654 }
3655 ArgTypes.push_back(t);
3656 }
Steve Naroff54055232008-10-27 17:20:55 +00003657 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003658 // Now do the pointer to function cast.
3659 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3660 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3661
3662 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003663
Steve Naroffb2f9e512008-11-03 23:29:32 +00003664 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003665 // Don't forget the parens to enforce the proper binding.
3666 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3667 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003668
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003669 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3670 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3671 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3672
Steve Naroffb2f9e512008-11-03 23:29:32 +00003673 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003674 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3675
3676 llvm::SmallVector<Expr*, 8> BlkExprs;
3677 // Add the implicit argument.
3678 BlkExprs.push_back(BlkCast);
3679 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003680 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3681 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003682 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003683 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003684 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3685 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003686}
3687
3688void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003689 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3690 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003691}
3692
3693void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3694 // FIXME: Add more elaborate code generation required by the ABI.
3695 InsertText(BDRE->getLocStart(), "*", 1);
3696}
3697
Steve Naroffb2f9e512008-11-03 23:29:32 +00003698void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3699 SourceLocation LocStart = CE->getLParenLoc();
3700 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003701
3702 // Need to avoid trying to rewrite synthesized casts.
3703 if (LocStart.isInvalid())
3704 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003705 // Need to avoid trying to rewrite casts contained in macros.
3706 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3707 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003708
Steve Naroff54055232008-10-27 17:20:55 +00003709 const char *startBuf = SM->getCharacterData(LocStart);
3710 const char *endBuf = SM->getCharacterData(LocEnd);
3711
3712 // advance the location to startArgList.
3713 const char *argPtr = startBuf;
3714
3715 while (*argPtr++ && (argPtr < endBuf)) {
3716 switch (*argPtr) {
3717 case '^':
3718 // Replace the '^' with '*'.
3719 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3720 ReplaceText(LocStart, 1, "*", 1);
3721 break;
3722 }
3723 }
3724 return;
3725}
3726
3727void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3728 SourceLocation DeclLoc = FD->getLocation();
3729 unsigned parenCount = 0;
3730
3731 // We have 1 or more arguments that have closure pointers.
3732 const char *startBuf = SM->getCharacterData(DeclLoc);
3733 const char *startArgList = strchr(startBuf, '(');
3734
3735 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3736
3737 parenCount++;
3738 // advance the location to startArgList.
3739 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3740 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3741
3742 const char *argPtr = startArgList;
3743
3744 while (*argPtr++ && parenCount) {
3745 switch (*argPtr) {
3746 case '^':
3747 // Replace the '^' with '*'.
3748 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3749 ReplaceText(DeclLoc, 1, "*", 1);
3750 break;
3751 case '(':
3752 parenCount++;
3753 break;
3754 case ')':
3755 parenCount--;
3756 break;
3757 }
3758 }
3759 return;
3760}
3761
3762bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3763 const FunctionTypeProto *FTP;
3764 const PointerType *PT = QT->getAsPointerType();
3765 if (PT) {
3766 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3767 } else {
3768 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3769 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3770 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3771 }
3772 if (FTP) {
3773 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3774 E = FTP->arg_type_end(); I != E; ++I)
3775 if (isBlockPointerType(*I))
3776 return true;
3777 }
3778 return false;
3779}
3780
3781void RewriteObjC::GetExtentOfArgList(const char *Name,
3782 const char *&LParen, const char *&RParen) {
3783 const char *argPtr = strchr(Name, '(');
3784 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3785
3786 LParen = argPtr; // output the start.
3787 argPtr++; // skip past the left paren.
3788 unsigned parenCount = 1;
3789
3790 while (*argPtr && parenCount) {
3791 switch (*argPtr) {
3792 case '(': parenCount++; break;
3793 case ')': parenCount--; break;
3794 default: break;
3795 }
3796 if (parenCount) argPtr++;
3797 }
3798 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3799 RParen = argPtr; // output the end
3800}
3801
3802void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3803 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3804 RewriteBlockPointerFunctionArgs(FD);
3805 return;
3806 }
3807 // Handle Variables and Typedefs.
3808 SourceLocation DeclLoc = ND->getLocation();
3809 QualType DeclT;
3810 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3811 DeclT = VD->getType();
3812 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3813 DeclT = TDD->getUnderlyingType();
3814 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3815 DeclT = FD->getType();
3816 else
3817 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3818
3819 const char *startBuf = SM->getCharacterData(DeclLoc);
3820 const char *endBuf = startBuf;
3821 // scan backward (from the decl location) for the end of the previous decl.
3822 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3823 startBuf--;
3824
3825 // *startBuf != '^' if we are dealing with a pointer to function that
3826 // may take block argument types (which will be handled below).
3827 if (*startBuf == '^') {
3828 // Replace the '^' with '*', computing a negative offset.
3829 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3830 ReplaceText(DeclLoc, 1, "*", 1);
3831 }
3832 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3833 // Replace the '^' with '*' for arguments.
3834 DeclLoc = ND->getLocation();
3835 startBuf = SM->getCharacterData(DeclLoc);
3836 const char *argListBegin, *argListEnd;
3837 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3838 while (argListBegin < argListEnd) {
3839 if (*argListBegin == '^') {
3840 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3841 ReplaceText(CaretLoc, 1, "*", 1);
3842 }
3843 argListBegin++;
3844 }
3845 }
3846 return;
3847}
3848
3849void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3850 // Add initializers for any closure decl refs.
3851 GetBlockDeclRefExprs(Exp->getBody());
3852 if (BlockDeclRefs.size()) {
3853 // Unique all "by copy" declarations.
3854 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3855 if (!BlockDeclRefs[i]->isByRef())
3856 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3857 // Unique all "by ref" declarations.
3858 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3859 if (BlockDeclRefs[i]->isByRef()) {
3860 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3861 }
3862 // Find any imported blocks...they will need special attention.
3863 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3864 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003865 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003866 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3867 }
3868 }
3869}
3870
Steve Narofffa15fd92008-10-28 20:29:00 +00003871FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3872 IdentifierInfo *ID = &Context->Idents.get(name);
3873 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3874 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3875 ID, FType, FunctionDecl::Extern, false, 0);
3876}
3877
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003878Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003879 Blocks.push_back(Exp);
3880
3881 CollectBlockDeclRefInfo(Exp);
3882 std::string FuncName;
3883
3884 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003885 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003886 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00003887 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003888 // Convert colons to underscores.
3889 std::string::size_type loc = 0;
3890 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3891 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003892 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003893 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00003894
3895 std::string BlockNumber = utostr(Blocks.size()-1);
3896
3897 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3898 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3899
3900 // Get a pointer to the function type so we can cast appropriately.
3901 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3902
3903 FunctionDecl *FD;
3904 Expr *NewRep;
3905
3906 // Simulate a contructor call...
3907 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3908 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3909
3910 llvm::SmallVector<Expr*, 4> InitExprs;
3911
Steve Narofffdc03722008-10-29 21:23:59 +00003912 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003913 FD = SynthBlockInitFunctionDecl(Func.c_str());
3914 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3915 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003916 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003917 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003918
3919 if (ImportedBlockDecls.size()) {
3920 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003921 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3922 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3923 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003924 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003925 InitExprs.push_back(castExpr);
3926
Steve Narofffa15fd92008-10-28 20:29:00 +00003927 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003928 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3929 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3930 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003931 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003932 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003933 }
3934 // Add initializers for any closure decl refs.
3935 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00003936 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00003937 // Output all "by copy" declarations.
3938 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3939 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003940 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003941 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00003942 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003943 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003944 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003945 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003946 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3947 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003948 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003949 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003950 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003951 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003952 }
Steve Narofffdc03722008-10-29 21:23:59 +00003953 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003954 }
3955 // Output all "by ref" declarations.
3956 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3957 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003958 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003959 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3960 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3961 Context->getPointerType(Exp->getType()),
3962 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00003963 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003964 }
3965 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003966 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3967 FType, SourceLocation());
3968 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3969 Context->getPointerType(NewRep->getType()),
3970 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00003971 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003972 BlockDeclRefs.clear();
3973 BlockByRefDecls.clear();
3974 BlockByCopyDecls.clear();
3975 ImportedBlockDecls.clear();
3976 return NewRep;
3977}
3978
3979//===----------------------------------------------------------------------===//
3980// Function Body / Expression rewriting
3981//===----------------------------------------------------------------------===//
3982
3983Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3984 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3985 isa<DoStmt>(S) || isa<ForStmt>(S))
3986 Stmts.push_back(S);
3987 else if (isa<ObjCForCollectionStmt>(S)) {
3988 Stmts.push_back(S);
3989 ObjCBcLabelNo.push_back(++BcLabelCount);
3990 }
3991
3992 SourceRange OrigStmtRange = S->getSourceRange();
3993
3994 // Perform a bottom up rewrite of all children.
3995 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3996 CI != E; ++CI)
3997 if (*CI) {
3998 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3999 if (newStmt)
4000 *CI = newStmt;
4001 }
4002
4003 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4004 // Rewrite the block body in place.
4005 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4006
4007 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004008 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4009 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004010
4011 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4012 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004013 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004014 return blockTranscribed;
4015 }
4016 // Handle specific things.
4017 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4018 return RewriteAtEncode(AtEncode);
4019
4020 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4021 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4022
Steve Naroff15f081d2008-12-03 00:56:33 +00004023 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S))
4024 return RewritePropertyRefExpr(PropRefExpr);
4025
4026 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4027 if (BinOp->isAssignmentOp()) {
4028 if (ObjCPropertyRefExpr *PRE = PropMsgExprs[BinOp->getLHS()])
4029 return RewritePropertySetter(BinOp, PRE);
4030 }
4031 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004032 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4033 return RewriteAtSelector(AtSelector);
4034
4035 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4036 return RewriteObjCStringLiteral(AtString);
4037
4038 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4039 // Before we rewrite it, put the original message expression in a comment.
4040 SourceLocation startLoc = MessExpr->getLocStart();
4041 SourceLocation endLoc = MessExpr->getLocEnd();
4042
4043 const char *startBuf = SM->getCharacterData(startLoc);
4044 const char *endBuf = SM->getCharacterData(endLoc);
4045
4046 std::string messString;
4047 messString += "// ";
4048 messString.append(startBuf, endBuf-startBuf+1);
4049 messString += "\n";
4050
4051 // FIXME: Missing definition of
4052 // InsertText(clang::SourceLocation, char const*, unsigned int).
4053 // InsertText(startLoc, messString.c_str(), messString.size());
4054 // Tried this, but it didn't work either...
4055 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4056 return RewriteMessageExpr(MessExpr);
4057 }
4058
4059 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4060 return RewriteObjCTryStmt(StmtTry);
4061
4062 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4063 return RewriteObjCSynchronizedStmt(StmtTry);
4064
4065 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4066 return RewriteObjCThrowStmt(StmtThrow);
4067
4068 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4069 return RewriteObjCProtocolExpr(ProtocolExp);
4070
4071 if (ObjCForCollectionStmt *StmtForCollection =
4072 dyn_cast<ObjCForCollectionStmt>(S))
4073 return RewriteObjCForCollectionStmt(StmtForCollection,
4074 OrigStmtRange.getEnd());
4075 if (BreakStmt *StmtBreakStmt =
4076 dyn_cast<BreakStmt>(S))
4077 return RewriteBreakStmt(StmtBreakStmt);
4078 if (ContinueStmt *StmtContinueStmt =
4079 dyn_cast<ContinueStmt>(S))
4080 return RewriteContinueStmt(StmtContinueStmt);
4081
4082 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4083 // and cast exprs.
4084 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4085 // FIXME: What we're doing here is modifying the type-specifier that
4086 // precedes the first Decl. In the future the DeclGroup should have
4087 // a separate type-specifier that we can rewrite.
4088 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4089
4090 // Blocks rewrite rules.
4091 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4092 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004093 ScopedDecl *SD = *DI;
4094 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4095 if (isBlockPointerType(ND->getType()))
4096 RewriteBlockPointerDecl(ND);
4097 else if (ND->getType()->isFunctionPointerType())
4098 CheckFunctionPointerDecl(ND->getType(), ND);
4099 }
4100 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4101 if (isBlockPointerType(TD->getUnderlyingType()))
4102 RewriteBlockPointerDecl(TD);
4103 else if (TD->getUnderlyingType()->isFunctionPointerType())
4104 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4105 }
4106 }
4107 }
4108
4109 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4110 RewriteObjCQualifiedInterfaceTypes(CE);
4111
4112 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4113 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4114 assert(!Stmts.empty() && "Statement stack is empty");
4115 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4116 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4117 && "Statement stack mismatch");
4118 Stmts.pop_back();
4119 }
4120 // Handle blocks rewriting.
4121 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4122 if (BDRE->isByRef())
4123 RewriteBlockDeclRefExpr(BDRE);
4124 }
4125 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004126 if (CE->getCallee()->getType()->isBlockPointerType()) {
4127 Stmt *BlockCall = SynthesizeBlockCall(CE);
4128 ReplaceStmt(S, BlockCall);
4129 return BlockCall;
4130 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004131 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004132 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004133 RewriteCastExpr(CE);
4134 }
4135#if 0
4136 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4137 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4138 // Get the new text.
4139 std::string SStr;
4140 llvm::raw_string_ostream Buf(SStr);
4141 Replacement->printPretty(Buf);
4142 const std::string &Str = Buf.str();
4143
4144 printf("CAST = %s\n", &Str[0]);
4145 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4146 delete S;
4147 return Replacement;
4148 }
4149#endif
4150 // Return this stmt unmodified.
4151 return S;
4152}
4153
4154/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4155/// main file of the input.
4156void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4157 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4158 // Since function prototypes don't have ParmDecl's, we check the function
4159 // prototype. This enables us to rewrite function declarations and
4160 // definitions using the same code.
4161 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4162
4163 if (Stmt *Body = FD->getBody()) {
4164 CurFunctionDef = FD;
4165 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4166 // This synthesizes and inserts the block "impl" struct, invoke function,
4167 // and any copy/dispose helper functions.
4168 InsertBlockLiteralsWithinFunction(FD);
4169 CurFunctionDef = 0;
4170 }
4171 return;
4172 }
4173 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4174 if (Stmt *Body = MD->getBody()) {
4175 //Body->dump();
4176 CurMethodDef = MD;
4177 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4178 InsertBlockLiteralsWithinMethod(MD);
4179 CurMethodDef = 0;
4180 }
4181 }
4182 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4183 ClassImplementation.push_back(CI);
4184 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4185 CategoryImplementation.push_back(CI);
4186 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4187 RewriteForwardClassDecl(CD);
4188 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4189 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004190 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004191 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004192 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004193 CheckFunctionPointerDecl(VD->getType(), VD);
4194 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004195 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004196 RewriteCastExpr(CE);
4197 }
4198 }
4199 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004200 if (VD->getInit()) {
4201 GlobalVarDecl = VD;
4202 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004203 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004204 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004205 GlobalVarDecl = 0;
4206
4207 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004208 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004209 RewriteCastExpr(CE);
4210 }
4211 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004212 return;
4213 }
4214 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4215 if (isBlockPointerType(TD->getUnderlyingType()))
4216 RewriteBlockPointerDecl(TD);
4217 else if (TD->getUnderlyingType()->isFunctionPointerType())
4218 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4219 return;
4220 }
4221 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4222 if (RD->isDefinition()) {
4223 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4224 e = RD->field_end(); i != e; ++i) {
4225 FieldDecl *FD = *i;
4226 if (isBlockPointerType(FD->getType()))
4227 RewriteBlockPointerDecl(FD);
4228 }
4229 }
4230 return;
4231 }
4232 // Nothing yet.
4233}
4234
4235void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4236 // Get the top-level buffer that this corresponds to.
4237
4238 // Rewrite tabs if we care.
4239 //RewriteTabs();
4240
4241 if (Diags.hasErrorOccurred())
4242 return;
4243
4244 // Create the output file.
4245
4246 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4247 llvm::raw_ostream *OutFile;
4248 if (OutFileName == "-") {
4249 OutFile = &llvm::outs();
4250 } else if (!OutFileName.empty()) {
4251 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004252 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004253 OwnedStream.reset(OutFile);
4254 } else if (InFileName == "-") {
4255 OutFile = &llvm::outs();
4256 } else {
4257 llvm::sys::Path Path(InFileName);
4258 Path.eraseSuffix();
4259 Path.appendSuffix("cpp");
4260 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004261 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004262 OwnedStream.reset(OutFile);
4263 }
4264
4265 RewriteInclude();
4266
4267 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4268 Preamble.c_str(), Preamble.size(), false);
4269
Steve Naroff0aab7962008-11-14 14:10:01 +00004270 if (ClassImplementation.size() || CategoryImplementation.size())
4271 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004272
4273 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4274 // we are done.
4275 if (const RewriteBuffer *RewriteBuf =
4276 Rewrite.getRewriteBufferFor(MainFileID)) {
4277 //printf("Changed:\n");
4278 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4279 } else {
4280 fprintf(stderr, "No changes\n");
4281 }
Steve Narofface66252008-11-13 20:07:04 +00004282
Steve Naroff0aab7962008-11-14 14:10:01 +00004283 if (ClassImplementation.size() || CategoryImplementation.size()) {
4284 // Rewrite Objective-c meta data*
4285 std::string ResultStr;
4286 SynthesizeMetaDataIntoBuffer(ResultStr);
4287 // Emit metadata.
4288 *OutFile << ResultStr;
4289 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004290 OutFile->flush();
4291}
4292