blob: 54882c392717387362157eb8f70b6618bbe3fe44 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Steve Naroff0113c9d2008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattner77cd2a02007-10-11 00:43:27 +000038namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattner01c57482007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000046 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000051
Ted Kremeneka526c5c2008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000083 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +000099
Steve Naroff54055232008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
Steve Naroffc77a6362008-12-04 16:24:46 +0000107 // This maps a property to it's assignment statement.
108 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
109 // This maps a property to the stmt it was rewritten to.
110 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Steve Naroff15f081d2008-12-03 00:56:33 +0000111
Steve Naroff54055232008-10-27 17:20:55 +0000112 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000113 VarDecl *GlobalVarDecl;
114
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000115 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000116 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000117 virtual void Initialize(ASTContext &context);
118
119 virtual void InitializeTU(TranslationUnit &TU) {
120 TU.SetOwnsDecls(false);
121 Initialize(TU.getContext());
122 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000123
Chris Lattner8a12c272007-10-11 18:38:32 +0000124
Chris Lattnerf04da132007-10-24 17:06:59 +0000125 // Top Level Driver code.
126 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000127 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000128 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000129 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000130
131 ~RewriteObjC() {}
132
133 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000134
135 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000136 // If replacement succeeded or warning disabled return with no warning.
137 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000138 return;
139
Chris Lattner0a14eee2008-11-18 07:04:44 +0000140 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
141 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000142 }
143
Steve Naroffba92b2e2008-03-27 22:29:16 +0000144 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
145 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000146 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000147 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000148 SilenceRewriteMacroWarning)
149 return;
150
151 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
152 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000153
Chris Lattneraadaf782008-01-31 19:51:04 +0000154 void RemoveText(SourceLocation Loc, unsigned StrLen) {
155 // If removal succeeded or warning disabled return with no warning.
156 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
157 return;
158
159 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
160 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000161
Chris Lattneraadaf782008-01-31 19:51:04 +0000162 void ReplaceText(SourceLocation Start, unsigned OrigLength,
163 const char *NewStr, unsigned NewLength) {
164 // If removal succeeded or warning disabled return with no warning.
165 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
166 SilenceRewriteMacroWarning)
167 return;
168
169 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
170 }
171
Chris Lattnerf04da132007-10-24 17:06:59 +0000172 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000173 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000174 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000175 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000176 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000177 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
178 ObjCImplementationDecl *IMD,
179 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000180 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000181 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000182 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
183 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
184 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
185 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
186 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000187 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000188 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000189 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000190 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000191 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000192 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000193 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000194 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000195 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000196
Chris Lattnerf04da132007-10-24 17:06:59 +0000197 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000198 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000199 void CollectPropertySetters(Stmt *S);
200
Chris Lattnere64b7772007-10-24 16:57:36 +0000201 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000202 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000203 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
204 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt);
Steve Naroffb42f8412007-11-05 14:50:49 +0000205 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000206 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000207 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000208 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000209 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000210 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000211 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
212 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
213 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000214 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
215 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000216 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
217 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000218 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000219 Stmt *RewriteBreakStmt(BreakStmt *S);
220 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000221 void SynthCountByEnumWithState(std::string &buf);
222
Steve Naroff09b266e2007-10-30 23:14:51 +0000223 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000224 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000225 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000226 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000227 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000228 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000229 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000230 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000231 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000232 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000233
Chris Lattnerf04da132007-10-24 17:06:59 +0000234 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000235 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000236 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000237
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000238 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000239 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000240
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000241 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
242 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000243 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000244 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000245 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000246 const char *ClassName,
247 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000248
Chris Lattner780f3292008-07-21 21:32:27 +0000249 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
250 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000251 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000252 const char *ClassName,
253 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000254 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000255 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000256 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
257 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000258 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000259 void RewriteImplementations();
260 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000261
262 // Block rewriting.
263 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
264 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
265
266 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
267 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
268
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000269 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000270 void RewriteBlockCall(CallExpr *Exp);
271 void RewriteBlockPointerDecl(NamedDecl *VD);
272 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
273 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
274
275 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
276 const char *funcName, std::string Tag);
277 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
278 const char *funcName, std::string Tag);
279 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
280 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000281 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000282 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
283 const char *FunName);
284
285 void CollectBlockDeclRefInfo(BlockExpr *Exp);
286 void GetBlockCallExprs(Stmt *S);
287 void GetBlockDeclRefExprs(Stmt *S);
288
289 // We avoid calling Type::isBlockPointerType(), since it operates on the
290 // canonical type. We only care if the top-level type is a closure pointer.
291 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
292
293 // FIXME: This predicate seems like it would be useful to add to ASTContext.
294 bool isObjCType(QualType T) {
295 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
296 return false;
297
298 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
299
300 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
301 OCT == Context->getCanonicalType(Context->getObjCClassType()))
302 return true;
303
304 if (const PointerType *PT = OCT->getAsPointerType()) {
305 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
306 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
307 return true;
308 }
309 return false;
310 }
311 bool PointerTypeTakesAnyBlockArguments(QualType QT);
312 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000313 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000314
315 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000316 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000317 };
318}
319
Steve Naroff54055232008-10-27 17:20:55 +0000320void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
321 NamedDecl *D) {
322 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
323 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
324 E = fproto->arg_type_end(); I && (I != E); ++I)
325 if (isBlockPointerType(*I)) {
326 // All the args are checked/rewritten. Don't call twice!
327 RewriteBlockPointerDecl(D);
328 break;
329 }
330 }
331}
332
333void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
334 const PointerType *PT = funcType->getAsPointerType();
335 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
336 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
337}
338
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000339static bool IsHeaderFile(const std::string &Filename) {
340 std::string::size_type DotPos = Filename.rfind('.');
341
342 if (DotPos == std::string::npos) {
343 // no file extension
344 return false;
345 }
346
347 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
348 // C header: .h
349 // C++ header: .hh or .H;
350 return Ext == "h" || Ext == "hh" || Ext == "H";
351}
352
Steve Naroffb29b4272008-04-14 22:03:09 +0000353RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000354 Diagnostic &D, const LangOptions &LOpts)
355 : Diags(D), LangOpts(LOpts) {
356 IsHeader = IsHeaderFile(inFile);
357 InFileName = inFile;
358 OutFileName = outFile;
359 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
360 "rewriting sub-expression within a macro (may not be correct)");
361}
362
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000363ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000364 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000365 Diagnostic &Diags,
366 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000367 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000368}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000369
Steve Naroffb29b4272008-04-14 22:03:09 +0000370void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000371 Context = &context;
372 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000373 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000374 MsgSendFunctionDecl = 0;
375 MsgSendSuperFunctionDecl = 0;
376 MsgSendStretFunctionDecl = 0;
377 MsgSendSuperStretFunctionDecl = 0;
378 MsgSendFpretFunctionDecl = 0;
379 GetClassFunctionDecl = 0;
380 GetMetaClassFunctionDecl = 0;
381 SelGetUidFunctionDecl = 0;
382 CFStringFunctionDecl = 0;
383 GetProtocolFunctionDecl = 0;
384 ConstantStringClassReference = 0;
385 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000386 CurMethodDef = 0;
387 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000388 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000389 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000390 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000391 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000392 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000393
394 // Get the ID and start/end of the main file.
395 MainFileID = SM->getMainFileID();
396 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
397 MainFileStart = MainBuf->getBufferStart();
398 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000399
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000400 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000401
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000402 // declaring objc_selector outside the parameter list removes a silly
403 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000404 if (IsHeader)
405 Preamble = "#pragma once\n";
406 Preamble += "struct objc_selector; struct objc_class;\n";
407 Preamble += "#ifndef OBJC_SUPER\n";
408 Preamble += "struct objc_super { struct objc_object *object; ";
409 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000410 if (LangOpts.Microsoft) {
411 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000412 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
413 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000414 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000415 Preamble += "};\n";
416 Preamble += "#define OBJC_SUPER\n";
417 Preamble += "#endif\n";
418 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
419 Preamble += "typedef struct objc_object Protocol;\n";
420 Preamble += "#define _REWRITER_typedef_Protocol\n";
421 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000422 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000423 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
424 else
425 Preamble += "#define __OBJC_RW_EXTERN extern\n";
426 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
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";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000429 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000430 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000431 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000432 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000433 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000434 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000435 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000436 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000437 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000438 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000439 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000440 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
441 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
442 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
443 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
444 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000445 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000446 // @synchronized hooks.
447 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
448 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000449 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000450 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
451 Preamble += "struct __objcFastEnumerationState {\n\t";
452 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000453 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000454 Preamble += "unsigned long *mutationsPtr;\n\t";
455 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000456 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000457 Preamble += "#define __FASTENUMERATIONSTATE\n";
458 Preamble += "#endif\n";
459 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
460 Preamble += "struct __NSConstantStringImpl {\n";
461 Preamble += " int *isa;\n";
462 Preamble += " int flags;\n";
463 Preamble += " char *str;\n";
464 Preamble += " long length;\n";
465 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000466 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
467 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
468 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000469 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000470 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000471 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
472 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000473 // Blocks preamble.
474 Preamble += "#ifndef BLOCK_IMPL\n";
475 Preamble += "#define BLOCK_IMPL\n";
476 Preamble += "struct __block_impl {\n";
477 Preamble += " void *isa;\n";
478 Preamble += " int Flags;\n";
479 Preamble += " int Size;\n";
480 Preamble += " void *FuncPtr;\n";
481 Preamble += "};\n";
482 Preamble += "enum {\n";
483 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
484 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
485 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000486 Preamble += "// Runtime copy/destroy helper functions\n";
487 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
488 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
489 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
490 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
491 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
492 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
493 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000494 if (LangOpts.Microsoft) {
495 Preamble += "#undef __OBJC_RW_EXTERN\n";
496 Preamble += "#define __attribute__(X)\n";
497 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000498}
499
500
Chris Lattnerf04da132007-10-24 17:06:59 +0000501//===----------------------------------------------------------------------===//
502// Top Level Driver Code
503//===----------------------------------------------------------------------===//
504
Steve Naroffb29b4272008-04-14 22:03:09 +0000505void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000506 // Two cases: either the decl could be in the main file, or it could be in a
507 // #included file. If the former, rewrite it now. If the later, check to see
508 // if we rewrote the #include/#import.
509 SourceLocation Loc = D->getLocation();
510 Loc = SM->getLogicalLoc(Loc);
511
512 // If this is for a builtin, ignore it.
513 if (Loc.isInvalid()) return;
514
Steve Naroffebf2b562007-10-23 23:50:29 +0000515 // Look for built-in declarations that we need to refer during the rewrite.
516 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000517 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000518 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000519 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000520 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000521 ConstantStringClassReference = FVD;
522 return;
523 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000524 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000525 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000526 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000527 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000528 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000529 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000530 } else if (ObjCForwardProtocolDecl *FP =
531 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000532 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000533 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000534 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000535 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000536 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000537}
538
Chris Lattnerf04da132007-10-24 17:06:59 +0000539//===----------------------------------------------------------------------===//
540// Syntactic (non-AST) Rewriting Code
541//===----------------------------------------------------------------------===//
542
Steve Naroffb29b4272008-04-14 22:03:09 +0000543void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000544 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
545 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
546 const char *MainBufStart = MainBuf.first;
547 const char *MainBufEnd = MainBuf.second;
548 size_t ImportLen = strlen("import");
549 size_t IncludeLen = strlen("include");
550
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000551 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000552 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
553 if (*BufPtr == '#') {
554 if (++BufPtr == MainBufEnd)
555 return;
556 while (*BufPtr == ' ' || *BufPtr == '\t')
557 if (++BufPtr == MainBufEnd)
558 return;
559 if (!strncmp(BufPtr, "import", ImportLen)) {
560 // replace import with include
561 SourceLocation ImportLoc =
562 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000563 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000564 BufPtr += ImportLen;
565 }
566 }
567 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000568}
569
Steve Naroffb29b4272008-04-14 22:03:09 +0000570void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000571 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
572 const char *MainBufStart = MainBuf.first;
573 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000574
Chris Lattnerf04da132007-10-24 17:06:59 +0000575 // Loop over the whole file, looking for tabs.
576 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
577 if (*BufPtr != '\t')
578 continue;
579
580 // Okay, we found a tab. This tab will turn into at least one character,
581 // but it depends on which 'virtual column' it is in. Compute that now.
582 unsigned VCol = 0;
583 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
584 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
585 ++VCol;
586
587 // Okay, now that we know the virtual column, we know how many spaces to
588 // insert. We assume 8-character tab-stops.
589 unsigned Spaces = 8-(VCol & 7);
590
591 // Get the location of the tab.
592 SourceLocation TabLoc =
593 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
594
595 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000596 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000597 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000598}
599
Steve Naroffeb0646c2008-12-02 15:48:25 +0000600static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
601 ObjCIvarDecl *OID) {
602 std::string S;
603 S = "((struct ";
604 S += ClassDecl->getIdentifier()->getName();
605 S += "_IMPL *)self)->";
606 S += OID->getNameAsCString();
607 return S;
608}
609
Steve Naroffa0876e82008-12-02 17:36:43 +0000610void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
611 ObjCImplementationDecl *IMD,
612 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000613 SourceLocation startLoc = PID->getLocStart();
614 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000615 const char *startBuf = SM->getCharacterData(startLoc);
616 assert((*startBuf == '@') && "bogus @synthesize location");
617 const char *semiBuf = strchr(startBuf, ';');
618 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
619 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
620
621 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
622 return; // FIXME: is this correct?
623
624 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000625 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000626 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000627 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000628
629 if (!OID)
630 return;
631
632 std::string Getr;
633 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
634 Getr += "{ ";
635 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000636 // FIXME: deal with code generation implications for various property
637 // attributes (copy, retain, nonatomic).
638 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000639 Getr += "return " + getIvarAccessString(ClassDecl, OID);
640 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000641 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000642
643 // Add the rewritten getter to trigger meta data generation. An alternate, and
644 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
645 // with properties explicitly. The following addInstanceMethod() required far
646 // less code change (and actually models what the rewriter is doing).
647 if (IMD)
648 IMD->addInstanceMethod(PD->getGetterMethodDecl());
649 else
650 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000651
652 if (PD->isReadOnly())
653 return;
654
655 // Generate the 'setter' function.
656 std::string Setr;
657 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000658 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000659 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000660 // FIXME: deal with code generation implications for various property
661 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000662 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000663 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
664 Setr += OID->getNameAsCString();
665 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000666 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000667
668 // Add the rewritten setter to trigger meta data generation.
669 if (IMD)
670 IMD->addInstanceMethod(PD->getSetterMethodDecl());
671 else
672 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000673}
Chris Lattner8a12c272007-10-11 18:38:32 +0000674
Steve Naroffb29b4272008-04-14 22:03:09 +0000675void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000676 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000677 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000678
679 // Get the start location and compute the semi location.
680 SourceLocation startLoc = ClassDecl->getLocation();
681 const char *startBuf = SM->getCharacterData(startLoc);
682 const char *semiPtr = strchr(startBuf, ';');
683
684 // Translate to typedef's that forward reference structs with the same name
685 // as the class. As a convenience, we include the original declaration
686 // as a comment.
687 std::string typedefString;
688 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000689 typedefString.append(startBuf, semiPtr-startBuf+1);
690 typedefString += "\n";
691 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000692 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000693 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000694 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000695 typedefString += "\n";
696 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000697 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000698 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000699 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000700 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000701 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000702 }
703
704 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000705 ReplaceText(startLoc, semiPtr-startBuf+1,
706 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000707}
708
Steve Naroffb29b4272008-04-14 22:03:09 +0000709void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000710 SourceLocation LocStart = Method->getLocStart();
711 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000712
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000713 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000714 InsertText(LocStart, "#if 0\n", 6);
715 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000716 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000717 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000718 }
719}
720
Steve Naroffb29b4272008-04-14 22:03:09 +0000721void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000722{
Chris Lattner55d13b42008-03-16 21:23:50 +0000723 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000724 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000725 SourceLocation Loc = Property->getLocation();
726
Chris Lattneraadaf782008-01-31 19:51:04 +0000727 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000728
729 // FIXME: handle properties that are declared across multiple lines.
730 }
731}
732
Steve Naroffb29b4272008-04-14 22:03:09 +0000733void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000734 SourceLocation LocStart = CatDecl->getLocStart();
735
736 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000737 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000738
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000739 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000740 E = CatDecl->instmeth_end(); I != E; ++I)
741 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000742 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000743 E = CatDecl->classmeth_end(); I != E; ++I)
744 RewriteMethodDeclaration(*I);
745
Steve Naroff423cb562007-10-30 13:30:57 +0000746 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000747 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000748}
749
Steve Naroffb29b4272008-04-14 22:03:09 +0000750void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000751 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000752
Steve Naroff752d6ef2007-10-30 16:42:30 +0000753 SourceLocation LocStart = PDecl->getLocStart();
754
755 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000756 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000757
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000758 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000759 E = PDecl->instmeth_end(); I != E; ++I)
760 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000761 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000762 E = PDecl->classmeth_end(); I != E; ++I)
763 RewriteMethodDeclaration(*I);
764
Steve Naroff752d6ef2007-10-30 16:42:30 +0000765 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000766 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000767 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000768
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000769 // Must comment out @optional/@required
770 const char *startBuf = SM->getCharacterData(LocStart);
771 const char *endBuf = SM->getCharacterData(LocEnd);
772 for (const char *p = startBuf; p < endBuf; p++) {
773 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
774 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000775 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000776 ReplaceText(OptionalLoc, strlen("@optional"),
777 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000778
779 }
780 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
781 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000782 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000783 ReplaceText(OptionalLoc, strlen("@required"),
784 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000785
786 }
787 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000788}
789
Steve Naroffb29b4272008-04-14 22:03:09 +0000790void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000791 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000792 if (LocStart.isInvalid())
793 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000794 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000795 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000796}
797
Steve Naroffb29b4272008-04-14 22:03:09 +0000798void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000799 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000800 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000801 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000802 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000803 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000804 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000805 else if (OMD->getResultType()->isFunctionPointerType()) {
806 // needs special handling, since pointer-to-functions have special
807 // syntax (where a decaration models use).
808 QualType retType = OMD->getResultType();
809 if (const PointerType* PT = retType->getAsPointerType()) {
810 QualType PointeeTy = PT->getPointeeType();
811 if ((FPRetType = PointeeTy->getAsFunctionType())) {
812 ResultStr += FPRetType->getResultType().getAsString();
813 ResultStr += "(*";
814 }
815 }
816 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000817 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000818 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000819
820 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000821 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000822
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000823 if (OMD->isInstance())
824 NameStr += "_I_";
825 else
826 NameStr += "_C_";
827
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000828 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000829 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000830
831 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000832 if (ObjCCategoryImplDecl *CID =
833 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000834 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000835 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000836 }
Steve Naroff563b8282008-04-04 22:23:44 +0000837 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000838 {
839 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000840 int len = selString.size();
841 for (int i = 0; i < len; i++)
842 if (selString[i] == ':')
843 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000844 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000845 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000846 // Remember this name for metadata emission
847 MethodInternalNames[OMD] = NameStr;
848 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000849
850 // Rewrite arguments
851 ResultStr += "(";
852
853 // invisible arguments
854 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000855 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000856 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000857 if (!LangOpts.Microsoft) {
858 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
859 ResultStr += "struct ";
860 }
861 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000862 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000863 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000864 }
865 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000866 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000867
868 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000869 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000870 ResultStr += " _cmd";
871
872 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000873 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000874 ParmVarDecl *PDecl = OMD->getParamDecl(i);
875 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000876 if (PDecl->getType()->isObjCQualifiedIdType()) {
877 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000878 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000879 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000880 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000881 if (isBlockPointerType(PDecl->getType())) {
882 // Make sure we convert "t (^)(...)" to "t (*)(...)".
883 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
884 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
885 } else
886 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000887 ResultStr += Name;
888 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000889 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000890 if (OMD->isVariadic())
891 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000892 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000893
Steve Naroff76e429d2008-07-16 14:40:40 +0000894 if (FPRetType) {
895 ResultStr += ")"; // close the precedence "scope" for "*".
896
897 // Now, emit the argument types (if any).
898 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
899 ResultStr += "(";
900 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
901 if (i) ResultStr += ", ";
902 std::string ParamStr = FT->getArgType(i).getAsString();
903 ResultStr += ParamStr;
904 }
905 if (FT->isVariadic()) {
906 if (FT->getNumArgs()) ResultStr += ", ";
907 ResultStr += "...";
908 }
909 ResultStr += ")";
910 } else {
911 ResultStr += "()";
912 }
913 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000914}
Steve Naroffb29b4272008-04-14 22:03:09 +0000915void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000916 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
917 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000918
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000919 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000920 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000921 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000922 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000923
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000924 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000925 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
926 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000927 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000928 ObjCMethodDecl *OMD = *I;
929 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000930 SourceLocation LocStart = OMD->getLocStart();
931 SourceLocation LocEnd = OMD->getBody()->getLocStart();
932
933 const char *startBuf = SM->getCharacterData(LocStart);
934 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000935 ReplaceText(LocStart, endBuf-startBuf,
936 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000937 }
938
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000939 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000940 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
941 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000942 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000943 ObjCMethodDecl *OMD = *I;
944 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000945 SourceLocation LocStart = OMD->getLocStart();
946 SourceLocation LocEnd = OMD->getBody()->getLocStart();
947
948 const char *startBuf = SM->getCharacterData(LocStart);
949 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000950 ReplaceText(LocStart, endBuf-startBuf,
951 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000952 }
Steve Naroffd40910b2008-12-01 20:33:01 +0000953 for (ObjCCategoryImplDecl::propimpl_iterator
954 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
955 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +0000956 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +0000957 }
958
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000959 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000960 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000961 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000962 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000963}
964
Steve Naroffb29b4272008-04-14 22:03:09 +0000965void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000966 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000967 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000968 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000969 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000970 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000971 ResultStr += "\n";
972 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000973 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000974 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000975 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000976 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000977 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000978 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000979 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000980 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000981 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000982
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000983 RewriteProperties(ClassDecl->getNumPropertyDecl(),
984 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000985 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000986 E = ClassDecl->instmeth_end(); I != E; ++I)
987 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000988 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000989 E = ClassDecl->classmeth_end(); I != E; ++I)
990 RewriteMethodDeclaration(*I);
991
Steve Naroff2feac5e2007-10-30 03:43:13 +0000992 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000993 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000994}
995
Steve Naroffc77a6362008-12-04 16:24:46 +0000996Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt) {
997 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
998 // This allows us to reuse all the fun and games in SynthMessageExpr().
999 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1000 ObjCMessageExpr *MsgExpr;
1001 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1002 llvm::SmallVector<Expr *, 1> ExprVec;
1003 ExprVec.push_back(newStmt);
1004
1005 MsgExpr = new ObjCMessageExpr(PropRefExpr->getBase(),
1006 PDecl->getSetterName(), PDecl->getType(),
1007 PDecl->getSetterMethodDecl(),
1008 SourceLocation(), SourceLocation(),
1009 &ExprVec[0], 1);
1010 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1011
1012 // Now do the actual rewrite.
1013 ReplaceStmt(BinOp, ReplacingStmt);
1014 delete BinOp;
1015 delete MsgExpr;
1016 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001017}
1018
Steve Naroffc77a6362008-12-04 16:24:46 +00001019Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
1020 Stmt *ReplacingStmt = PropGetters[PropRefExpr];
1021
1022 if (ReplacingStmt)
1023 return ReplacingStmt; // We can't rewrite the same property twice.
1024
Steve Naroff15f081d2008-12-03 00:56:33 +00001025 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1026 // This allows us to reuse all the fun and games in SynthMessageExpr().
1027 ObjCMessageExpr *MsgExpr;
1028 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1029
1030 MsgExpr = new ObjCMessageExpr(PropRefExpr->getBase(),
1031 PDecl->getGetterName(), PDecl->getType(),
1032 PDecl->getGetterMethodDecl(),
1033 SourceLocation(), SourceLocation(),
1034 0, 0);
1035
Steve Naroffc77a6362008-12-04 16:24:46 +00001036 ReplacingStmt = SynthMessageExpr(MsgExpr);
1037
Steve Naroff15f081d2008-12-03 00:56:33 +00001038 ReplaceStmt(PropRefExpr, ReplacingStmt);
Steve Naroffc77a6362008-12-04 16:24:46 +00001039
1040 PropGetters[PropRefExpr] = ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001041
1042 // delete PropRefExpr; elsewhere...
1043 delete MsgExpr;
1044 return ReplacingStmt;
1045}
1046
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001047Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1048 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001049 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001050 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001051 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001052 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1053 // lookup which class implements the instance variable.
1054 ObjCInterfaceDecl *clsDeclared = 0;
1055 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1056 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1057
1058 // Synthesize an explicit cast to gain access to the ivar.
1059 std::string RecName = clsDeclared->getIdentifier()->getName();
1060 RecName += "_IMPL";
1061 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001062 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001063 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001064 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1065 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001066 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001067 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001068 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001069 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1070 IV->getBase()->getLocEnd(),
1071 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001072 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001073 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001074 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1075 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001076 ReplaceStmt(IV, ME);
1077 delete IV;
1078 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001079 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001080
1081 ReplaceStmt(IV->getBase(), PE);
1082 // Cannot delete IV->getBase(), since PE points to it.
1083 // Replace the old base with the cast. This is important when doing
1084 // embedded rewrites. For example, [newInv->_container addObject:0].
1085 IV->setBase(PE);
1086 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001087 }
Steve Naroff84472a82008-04-18 21:55:08 +00001088 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001089 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1090
1091 // Explicit ivar refs need to have a cast inserted.
1092 // FIXME: consider sharing some of this code with the code above.
1093 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001094 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001095 // lookup which class implements the instance variable.
1096 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001097 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001098 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1099
1100 // Synthesize an explicit cast to gain access to the ivar.
1101 std::string RecName = clsDeclared->getIdentifier()->getName();
1102 RecName += "_IMPL";
1103 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001104 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001105 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001106 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1107 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001108 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001109 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001110 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001111 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1112 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001113 ReplaceStmt(IV->getBase(), PE);
1114 // Cannot delete IV->getBase(), since PE points to it.
1115 // Replace the old base with the cast. This is important when doing
1116 // embedded rewrites. For example, [newInv->_container addObject:0].
1117 IV->setBase(PE);
1118 return IV;
1119 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001120 }
Steve Naroff84472a82008-04-18 21:55:08 +00001121 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001122}
1123
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001124/// SynthCountByEnumWithState - To print:
1125/// ((unsigned int (*)
1126/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1127/// (void *)objc_msgSend)((id)l_collection,
1128/// sel_registerName(
1129/// "countByEnumeratingWithState:objects:count:"),
1130/// &enumState,
1131/// (id *)items, (unsigned int)16)
1132///
Steve Naroffb29b4272008-04-14 22:03:09 +00001133void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001134 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1135 "id *, unsigned int))(void *)objc_msgSend)";
1136 buf += "\n\t\t";
1137 buf += "((id)l_collection,\n\t\t";
1138 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1139 buf += "\n\t\t";
1140 buf += "&enumState, "
1141 "(id *)items, (unsigned int)16)";
1142}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001143
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001144/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1145/// statement to exit to its outer synthesized loop.
1146///
Steve Naroffb29b4272008-04-14 22:03:09 +00001147Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001148 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1149 return S;
1150 // replace break with goto __break_label
1151 std::string buf;
1152
1153 SourceLocation startLoc = S->getLocStart();
1154 buf = "goto __break_label_";
1155 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001156 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001157
1158 return 0;
1159}
1160
1161/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1162/// statement to continue with its inner synthesized loop.
1163///
Steve Naroffb29b4272008-04-14 22:03:09 +00001164Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001165 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1166 return S;
1167 // replace continue with goto __continue_label
1168 std::string buf;
1169
1170 SourceLocation startLoc = S->getLocStart();
1171 buf = "goto __continue_label_";
1172 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001173 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001174
1175 return 0;
1176}
1177
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001178/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001179/// It rewrites:
1180/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001181
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001182/// Into:
1183/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001184/// type elem;
1185/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001186/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001187/// id l_collection = (id)collection;
1188/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1189/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001190/// if (limit) {
1191/// unsigned long startMutations = *enumState.mutationsPtr;
1192/// do {
1193/// unsigned long counter = 0;
1194/// do {
1195/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001196/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001197/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001198/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001199/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001200/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001201/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1202/// objects:items count:16]);
1203/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001204/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001205/// }
1206/// else
1207/// elem = nil;
1208/// }
1209///
Steve Naroffb29b4272008-04-14 22:03:09 +00001210Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001211 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001212 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1213 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1214 "ObjCForCollectionStmt Statement stack mismatch");
1215 assert(!ObjCBcLabelNo.empty() &&
1216 "ObjCForCollectionStmt - Label No stack empty");
1217
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001218 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001219 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001220 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001221 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001222 std::string buf;
1223 buf = "\n{\n\t";
1224 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1225 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001226 ScopedDecl* D = DS->getSolitaryDecl();
1227 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001228 elementTypeAsString = ElementType.getAsString();
1229 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001230 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001231 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001232 buf += elementName;
1233 buf += ";\n\t";
1234 }
Chris Lattner06767512008-04-08 05:52:18 +00001235 else {
1236 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001237 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001238 elementTypeAsString
1239 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001240 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001241
1242 // struct __objcFastEnumerationState enumState = { 0 };
1243 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1244 // id items[16];
1245 buf += "id items[16];\n\t";
1246 // id l_collection = (id)
1247 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001248 // Find start location of 'collection' the hard way!
1249 const char *startCollectionBuf = startBuf;
1250 startCollectionBuf += 3; // skip 'for'
1251 startCollectionBuf = strchr(startCollectionBuf, '(');
1252 startCollectionBuf++; // skip '('
1253 // find 'in' and skip it.
1254 while (*startCollectionBuf != ' ' ||
1255 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1256 (*(startCollectionBuf+3) != ' ' &&
1257 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1258 startCollectionBuf++;
1259 startCollectionBuf += 3;
1260
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001261 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001262 ReplaceText(startLoc, startCollectionBuf - startBuf,
1263 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001264 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001265 SourceLocation rightParenLoc = S->getRParenLoc();
1266 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1267 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001268 buf = ";\n\t";
1269
1270 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1271 // objects:items count:16];
1272 // which is synthesized into:
1273 // unsigned int limit =
1274 // ((unsigned int (*)
1275 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1276 // (void *)objc_msgSend)((id)l_collection,
1277 // sel_registerName(
1278 // "countByEnumeratingWithState:objects:count:"),
1279 // (struct __objcFastEnumerationState *)&state,
1280 // (id *)items, (unsigned int)16);
1281 buf += "unsigned long limit =\n\t\t";
1282 SynthCountByEnumWithState(buf);
1283 buf += ";\n\t";
1284 /// if (limit) {
1285 /// unsigned long startMutations = *enumState.mutationsPtr;
1286 /// do {
1287 /// unsigned long counter = 0;
1288 /// do {
1289 /// if (startMutations != *enumState.mutationsPtr)
1290 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001291 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001292 buf += "if (limit) {\n\t";
1293 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1294 buf += "do {\n\t\t";
1295 buf += "unsigned long counter = 0;\n\t\t";
1296 buf += "do {\n\t\t\t";
1297 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1298 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1299 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001300 buf += " = (";
1301 buf += elementTypeAsString;
1302 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001303 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001304 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001305
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001306 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001307 /// } while (counter < limit);
1308 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1309 /// objects:items count:16]);
1310 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001311 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001312 /// }
1313 /// else
1314 /// elem = nil;
1315 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001316 ///
1317 buf = ";\n\t";
1318 buf += "__continue_label_";
1319 buf += utostr(ObjCBcLabelNo.back());
1320 buf += ": ;";
1321 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001322 buf += "} while (counter < limit);\n\t";
1323 buf += "} while (limit = ";
1324 SynthCountByEnumWithState(buf);
1325 buf += ");\n\t";
1326 buf += elementName;
1327 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001328 buf += "__break_label_";
1329 buf += utostr(ObjCBcLabelNo.back());
1330 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001331 buf += "}\n\t";
1332 buf += "else\n\t\t";
1333 buf += elementName;
1334 buf += " = nil;\n";
1335 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001336
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001337 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001338 if (isa<CompoundStmt>(S->getBody())) {
1339 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1340 InsertText(endBodyLoc, buf.c_str(), buf.size());
1341 } else {
1342 /* Need to treat single statements specially. For example:
1343 *
1344 * for (A *a in b) if (stuff()) break;
1345 * for (A *a in b) xxxyy;
1346 *
1347 * The following code simply scans ahead to the semi to find the actual end.
1348 */
1349 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1350 const char *semiBuf = strchr(stmtBuf, ';');
1351 assert(semiBuf && "Can't find ';'");
1352 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1353 InsertText(endBodyLoc, buf.c_str(), buf.size());
1354 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001355 Stmts.pop_back();
1356 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001357 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001358}
1359
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001360/// RewriteObjCSynchronizedStmt -
1361/// This routine rewrites @synchronized(expr) stmt;
1362/// into:
1363/// objc_sync_enter(expr);
1364/// @try stmt @finally { objc_sync_exit(expr); }
1365///
Steve Naroffb29b4272008-04-14 22:03:09 +00001366Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001367 // Get the start location and compute the semi location.
1368 SourceLocation startLoc = S->getLocStart();
1369 const char *startBuf = SM->getCharacterData(startLoc);
1370
1371 assert((*startBuf == '@') && "bogus @synchronized location");
1372
1373 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001374 buf = "objc_sync_enter((id)";
1375 const char *lparenBuf = startBuf;
1376 while (*lparenBuf != '(') lparenBuf++;
1377 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001378 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1379 // the sync expression is typically a message expression that's already
1380 // been rewritten! (which implies the SourceLocation's are invalid).
1381 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001382 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001383 while (*endBuf != ')') endBuf--;
1384 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001385 buf = ");\n";
1386 // declare a new scope with two variables, _stack and _rethrow.
1387 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1388 buf += "int buf[18/*32-bit i386*/];\n";
1389 buf += "char *pointers[4];} _stack;\n";
1390 buf += "id volatile _rethrow = 0;\n";
1391 buf += "objc_exception_try_enter(&_stack);\n";
1392 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001393 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001394 startLoc = S->getSynchBody()->getLocEnd();
1395 startBuf = SM->getCharacterData(startLoc);
1396
Steve Naroffc7089f12008-08-19 13:04:19 +00001397 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001398 SourceLocation lastCurlyLoc = startLoc;
1399 buf = "}\nelse {\n";
1400 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1401 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001402 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001403 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001404 S->getSynchExpr(),
1405 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001406 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001407 std::string syncExprBufS;
1408 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001409 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001410 buf += syncExprBuf.str();
1411 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001412 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1413 buf += "}\n";
1414 buf += "}";
1415
Chris Lattneraadaf782008-01-31 19:51:04 +00001416 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001417 return 0;
1418}
1419
Steve Naroffb29b4272008-04-14 22:03:09 +00001420Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001421 // Get the start location and compute the semi location.
1422 SourceLocation startLoc = S->getLocStart();
1423 const char *startBuf = SM->getCharacterData(startLoc);
1424
1425 assert((*startBuf == '@') && "bogus @try location");
1426
1427 std::string buf;
1428 // declare a new scope with two variables, _stack and _rethrow.
1429 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1430 buf += "int buf[18/*32-bit i386*/];\n";
1431 buf += "char *pointers[4];} _stack;\n";
1432 buf += "id volatile _rethrow = 0;\n";
1433 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001434 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001435
Chris Lattneraadaf782008-01-31 19:51:04 +00001436 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001437
1438 startLoc = S->getTryBody()->getLocEnd();
1439 startBuf = SM->getCharacterData(startLoc);
1440
1441 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001442
Steve Naroff75730982007-11-07 04:08:17 +00001443 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001444 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1445 if (catchList) {
1446 startLoc = startLoc.getFileLocWithOffset(1);
1447 buf = " /* @catch begin */ else {\n";
1448 buf += " id _caught = objc_exception_extract(&_stack);\n";
1449 buf += " objc_exception_try_enter (&_stack);\n";
1450 buf += " if (_setjmp(_stack.buf))\n";
1451 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1452 buf += " else { /* @catch continue */";
1453
1454 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001455 } else { /* no catch list */
1456 buf = "}\nelse {\n";
1457 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1458 buf += "}";
1459 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001460 }
Steve Naroff75730982007-11-07 04:08:17 +00001461 bool sawIdTypedCatch = false;
1462 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001463 while (catchList) {
1464 Stmt *catchStmt = catchList->getCatchParamStmt();
1465
1466 if (catchList == S->getCatchStmts())
1467 buf = "if ("; // we are generating code for the first catch clause
1468 else
1469 buf = "else if (";
1470 startLoc = catchList->getLocStart();
1471 startBuf = SM->getCharacterData(startLoc);
1472
1473 assert((*startBuf == '@') && "bogus @catch location");
1474
1475 const char *lParenLoc = strchr(startBuf, '(');
1476
Steve Naroffbe4b3332008-02-01 22:08:12 +00001477 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001478 // Now rewrite the body...
1479 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001480 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1481 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001482 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1483 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001484 assert((*bodyBuf == '{') && "bogus @catch body location");
1485
1486 buf += "1) { id _tmp = _caught;";
1487 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1488 buf.c_str(), buf.size());
1489 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001490 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001491 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001492 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001493 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001494 sawIdTypedCatch = true;
1495 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001496 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001497
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001498 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001499 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001500 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001501 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001502 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001503 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001504 }
1505 }
1506 // Now rewrite the body...
1507 lastCatchBody = catchList->getCatchBody();
1508 SourceLocation rParenLoc = catchList->getRParenLoc();
1509 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1510 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1511 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1512 assert((*rParenBuf == ')') && "bogus @catch paren location");
1513 assert((*bodyBuf == '{') && "bogus @catch body location");
1514
1515 buf = " = _caught;";
1516 // Here we replace ") {" with "= _caught;" (which initializes and
1517 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001518 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001519 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001520 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001521 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001522 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001523 catchList = catchList->getNextCatchStmt();
1524 }
1525 // Complete the catch list...
1526 if (lastCatchBody) {
1527 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001528 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1529 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001530
Steve Naroff378f47a2008-09-11 15:29:03 +00001531 // Insert the last (implicit) else clause *before* the right curly brace.
1532 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1533 buf = "} /* last catch end */\n";
1534 buf += "else {\n";
1535 buf += " _rethrow = _caught;\n";
1536 buf += " objc_exception_try_exit(&_stack);\n";
1537 buf += "} } /* @catch end */\n";
1538 if (!S->getFinallyStmt())
1539 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001540 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001541
1542 // Set lastCurlyLoc
1543 lastCurlyLoc = lastCatchBody->getLocEnd();
1544 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001545 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001546 startLoc = finalStmt->getLocStart();
1547 startBuf = SM->getCharacterData(startLoc);
1548 assert((*startBuf == '@') && "bogus @finally start");
1549
1550 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001551 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001552
1553 Stmt *body = finalStmt->getFinallyBody();
1554 SourceLocation startLoc = body->getLocStart();
1555 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001556 assert(*SM->getCharacterData(startLoc) == '{' &&
1557 "bogus @finally body location");
1558 assert(*SM->getCharacterData(endLoc) == '}' &&
1559 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001560
1561 startLoc = startLoc.getFileLocWithOffset(1);
1562 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001563 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001564 endLoc = endLoc.getFileLocWithOffset(-1);
1565 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001566 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001567
1568 // Set lastCurlyLoc
1569 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001570 } else { /* no finally clause - make sure we synthesize an implicit one */
1571 buf = "{ /* implicit finally clause */\n";
1572 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1573 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1574 buf += "}";
1575 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001576 }
1577 // Now emit the final closing curly brace...
1578 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1579 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001580 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001581 return 0;
1582}
1583
Steve Naroffb29b4272008-04-14 22:03:09 +00001584Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001585 return 0;
1586}
1587
Steve Naroffb29b4272008-04-14 22:03:09 +00001588Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001589 return 0;
1590}
1591
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001592// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001593// the throw expression is typically a message expression that's already
1594// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001595Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001596 // Get the start location and compute the semi location.
1597 SourceLocation startLoc = S->getLocStart();
1598 const char *startBuf = SM->getCharacterData(startLoc);
1599
1600 assert((*startBuf == '@') && "bogus @throw location");
1601
1602 std::string buf;
1603 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001604 if (S->getThrowExpr())
1605 buf = "objc_exception_throw(";
1606 else // add an implicit argument
1607 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001608
1609 // handle "@ throw" correctly.
1610 const char *wBuf = strchr(startBuf, 'w');
1611 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1612 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1613
Steve Naroff2bd03922007-11-07 15:32:26 +00001614 const char *semiBuf = strchr(startBuf, ';');
1615 assert((*semiBuf == ';') && "@throw: can't find ';'");
1616 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1617 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001618 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001619 return 0;
1620}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001621
Steve Naroffb29b4272008-04-14 22:03:09 +00001622Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001623 // Create a new string expression.
1624 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001625 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001626 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001627 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1628 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001629 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001630 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001631
Chris Lattner07506182007-11-30 22:53:43 +00001632 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001633 delete Exp;
1634 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001635}
1636
Steve Naroffb29b4272008-04-14 22:03:09 +00001637Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001638 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1639 // Create a call to sel_registerName("selName").
1640 llvm::SmallVector<Expr*, 8> SelExprs;
1641 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001642 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1643 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001644 false, argType, SourceLocation(),
1645 SourceLocation()));
1646 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1647 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001648 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001649 delete Exp;
1650 return SelExp;
1651}
1652
Steve Naroffb29b4272008-04-14 22:03:09 +00001653CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001654 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001655 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001656 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001657
1658 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001659 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001660
1661 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001662 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001663 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1664 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001665
1666 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001667
Steve Naroff934f2762007-10-24 22:48:43 +00001668 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1669}
1670
Steve Naroffd5255f52007-11-01 13:24:47 +00001671static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1672 const char *&startRef, const char *&endRef) {
1673 while (startBuf < endBuf) {
1674 if (*startBuf == '<')
1675 startRef = startBuf; // mark the start.
1676 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001677 if (startRef && *startRef == '<') {
1678 endRef = startBuf; // mark the end.
1679 return true;
1680 }
1681 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001682 }
1683 startBuf++;
1684 }
1685 return false;
1686}
1687
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001688static void scanToNextArgument(const char *&argRef) {
1689 int angle = 0;
1690 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1691 if (*argRef == '<')
1692 angle++;
1693 else if (*argRef == '>')
1694 angle--;
1695 argRef++;
1696 }
1697 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1698}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001699
Steve Naroffb29b4272008-04-14 22:03:09 +00001700bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001701
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001702 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001703 return true;
1704
Steve Naroffd5255f52007-11-01 13:24:47 +00001705 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001706 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001707 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001708 return true; // we have "Class <Protocol> *".
1709 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001710 return false;
1711}
1712
Steve Naroff4f95b752008-07-29 18:15:38 +00001713void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1714 QualType Type = E->getType();
1715 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001716 SourceLocation Loc, EndLoc;
1717
1718 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1719 Loc = ECE->getLParenLoc();
1720 EndLoc = ECE->getRParenLoc();
1721 } else {
1722 Loc = E->getLocStart();
1723 EndLoc = E->getLocEnd();
1724 }
1725 // This will defend against trying to rewrite synthesized expressions.
1726 if (Loc.isInvalid() || EndLoc.isInvalid())
1727 return;
1728
Steve Naroff4f95b752008-07-29 18:15:38 +00001729 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001730 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001731 const char *startRef = 0, *endRef = 0;
1732 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1733 // Get the locations of the startRef, endRef.
1734 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1735 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1736 // Comment out the protocol references.
1737 InsertText(LessLoc, "/*", 2);
1738 InsertText(GreaterLoc, "*/", 2);
1739 }
1740 }
1741}
1742
Steve Naroffb29b4272008-04-14 22:03:09 +00001743void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001744 SourceLocation Loc;
1745 QualType Type;
1746 const FunctionTypeProto *proto = 0;
1747 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1748 Loc = VD->getLocation();
1749 Type = VD->getType();
1750 }
1751 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1752 Loc = FD->getLocation();
1753 // Check for ObjC 'id' and class types that have been adorned with protocol
1754 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1755 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1756 assert(funcType && "missing function type");
1757 proto = dyn_cast<FunctionTypeProto>(funcType);
1758 if (!proto)
1759 return;
1760 Type = proto->getResultType();
1761 }
1762 else
1763 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001764
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001765 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001766 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001767
1768 const char *endBuf = SM->getCharacterData(Loc);
1769 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001770 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001771 startBuf--; // scan backward (from the decl location) for return type.
1772 const char *startRef = 0, *endRef = 0;
1773 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1774 // Get the locations of the startRef, endRef.
1775 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1776 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1777 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001778 InsertText(LessLoc, "/*", 2);
1779 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001780 }
1781 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001782 if (!proto)
1783 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001784 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001785 const char *startBuf = SM->getCharacterData(Loc);
1786 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001787 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1788 if (needToScanForQualifiers(proto->getArgType(i))) {
1789 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001790
Steve Naroffd5255f52007-11-01 13:24:47 +00001791 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001792 // scan forward (from the decl location) for argument types.
1793 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001794 const char *startRef = 0, *endRef = 0;
1795 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1796 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001797 SourceLocation LessLoc =
1798 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1799 SourceLocation GreaterLoc =
1800 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001801 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001802 InsertText(LessLoc, "/*", 2);
1803 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001804 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001805 startBuf = ++endBuf;
1806 }
1807 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001808 // If the function name is derived from a macro expansion, then the
1809 // argument buffer will not follow the name. Need to speak with Chris.
1810 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001811 startBuf++; // scan forward (from the decl location) for argument types.
1812 startBuf++;
1813 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001814 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001815}
1816
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001817// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001818void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001819 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1820 llvm::SmallVector<QualType, 16> ArgTys;
1821 ArgTys.push_back(Context->getPointerType(
1822 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001823 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001824 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001825 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001826 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001827 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001828 SelGetUidIdent, getFuncType,
1829 FunctionDecl::Extern, false, 0);
1830}
1831
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001832// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001833void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001834 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1835 llvm::SmallVector<QualType, 16> ArgTys;
1836 ArgTys.push_back(Context->getPointerType(
1837 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001838 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001839 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001840 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001841 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001842 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001843 SelGetProtoIdent, getFuncType,
1844 FunctionDecl::Extern, false, 0);
1845}
1846
Steve Naroffb29b4272008-04-14 22:03:09 +00001847void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001848 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001849 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001850 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001851 return;
1852 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001853 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001854}
1855
Steve Naroffc0a123c2008-03-11 17:37:02 +00001856// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001857void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001858 if (SuperContructorFunctionDecl)
1859 return;
1860 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1861 llvm::SmallVector<QualType, 16> ArgTys;
1862 QualType argT = Context->getObjCIdType();
1863 assert(!argT.isNull() && "Can't find 'id' type");
1864 ArgTys.push_back(argT);
1865 ArgTys.push_back(argT);
1866 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1867 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001868 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001869 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001870 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001871 msgSendIdent, msgSendType,
1872 FunctionDecl::Extern, false, 0);
1873}
1874
Steve Naroff09b266e2007-10-30 23:14:51 +00001875// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001876void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001877 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1878 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001879 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001880 assert(!argT.isNull() && "Can't find 'id' type");
1881 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001882 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001883 assert(!argT.isNull() && "Can't find 'SEL' type");
1884 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001885 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001886 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001887 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001888 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001889 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001890 msgSendIdent, msgSendType,
1891 FunctionDecl::Extern, false, 0);
1892}
1893
Steve Naroff874e2322007-11-15 10:28:18 +00001894// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001895void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001896 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1897 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001898 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001899 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001900 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001901 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1902 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1903 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001904 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001905 assert(!argT.isNull() && "Can't find 'SEL' type");
1906 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001907 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001908 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001909 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001910 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001911 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001912 msgSendIdent, msgSendType,
1913 FunctionDecl::Extern, false, 0);
1914}
1915
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001916// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001917void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001918 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1919 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001920 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001921 assert(!argT.isNull() && "Can't find 'id' type");
1922 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001923 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001924 assert(!argT.isNull() && "Can't find 'SEL' type");
1925 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001926 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001927 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001928 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001929 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001930 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001931 msgSendIdent, msgSendType,
1932 FunctionDecl::Extern, false, 0);
1933}
1934
1935// SynthMsgSendSuperStretFunctionDecl -
1936// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001937void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001938 IdentifierInfo *msgSendIdent =
1939 &Context->Idents.get("objc_msgSendSuper_stret");
1940 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001941 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001942 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001943 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001944 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1945 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1946 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001947 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001948 assert(!argT.isNull() && "Can't find 'SEL' type");
1949 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001950 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001951 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001952 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001953 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001954 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001955 msgSendIdent, msgSendType,
1956 FunctionDecl::Extern, false, 0);
1957}
1958
Steve Naroff1284db82008-05-08 22:02:18 +00001959// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001960void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001961 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1962 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001963 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001964 assert(!argT.isNull() && "Can't find 'id' type");
1965 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001966 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001967 assert(!argT.isNull() && "Can't find 'SEL' type");
1968 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001969 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001970 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001971 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001972 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001973 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001974 msgSendIdent, msgSendType,
1975 FunctionDecl::Extern, false, 0);
1976}
1977
Steve Naroff09b266e2007-10-30 23:14:51 +00001978// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001979void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001980 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1981 llvm::SmallVector<QualType, 16> ArgTys;
1982 ArgTys.push_back(Context->getPointerType(
1983 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001984 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001985 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001986 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001987 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001988 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001989 getClassIdent, getClassType,
1990 FunctionDecl::Extern, false, 0);
1991}
1992
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001993// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001994void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001995 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1996 llvm::SmallVector<QualType, 16> ArgTys;
1997 ArgTys.push_back(Context->getPointerType(
1998 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001999 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002000 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002001 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002002 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002003 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002004 getClassIdent, getClassType,
2005 FunctionDecl::Extern, false, 0);
2006}
2007
Steve Naroffb29b4272008-04-14 22:03:09 +00002008Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002009 QualType strType = getConstantStringStructType();
2010
2011 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002012
2013 std::string tmpName = InFileName;
2014 unsigned i;
2015 for (i=0; i < tmpName.length(); i++) {
2016 char c = tmpName.at(i);
2017 // replace any non alphanumeric characters with '_'.
2018 if (!isalpha(c) && (c < '0' || c > '9'))
2019 tmpName[i] = '_';
2020 }
2021 S += tmpName;
2022 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002023 S += utostr(NumObjCStringLiterals++);
2024
Steve Naroffba92b2e2008-03-27 22:29:16 +00002025 Preamble += "static __NSConstantStringImpl " + S;
2026 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2027 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002028 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002029 std::string prettyBufS;
2030 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002031 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002032 Preamble += prettyBuf.str();
2033 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002034 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002035 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002036
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002037 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002038 &Context->Idents.get(S.c_str()), strType,
2039 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002040 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2041 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2042 Context->getPointerType(DRE->getType()),
2043 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002044 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002045 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002046 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002047 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00002048 delete Exp;
2049 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002050}
2051
Steve Naroffb29b4272008-04-14 22:03:09 +00002052ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002053 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002054 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002055
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002056 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2057 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002058 assert(PT);
2059 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2060 return IT->getDecl();
2061 }
2062 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002063}
2064
2065// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002066QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002067 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002068 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002069 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002070 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002071 QualType FieldTypes[2];
2072
2073 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002074 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002075 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002076 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002077 // Create fields
2078 FieldDecl *FieldDecls[2];
2079
2080 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002081 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002082 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002083
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002084 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002085 }
2086 return Context->getTagDeclType(SuperStructDecl);
2087}
2088
Steve Naroffb29b4272008-04-14 22:03:09 +00002089QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002090 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002091 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002092 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002093 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002094 QualType FieldTypes[4];
2095
2096 // struct objc_object *receiver;
2097 FieldTypes[0] = Context->getObjCIdType();
2098 // int flags;
2099 FieldTypes[1] = Context->IntTy;
2100 // char *str;
2101 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2102 // long length;
2103 FieldTypes[3] = Context->LongTy;
2104 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002105 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002106
2107 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002108 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002109 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002110
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002111 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002112 }
2113 return Context->getTagDeclType(ConstantStringDecl);
2114}
2115
Steve Naroffb29b4272008-04-14 22:03:09 +00002116Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002117 if (!SelGetUidFunctionDecl)
2118 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002119 if (!MsgSendFunctionDecl)
2120 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002121 if (!MsgSendSuperFunctionDecl)
2122 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002123 if (!MsgSendStretFunctionDecl)
2124 SynthMsgSendStretFunctionDecl();
2125 if (!MsgSendSuperStretFunctionDecl)
2126 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002127 if (!MsgSendFpretFunctionDecl)
2128 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002129 if (!GetClassFunctionDecl)
2130 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002131 if (!GetMetaClassFunctionDecl)
2132 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002133
Steve Naroff874e2322007-11-15 10:28:18 +00002134 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002135 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2136 // May need to use objc_msgSend_stret() as well.
2137 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002138 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002139 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002140 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002141 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002142 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002143 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002144 }
Steve Naroff874e2322007-11-15 10:28:18 +00002145
Steve Naroff934f2762007-10-24 22:48:43 +00002146 // Synthesize a call to objc_msgSend().
2147 llvm::SmallVector<Expr*, 8> MsgExprs;
2148 IdentifierInfo *clsName = Exp->getClassName();
2149
2150 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2151 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002152 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2153 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002154 if (!strcmp(clsName->getName(), "super")) {
2155 MsgSendFlavor = MsgSendSuperFunctionDecl;
2156 if (MsgSendStretFlavor)
2157 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2158 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2159
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002160 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002161 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002162
2163 llvm::SmallVector<Expr*, 4> InitExprs;
2164
2165 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002166 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002167 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002168 Context->getObjCIdType(),
2169 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002170 llvm::SmallVector<Expr*, 8> ClsExprs;
2171 QualType argType = Context->getPointerType(Context->CharTy);
2172 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2173 SuperDecl->getIdentifier()->getLength(),
2174 false, argType, SourceLocation(),
2175 SourceLocation()));
2176 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2177 &ClsExprs[0],
2178 ClsExprs.size());
2179 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002180 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002181 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002182 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002183 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002184 // struct objc_super
2185 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002186 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002187
Steve Naroff23f41272008-03-11 18:14:26 +00002188 if (LangOpts.Microsoft) {
2189 SynthSuperContructorFunctionDecl();
2190 // Simulate a contructor call...
2191 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2192 superType, SourceLocation());
2193 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2194 superType, SourceLocation());
2195 } else {
2196 // (struct objc_super) { <exprs from above> }
2197 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2198 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002199 SourceLocation(), false);
2200 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2201 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002202 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002203 // struct objc_super *
2204 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2205 Context->getPointerType(SuperRep->getType()),
2206 SourceLocation());
2207 MsgExprs.push_back(Unop);
2208 } else {
2209 llvm::SmallVector<Expr*, 8> ClsExprs;
2210 QualType argType = Context->getPointerType(Context->CharTy);
2211 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2212 clsName->getLength(),
2213 false, argType, SourceLocation(),
2214 SourceLocation()));
2215 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2216 &ClsExprs[0],
2217 ClsExprs.size());
2218 MsgExprs.push_back(Cls);
2219 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002220 } else { // instance message.
2221 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002222
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002223 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002224 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002225 if (MsgSendStretFlavor)
2226 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002227 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2228
2229 llvm::SmallVector<Expr*, 4> InitExprs;
2230
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002231 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002232 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002233 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002234 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002235 SourceLocation()),
2236 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002237 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002238
2239 llvm::SmallVector<Expr*, 8> ClsExprs;
2240 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002241 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2242 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002243 false, argType, SourceLocation(),
2244 SourceLocation()));
2245 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002246 &ClsExprs[0],
2247 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002248 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002249 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002250 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002251 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002252 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002253 // struct objc_super
2254 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002255 Expr *SuperRep;
2256
2257 if (LangOpts.Microsoft) {
2258 SynthSuperContructorFunctionDecl();
2259 // Simulate a contructor call...
2260 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2261 superType, SourceLocation());
2262 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2263 superType, SourceLocation());
2264 } else {
2265 // (struct objc_super) { <exprs from above> }
2266 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2267 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002268 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002269 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2270 }
Steve Naroff874e2322007-11-15 10:28:18 +00002271 // struct objc_super *
2272 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2273 Context->getPointerType(SuperRep->getType()),
2274 SourceLocation());
2275 MsgExprs.push_back(Unop);
2276 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002277 // Remove all type-casts because it may contain objc-style types; e.g.
2278 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002279 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002280 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002281 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002282 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002283 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002284 MsgExprs.push_back(recExpr);
2285 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002286 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002287 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002288 llvm::SmallVector<Expr*, 8> SelExprs;
2289 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002290 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2291 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002292 false, argType, SourceLocation(),
2293 SourceLocation()));
2294 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2295 &SelExprs[0], SelExprs.size());
2296 MsgExprs.push_back(SelExp);
2297
2298 // Now push any user supplied arguments.
2299 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002300 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002301 // Make all implicit casts explicit...ICE comes in handy:-)
2302 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2303 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002304 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002305 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002306 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002307 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002308 }
2309 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002310 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002311 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002312 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002313 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002314 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002315 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002316 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002317 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002318 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002319 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002320 // We've transferred the ownership to MsgExprs. Null out the argument in
2321 // the original expression, since we will delete it below.
2322 Exp->setArg(i, 0);
2323 }
Steve Naroffab972d32007-11-04 22:37:50 +00002324 // Generate the funky cast.
2325 CastExpr *cast;
2326 llvm::SmallVector<QualType, 8> ArgTypes;
2327 QualType returnType;
2328
2329 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002330 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2331 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2332 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002333 ArgTypes.push_back(Context->getObjCIdType());
2334 ArgTypes.push_back(Context->getObjCSelType());
2335 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002336 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002337 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002338 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2339 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002340 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002341 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2342 if (isBlockPointerType(t)) {
2343 const BlockPointerType *BPT = t->getAsBlockPointerType();
2344 t = Context->getPointerType(BPT->getPointeeType());
2345 }
Steve Naroff352336b2007-11-05 14:36:37 +00002346 ArgTypes.push_back(t);
2347 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002348 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2349 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002350 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002351 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002352 }
2353 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002354 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002355
2356 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002357 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2358 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002359
2360 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2361 // If we don't do this cast, we get the following bizarre warning/note:
2362 // xx.m:13: warning: function called through a non-compatible type
2363 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002364 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002365 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002366 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002367
Steve Naroffab972d32007-11-04 22:37:50 +00002368 // Now do the "normal" pointer to function cast.
2369 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002370 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002371 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002372 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002373 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002374 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002375
2376 // Don't forget the parens to enforce the proper binding.
2377 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2378
2379 const FunctionType *FT = msgSendType->getAsFunctionType();
2380 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2381 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002382 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002383 if (MsgSendStretFlavor) {
2384 // We have the method which returns a struct/union. Must also generate
2385 // call to objc_msgSend_stret and hang both varieties on a conditional
2386 // expression which dictate which one to envoke depending on size of
2387 // method's return type.
2388
2389 // Create a reference to the objc_msgSend_stret() declaration.
2390 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2391 SourceLocation());
2392 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002393 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002394 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002395 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002396 // Now do the "normal" pointer to function cast.
2397 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002398 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002399 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002400 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002401 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002402
2403 // Don't forget the parens to enforce the proper binding.
2404 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2405
2406 FT = msgSendType->getAsFunctionType();
2407 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2408 FT->getResultType(), SourceLocation());
2409
2410 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002411 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2412 returnType.getAsOpaquePtr(),
2413 Context->getSizeType(),
2414 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002415 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2416 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2417 // For X86 it is more complicated and some kind of target specific routine
2418 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002419 unsigned IntSize =
2420 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002421 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2422 Context->IntTy,
2423 SourceLocation());
2424 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2425 BinaryOperator::LE,
2426 Context->IntTy,
2427 SourceLocation());
2428 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2429 ConditionalOperator *CondExpr =
2430 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002431 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002432 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002433 return ReplacingStmt;
2434}
2435
Steve Naroffb29b4272008-04-14 22:03:09 +00002436Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002437 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002438
Steve Naroffc77a6362008-12-04 16:24:46 +00002439 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002440 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002441 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002442
Chris Lattnere64b7772007-10-24 16:57:36 +00002443 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002444 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002445}
2446
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002447/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2448/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002449Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002450 if (!GetProtocolFunctionDecl)
2451 SynthGetProtocolFunctionDecl();
2452 // Create a call to objc_getProtocol("ProtocolName").
2453 llvm::SmallVector<Expr*, 8> ProtoExprs;
2454 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002455 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2456 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002457 false, argType, SourceLocation(),
2458 SourceLocation()));
2459 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2460 &ProtoExprs[0],
2461 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002462 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002463 delete Exp;
2464 return ProtoExp;
2465
2466}
2467
Steve Naroffbaf58c32008-05-31 14:15:04 +00002468bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2469 const char *endBuf) {
2470 while (startBuf < endBuf) {
2471 if (*startBuf == '#') {
2472 // Skip whitespace.
2473 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2474 ;
2475 if (!strncmp(startBuf, "if", strlen("if")) ||
2476 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2477 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2478 !strncmp(startBuf, "define", strlen("define")) ||
2479 !strncmp(startBuf, "undef", strlen("undef")) ||
2480 !strncmp(startBuf, "else", strlen("else")) ||
2481 !strncmp(startBuf, "elif", strlen("elif")) ||
2482 !strncmp(startBuf, "endif", strlen("endif")) ||
2483 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2484 !strncmp(startBuf, "include", strlen("include")) ||
2485 !strncmp(startBuf, "import", strlen("import")) ||
2486 !strncmp(startBuf, "include_next", strlen("include_next")))
2487 return true;
2488 }
2489 startBuf++;
2490 }
2491 return false;
2492}
2493
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002494/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002495/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002496void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002497 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002498 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002499 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002500 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002501 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002502 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002503 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002504 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002505 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002506 SourceLocation LocStart = CDecl->getLocStart();
2507 SourceLocation LocEnd = CDecl->getLocEnd();
2508
2509 const char *startBuf = SM->getCharacterData(LocStart);
2510 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002511
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002512 // If no ivars and no root or if its root, directly or indirectly,
2513 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002514 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2515 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002516 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002517 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002518 return;
2519 }
2520
2521 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002522 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002523 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002524 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002525 if (LangOpts.Microsoft)
2526 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002527
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002528 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002529 const char *cursor = strchr(startBuf, '{');
2530 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002531 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002532 // If the buffer contains preprocessor directives, we do more fine-grained
2533 // rewrites. This is intended to fix code that looks like (which occurs in
2534 // NSURL.h, for example):
2535 //
2536 // #ifdef XYZ
2537 // @interface Foo : NSObject
2538 // #else
2539 // @interface FooBar : NSObject
2540 // #endif
2541 // {
2542 // int i;
2543 // }
2544 // @end
2545 //
2546 // This clause is segregated to avoid breaking the common case.
2547 if (BufferContainsPPDirectives(startBuf, cursor)) {
2548 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2549 CDecl->getClassLoc();
2550 const char *endHeader = SM->getCharacterData(L);
2551 endHeader += Lexer::MeasureTokenLength(L, *SM);
2552
Chris Lattner3db6cae2008-07-21 18:19:38 +00002553 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002554 // advance to the end of the referenced protocols.
2555 while (endHeader < cursor && *endHeader != '>') endHeader++;
2556 endHeader++;
2557 }
2558 // rewrite the original header
2559 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2560 } else {
2561 // rewrite the original header *without* disturbing the '{'
2562 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2563 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002564 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002565 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002566 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002567 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002568 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002569 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002570
2571 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002572 SourceLocation OnePastCurly =
2573 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2574 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002575 }
2576 cursor++; // past '{'
2577
2578 // Now comment out any visibility specifiers.
2579 while (cursor < endBuf) {
2580 if (*cursor == '@') {
2581 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002582 // Skip whitespace.
2583 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2584 /*scan*/;
2585
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002586 // FIXME: presence of @public, etc. inside comment results in
2587 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002588 if (!strncmp(cursor, "public", strlen("public")) ||
2589 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002590 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002591 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002592 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002593 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002594 // FIXME: If there are cases where '<' is used in ivar declaration part
2595 // of user code, then scan the ivar list and use needToScanForQualifiers
2596 // for type checking.
2597 else if (*cursor == '<') {
2598 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002599 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002600 cursor = strchr(cursor, '>');
2601 cursor++;
2602 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002603 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002604 } else if (*cursor == '^') { // rewrite block specifier.
2605 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2606 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002607 }
Steve Narofffea763e82007-11-14 19:25:57 +00002608 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002609 }
Steve Narofffea763e82007-11-14 19:25:57 +00002610 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002611 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002612 } else { // we don't have any instance variables - insert super struct.
2613 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2614 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002615 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002616 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002617 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002618 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002619 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002620 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002621 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002622 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002623 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002624}
2625
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002626// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002627/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002628void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002629 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002630 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002631 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002632 const char *ClassName,
2633 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002634 if (MethodBegin == MethodEnd) return;
2635
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002636 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002637 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002638 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002639 SEL _cmd;
2640 char *method_types;
2641 void *_imp;
2642 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002643 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002644 Result += "\nstruct _objc_method {\n";
2645 Result += "\tSEL _cmd;\n";
2646 Result += "\tchar *method_types;\n";
2647 Result += "\tvoid *_imp;\n";
2648 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002649
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002650 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002651 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002652
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002653 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002654
2655 /* struct {
2656 struct _objc_method_list *next_method;
2657 int method_count;
2658 struct _objc_method method_list[];
2659 }
2660 */
2661 Result += "\nstatic struct {\n";
2662 Result += "\tstruct _objc_method_list *next_method;\n";
2663 Result += "\tint method_count;\n";
2664 Result += "\tstruct _objc_method method_list[";
2665 Result += utostr(MethodEnd-MethodBegin);
2666 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002667 Result += prefix;
2668 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2669 Result += "_METHODS_";
2670 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002671 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002672 Result += IsInstanceMethod ? "inst" : "cls";
2673 Result += "_meth\")))= ";
2674 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002675
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002676 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002677 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002678 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002679 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002680 Result += "\", \"";
2681 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002682 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002683 Result += MethodInternalNames[*MethodBegin];
2684 Result += "}\n";
2685 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2686 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002687 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002688 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002689 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002690 Result += "\", \"";
2691 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002692 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002693 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002694 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002695 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002696 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002697}
2698
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002699/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002700void RewriteObjC::
2701RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2702 const char *prefix,
2703 const char *ClassName,
2704 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002705 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002706 if (Protocols.empty()) return;
2707
2708 for (unsigned i = 0; i != Protocols.size(); i++) {
2709 ObjCProtocolDecl *PDecl = Protocols[i];
2710 // Output struct protocol_methods holder of method selector and type.
2711 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2712 /* struct protocol_methods {
2713 SEL _cmd;
2714 char *method_types;
2715 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002716 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002717 Result += "\nstruct protocol_methods {\n";
2718 Result += "\tSEL _cmd;\n";
2719 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002720 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002721
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002722 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002723 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002724 // Do not synthesize the protocol more than once.
2725 if (ObjCSynthesizedProtocols.count(PDecl))
2726 continue;
2727
2728 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2729 unsigned NumMethods = PDecl->getNumInstanceMethods();
2730 /* struct _objc_protocol_method_list {
2731 int protocol_method_count;
2732 struct protocol_methods protocols[];
2733 }
2734 */
2735 Result += "\nstatic struct {\n";
2736 Result += "\tint protocol_method_count;\n";
2737 Result += "\tstruct protocol_methods protocols[";
2738 Result += utostr(NumMethods);
2739 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002740 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002741 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2742 "{\n\t" + utostr(NumMethods) + "\n";
2743
2744 // Output instance methods declared in this protocol.
2745 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2746 E = PDecl->instmeth_end(); I != E; ++I) {
2747 if (I == PDecl->instmeth_begin())
2748 Result += "\t ,{{(SEL)\"";
2749 else
2750 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002751 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002752 std::string MethodTypeString;
2753 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2754 Result += "\", \"";
2755 Result += MethodTypeString;
2756 Result += "\"}\n";
2757 }
2758 Result += "\t }\n};\n";
2759 }
2760
2761 // Output class methods declared in this protocol.
2762 int NumMethods = PDecl->getNumClassMethods();
2763 if (NumMethods > 0) {
2764 /* struct _objc_protocol_method_list {
2765 int protocol_method_count;
2766 struct protocol_methods protocols[];
2767 }
2768 */
2769 Result += "\nstatic struct {\n";
2770 Result += "\tint protocol_method_count;\n";
2771 Result += "\tstruct protocol_methods protocols[";
2772 Result += utostr(NumMethods);
2773 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002774 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002775 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2776 "{\n\t";
2777 Result += utostr(NumMethods);
2778 Result += "\n";
2779
2780 // Output instance methods declared in this protocol.
2781 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2782 E = PDecl->classmeth_end(); I != E; ++I) {
2783 if (I == PDecl->classmeth_begin())
2784 Result += "\t ,{{(SEL)\"";
2785 else
2786 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002787 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002788 std::string MethodTypeString;
2789 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2790 Result += "\", \"";
2791 Result += MethodTypeString;
2792 Result += "\"}\n";
2793 }
2794 Result += "\t }\n};\n";
2795 }
2796
2797 // Output:
2798 /* struct _objc_protocol {
2799 // Objective-C 1.0 extensions
2800 struct _objc_protocol_extension *isa;
2801 char *protocol_name;
2802 struct _objc_protocol **protocol_list;
2803 struct _objc_protocol_method_list *instance_methods;
2804 struct _objc_protocol_method_list *class_methods;
2805 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002806 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002807 static bool objc_protocol = false;
2808 if (!objc_protocol) {
2809 Result += "\nstruct _objc_protocol {\n";
2810 Result += "\tstruct _objc_protocol_extension *isa;\n";
2811 Result += "\tchar *protocol_name;\n";
2812 Result += "\tstruct _objc_protocol **protocol_list;\n";
2813 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2814 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2815 Result += "};\n";
2816
2817 objc_protocol = true;
2818 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002819
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002820 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002821 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002822 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2823 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002824 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002825 Result += "\", 0, ";
2826 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2827 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002828 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002829 Result += ", ";
2830 }
2831 else
2832 Result += "0, ";
2833 if (PDecl->getNumClassMethods() > 0) {
2834 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002835 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002836 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002837 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002838 else
2839 Result += "0\n";
2840 Result += "};\n";
2841
2842 // Mark this protocol as having been generated.
2843 if (!ObjCSynthesizedProtocols.insert(PDecl))
2844 assert(false && "protocol already synthesized");
2845 }
2846 // Output the top lovel protocol meta-data for the class.
2847 /* struct _objc_protocol_list {
2848 struct _objc_protocol_list *next;
2849 int protocol_count;
2850 struct _objc_protocol *class_protocols[];
2851 }
2852 */
2853 Result += "\nstatic struct {\n";
2854 Result += "\tstruct _objc_protocol_list *next;\n";
2855 Result += "\tint protocol_count;\n";
2856 Result += "\tstruct _objc_protocol *class_protocols[";
2857 Result += utostr(Protocols.size());
2858 Result += "];\n} _OBJC_";
2859 Result += prefix;
2860 Result += "_PROTOCOLS_";
2861 Result += ClassName;
2862 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2863 "{\n\t0, ";
2864 Result += utostr(Protocols.size());
2865 Result += "\n";
2866
2867 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002868 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002869 Result += " \n";
2870
2871 for (unsigned i = 1; i != Protocols.size(); i++) {
2872 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002873 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002874 Result += "\n";
2875 }
2876 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002877}
2878
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002879/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002880/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002881void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002882 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002883 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002884 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002885 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002886 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2887 CDecl = CDecl->getNextClassCategory())
2888 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2889 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002890
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002891 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002892 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002893 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002894
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002895 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002896 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002897 true, "CATEGORY_", FullCategoryName.c_str(),
2898 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002899
2900 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002901 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002902 false, "CATEGORY_", FullCategoryName.c_str(),
2903 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002904
2905 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002906 // Null CDecl is case of a category implementation with no category interface
2907 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002908 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002909 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002910
2911 /* struct _objc_category {
2912 char *category_name;
2913 char *class_name;
2914 struct _objc_method_list *instance_methods;
2915 struct _objc_method_list *class_methods;
2916 struct _objc_protocol_list *protocols;
2917 // Objective-C 1.0 extensions
2918 uint32_t size; // sizeof (struct _objc_category)
2919 struct _objc_property_list *instance_properties; // category's own
2920 // @property decl.
2921 };
2922 */
2923
2924 static bool objc_category = false;
2925 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002926 Result += "\nstruct _objc_category {\n";
2927 Result += "\tchar *category_name;\n";
2928 Result += "\tchar *class_name;\n";
2929 Result += "\tstruct _objc_method_list *instance_methods;\n";
2930 Result += "\tstruct _objc_method_list *class_methods;\n";
2931 Result += "\tstruct _objc_protocol_list *protocols;\n";
2932 Result += "\tunsigned int size;\n";
2933 Result += "\tstruct _objc_property_list *instance_properties;\n";
2934 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002935 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002936 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002937 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2938 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002939 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002940 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002941 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002942 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002943 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002944
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002945 if (IDecl->getNumInstanceMethods() > 0) {
2946 Result += "\t, (struct _objc_method_list *)"
2947 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2948 Result += FullCategoryName;
2949 Result += "\n";
2950 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002951 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002952 Result += "\t, 0\n";
2953 if (IDecl->getNumClassMethods() > 0) {
2954 Result += "\t, (struct _objc_method_list *)"
2955 "&_OBJC_CATEGORY_CLASS_METHODS_";
2956 Result += FullCategoryName;
2957 Result += "\n";
2958 }
2959 else
2960 Result += "\t, 0\n";
2961
Chris Lattner780f3292008-07-21 21:32:27 +00002962 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002963 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2964 Result += FullCategoryName;
2965 Result += "\n";
2966 }
2967 else
2968 Result += "\t, 0\n";
2969 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002970}
2971
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002972/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2973/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002974void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002975 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002976 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002977 if (ivar->isBitField()) {
2978 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2979 // place all bitfields at offset 0.
2980 Result += "0";
2981 } else {
2982 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002983 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002984 if (LangOpts.Microsoft)
2985 Result += "_IMPL";
2986 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002987 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002988 Result += ")";
2989 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002990}
2991
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002992//===----------------------------------------------------------------------===//
2993// Meta Data Emission
2994//===----------------------------------------------------------------------===//
2995
Steve Naroffb29b4272008-04-14 22:03:09 +00002996void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002997 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002998 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002999
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003000 // Explictly declared @interface's are already synthesized.
3001 if (CDecl->ImplicitInterfaceDecl()) {
3002 // FIXME: Implementation of a class with no @interface (legacy) doese not
3003 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003004 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003005 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003006
Chris Lattnerbe6df082007-12-12 07:56:42 +00003007 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003008 unsigned NumIvars = !IDecl->ivar_empty()
3009 ? IDecl->ivar_size()
3010 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003011 if (NumIvars > 0) {
3012 static bool objc_ivar = false;
3013 if (!objc_ivar) {
3014 /* struct _objc_ivar {
3015 char *ivar_name;
3016 char *ivar_type;
3017 int ivar_offset;
3018 };
3019 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003020 Result += "\nstruct _objc_ivar {\n";
3021 Result += "\tchar *ivar_name;\n";
3022 Result += "\tchar *ivar_type;\n";
3023 Result += "\tint ivar_offset;\n";
3024 Result += "};\n";
3025
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003026 objc_ivar = true;
3027 }
3028
Steve Naroff946a6932008-03-11 00:12:29 +00003029 /* struct {
3030 int ivar_count;
3031 struct _objc_ivar ivar_list[nIvars];
3032 };
3033 */
3034 Result += "\nstatic struct {\n";
3035 Result += "\tint ivar_count;\n";
3036 Result += "\tstruct _objc_ivar ivar_list[";
3037 Result += utostr(NumIvars);
3038 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003039 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003040 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003041 "{\n\t";
3042 Result += utostr(NumIvars);
3043 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003044
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003045 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003046 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003047 IVI = IDecl->ivar_begin();
3048 IVE = IDecl->ivar_end();
3049 } else {
3050 IVI = CDecl->ivar_begin();
3051 IVE = CDecl->ivar_end();
3052 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003053 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003054 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003055 Result += "\", \"";
3056 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003057 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003058 Result += StrEncoding;
3059 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003060 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003061 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003062 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003063 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003064 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003065 Result += "\", \"";
3066 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003067 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003068 Result += StrEncoding;
3069 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003070 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003071 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003072 }
3073
3074 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003075 }
3076
3077 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003078 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003079 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003080
3081 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003082 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003083 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003084
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003085 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003086 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003087 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003088
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003089
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003090 // Declaration of class/meta-class metadata
3091 /* struct _objc_class {
3092 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003093 const char *super_class_name;
3094 char *name;
3095 long version;
3096 long info;
3097 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003098 struct _objc_ivar_list *ivars;
3099 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003100 struct objc_cache *cache;
3101 struct objc_protocol_list *protocols;
3102 const char *ivar_layout;
3103 struct _objc_class_ext *ext;
3104 };
3105 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003106 static bool objc_class = false;
3107 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003108 Result += "\nstruct _objc_class {\n";
3109 Result += "\tstruct _objc_class *isa;\n";
3110 Result += "\tconst char *super_class_name;\n";
3111 Result += "\tchar *name;\n";
3112 Result += "\tlong version;\n";
3113 Result += "\tlong info;\n";
3114 Result += "\tlong instance_size;\n";
3115 Result += "\tstruct _objc_ivar_list *ivars;\n";
3116 Result += "\tstruct _objc_method_list *methods;\n";
3117 Result += "\tstruct objc_cache *cache;\n";
3118 Result += "\tstruct _objc_protocol_list *protocols;\n";
3119 Result += "\tconst char *ivar_layout;\n";
3120 Result += "\tstruct _objc_class_ext *ext;\n";
3121 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003122 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003123 }
3124
3125 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003126 ObjCInterfaceDecl *RootClass = 0;
3127 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003128 while (SuperClass) {
3129 RootClass = SuperClass;
3130 SuperClass = SuperClass->getSuperClass();
3131 }
3132 SuperClass = CDecl->getSuperClass();
3133
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003134 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003135 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003136 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003137 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003138 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003139 Result += "\"";
3140
3141 if (SuperClass) {
3142 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003143 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003144 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003145 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003146 Result += "\"";
3147 }
3148 else {
3149 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003150 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003151 Result += "\"";
3152 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003153 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003154 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003155 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003156 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003157 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003158 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003159 Result += "\n";
3160 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003161 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003162 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003163 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003164 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003165 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003166 Result += ",0,0\n";
3167 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003168 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003169 Result += "\t,0,0,0,0\n";
3170 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003171
3172 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003173 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003174 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003175 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003176 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003177 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003178 if (SuperClass) {
3179 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003180 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003181 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003182 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003183 Result += "\"";
3184 }
3185 else {
3186 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003187 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003188 Result += "\"";
3189 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003190 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003191 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003192 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003193 Result += ",0";
3194 else {
3195 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003196 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003197 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003198 if (LangOpts.Microsoft)
3199 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003200 Result += ")";
3201 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003202 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003203 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003204 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003205 Result += "\n\t";
3206 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003207 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003208 Result += ",0";
3209 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003210 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003211 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003212 Result += ", 0\n\t";
3213 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003214 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003215 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003216 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003217 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003218 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003219 Result += ", 0,0\n";
3220 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003221 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003222 Result += ",0,0,0\n";
3223 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003224}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003225
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003226/// RewriteImplementations - This routine rewrites all method implementations
3227/// and emits meta-data.
3228
Steve Narofface66252008-11-13 20:07:04 +00003229void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003230 int ClsDefCount = ClassImplementation.size();
3231 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003232
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003233 // Rewrite implemented methods
3234 for (int i = 0; i < ClsDefCount; i++)
3235 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003236
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003237 for (int i = 0; i < CatDefCount; i++)
3238 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003239}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003240
Steve Narofface66252008-11-13 20:07:04 +00003241void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3242 int ClsDefCount = ClassImplementation.size();
3243 int CatDefCount = CategoryImplementation.size();
3244
Steve Naroff5df5b762008-05-07 21:23:49 +00003245 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003246 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003247 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003248 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003249 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003250
3251 // For each implemented category, write out all its meta data.
3252 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003253 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003254
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003255 // Write objc_symtab metadata
3256 /*
3257 struct _objc_symtab
3258 {
3259 long sel_ref_cnt;
3260 SEL *refs;
3261 short cls_def_cnt;
3262 short cat_def_cnt;
3263 void *defs[cls_def_cnt + cat_def_cnt];
3264 };
3265 */
3266
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003267 Result += "\nstruct _objc_symtab {\n";
3268 Result += "\tlong sel_ref_cnt;\n";
3269 Result += "\tSEL *refs;\n";
3270 Result += "\tshort cls_def_cnt;\n";
3271 Result += "\tshort cat_def_cnt;\n";
3272 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3273 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003274
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003275 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003276 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003277 Result += "\t0, 0, " + utostr(ClsDefCount)
3278 + ", " + utostr(CatDefCount) + "\n";
3279 for (int i = 0; i < ClsDefCount; i++) {
3280 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003281 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003282 Result += "\n";
3283 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003284
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003285 for (int i = 0; i < CatDefCount; i++) {
3286 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003287 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003288 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003289 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003290 Result += "\n";
3291 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003292
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003293 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003294
3295 // Write objc_module metadata
3296
3297 /*
3298 struct _objc_module {
3299 long version;
3300 long size;
3301 const char *name;
3302 struct _objc_symtab *symtab;
3303 }
3304 */
3305
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003306 Result += "\nstruct _objc_module {\n";
3307 Result += "\tlong version;\n";
3308 Result += "\tlong size;\n";
3309 Result += "\tconst char *name;\n";
3310 Result += "\tstruct _objc_symtab *symtab;\n";
3311 Result += "};\n\n";
3312 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003313 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003314 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3315 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003316 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003317
3318 if (LangOpts.Microsoft) {
3319 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003320 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003321 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3322 Result += "&_OBJC_MODULES;\n";
3323 Result += "#pragma data_seg(pop)\n\n";
3324 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003325}
Chris Lattner311ff022007-10-16 22:36:42 +00003326
Steve Naroff54055232008-10-27 17:20:55 +00003327std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3328 const char *funcName,
3329 std::string Tag) {
3330 const FunctionType *AFT = CE->getFunctionType();
3331 QualType RT = AFT->getResultType();
3332 std::string StructRef = "struct " + Tag;
3333 std::string S = "static " + RT.getAsString() + " __" +
3334 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003335
Steve Naroff54055232008-10-27 17:20:55 +00003336 BlockDecl *BD = CE->getBlockDecl();
3337
3338 if (isa<FunctionTypeNoProto>(AFT)) {
3339 S += "()";
3340 } else if (BD->param_empty()) {
3341 S += "(" + StructRef + " *__cself)";
3342 } else {
3343 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3344 assert(FT && "SynthesizeBlockFunc: No function proto");
3345 S += '(';
3346 // first add the implicit argument.
3347 S += StructRef + " *__cself, ";
3348 std::string ParamStr;
3349 for (BlockDecl::param_iterator AI = BD->param_begin(),
3350 E = BD->param_end(); AI != E; ++AI) {
3351 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003352 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003353 (*AI)->getType().getAsStringInternal(ParamStr);
3354 S += ParamStr;
3355 }
3356 if (FT->isVariadic()) {
3357 if (!BD->param_empty()) S += ", ";
3358 S += "...";
3359 }
3360 S += ')';
3361 }
3362 S += " {\n";
3363
3364 // Create local declarations to avoid rewriting all closure decl ref exprs.
3365 // First, emit a declaration for all "by ref" decls.
3366 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3367 E = BlockByRefDecls.end(); I != E; ++I) {
3368 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003369 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003370 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003371 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003372 }
3373 // Next, emit a declaration for all "by copy" declarations.
3374 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3375 E = BlockByCopyDecls.end(); I != E; ++I) {
3376 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003377 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003378 // Handle nested closure invocation. For example:
3379 //
3380 // void (^myImportedClosure)(void);
3381 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3382 //
3383 // void (^anotherClosure)(void);
3384 // anotherClosure = ^(void) {
3385 // myImportedClosure(); // import and invoke the closure
3386 // };
3387 //
3388 if (isBlockPointerType((*I)->getType()))
3389 S += "struct __block_impl *";
3390 else
3391 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003392 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003393 }
3394 std::string RewrittenStr = RewrittenBlockExprs[CE];
3395 const char *cstr = RewrittenStr.c_str();
3396 while (*cstr++ != '{') ;
3397 S += cstr;
3398 S += "\n";
3399 return S;
3400}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003401
Steve Naroff54055232008-10-27 17:20:55 +00003402std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3403 const char *funcName,
3404 std::string Tag) {
3405 std::string StructRef = "struct " + Tag;
3406 std::string S = "static void __";
3407
3408 S += funcName;
3409 S += "_block_copy_" + utostr(i);
3410 S += "(" + StructRef;
3411 S += "*dst, " + StructRef;
3412 S += "*src) {";
3413 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3414 E = ImportedBlockDecls.end(); I != E; ++I) {
3415 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003416 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003417 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003418 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003419 S += ");}";
3420 }
3421 S += "\nstatic void __";
3422 S += funcName;
3423 S += "_block_dispose_" + utostr(i);
3424 S += "(" + StructRef;
3425 S += "*src) {";
3426 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3427 E = ImportedBlockDecls.end(); I != E; ++I) {
3428 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003429 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003430 S += ");";
3431 }
3432 S += "}\n";
3433 return S;
3434}
3435
3436std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3437 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003438 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003439 std::string Constructor = " " + Tag;
3440
3441 S += " {\n struct __block_impl impl;\n";
3442
3443 if (hasCopyDisposeHelpers)
3444 S += " void *copy;\n void *dispose;\n";
3445
3446 Constructor += "(void *fp";
3447
3448 if (hasCopyDisposeHelpers)
3449 Constructor += ", void *copyHelp, void *disposeHelp";
3450
3451 if (BlockDeclRefs.size()) {
3452 // Output all "by copy" declarations.
3453 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3454 E = BlockByCopyDecls.end(); I != E; ++I) {
3455 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003456 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003457 std::string ArgName = "_" + FieldName;
3458 // Handle nested closure invocation. For example:
3459 //
3460 // void (^myImportedBlock)(void);
3461 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3462 //
3463 // void (^anotherBlock)(void);
3464 // anotherBlock = ^(void) {
3465 // myImportedBlock(); // import and invoke the closure
3466 // };
3467 //
3468 if (isBlockPointerType((*I)->getType())) {
3469 S += "struct __block_impl *";
3470 Constructor += ", void *" + ArgName;
3471 } else {
3472 (*I)->getType().getAsStringInternal(FieldName);
3473 (*I)->getType().getAsStringInternal(ArgName);
3474 Constructor += ", " + ArgName;
3475 }
3476 S += FieldName + ";\n";
3477 }
3478 // Output all "by ref" declarations.
3479 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3480 E = BlockByRefDecls.end(); I != E; ++I) {
3481 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003482 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003483 std::string ArgName = "_" + FieldName;
3484 // Handle nested closure invocation. For example:
3485 //
3486 // void (^myImportedBlock)(void);
3487 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3488 //
3489 // void (^anotherBlock)(void);
3490 // anotherBlock = ^(void) {
3491 // myImportedBlock(); // import and invoke the closure
3492 // };
3493 //
3494 if (isBlockPointerType((*I)->getType())) {
3495 S += "struct __block_impl *";
3496 Constructor += ", void *" + ArgName;
3497 } else {
3498 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3499 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3500 Constructor += ", " + ArgName;
3501 }
3502 S += FieldName + "; // by ref\n";
3503 }
3504 // Finish writing the constructor.
3505 // FIXME: handle NSConcreteGlobalBlock.
3506 Constructor += ", int flags=0) {\n";
3507 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3508 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3509
3510 if (hasCopyDisposeHelpers)
3511 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3512
3513 // Initialize all "by copy" arguments.
3514 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3515 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003516 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003517 Constructor += " ";
3518 if (isBlockPointerType((*I)->getType()))
3519 Constructor += Name + " = (struct __block_impl *)_";
3520 else
3521 Constructor += Name + " = _";
3522 Constructor += Name + ";\n";
3523 }
3524 // Initialize all "by ref" arguments.
3525 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3526 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003527 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003528 Constructor += " ";
3529 if (isBlockPointerType((*I)->getType()))
3530 Constructor += Name + " = (struct __block_impl *)_";
3531 else
3532 Constructor += Name + " = _";
3533 Constructor += Name + ";\n";
3534 }
3535 } else {
3536 // Finish writing the constructor.
3537 // FIXME: handle NSConcreteGlobalBlock.
3538 Constructor += ", int flags=0) {\n";
3539 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3540 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3541 if (hasCopyDisposeHelpers)
3542 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3543 }
3544 Constructor += " ";
3545 Constructor += "}\n";
3546 S += Constructor;
3547 S += "};\n";
3548 return S;
3549}
3550
3551void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3552 const char *FunName) {
3553 // Insert closures that were part of the function.
3554 for (unsigned i = 0; i < Blocks.size(); i++) {
3555
3556 CollectBlockDeclRefInfo(Blocks[i]);
3557
3558 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3559
3560 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3561 ImportedBlockDecls.size() > 0);
3562
3563 InsertText(FunLocStart, CI.c_str(), CI.size());
3564
3565 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3566
3567 InsertText(FunLocStart, CF.c_str(), CF.size());
3568
3569 if (ImportedBlockDecls.size()) {
3570 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3571 InsertText(FunLocStart, HF.c_str(), HF.size());
3572 }
3573
3574 BlockDeclRefs.clear();
3575 BlockByRefDecls.clear();
3576 BlockByCopyDecls.clear();
3577 BlockCallExprs.clear();
3578 ImportedBlockDecls.clear();
3579 }
3580 Blocks.clear();
3581 RewrittenBlockExprs.clear();
3582}
3583
3584void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3585 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003586 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003587
3588 SynthesizeBlockLiterals(FunLocStart, FuncName);
3589}
3590
3591void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003592 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3593 //SourceLocation FunLocStart = MD->getLocStart();
3594 // FIXME: This hack works around a bug in Rewrite.InsertText().
3595 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003596 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003597 // Convert colons to underscores.
3598 std::string::size_type loc = 0;
3599 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3600 FuncName.replace(loc, 1, "_");
3601
3602 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3603}
3604
3605void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3606 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3607 CI != E; ++CI)
3608 if (*CI) {
3609 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3610 GetBlockDeclRefExprs(CBE->getBody());
3611 else
3612 GetBlockDeclRefExprs(*CI);
3613 }
3614 // Handle specific things.
3615 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3616 // FIXME: Handle enums.
3617 if (!isa<FunctionDecl>(CDRE->getDecl()))
3618 BlockDeclRefs.push_back(CDRE);
3619 return;
3620}
3621
3622void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3623 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3624 CI != E; ++CI)
3625 if (*CI) {
3626 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3627 GetBlockCallExprs(CBE->getBody());
3628 else
3629 GetBlockCallExprs(*CI);
3630 }
3631
3632 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3633 if (CE->getCallee()->getType()->isBlockPointerType()) {
3634 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3635 }
3636 }
3637 return;
3638}
3639
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003640Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003641 // Navigate to relevant type information.
3642 const char *closureName = 0;
3643 const BlockPointerType *CPT = 0;
3644
3645 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003646 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003647 CPT = DRE->getType()->getAsBlockPointerType();
3648 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003649 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003650 CPT = CDRE->getType()->getAsBlockPointerType();
3651 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003652 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003653 CPT = MExpr->getType()->getAsBlockPointerType();
3654 } else {
3655 assert(1 && "RewriteBlockClass: Bad type");
3656 }
3657 assert(CPT && "RewriteBlockClass: Bad type");
3658 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3659 assert(FT && "RewriteBlockClass: Bad type");
3660 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3661 // FTP will be null for closures that don't take arguments.
3662
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003663 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3664 SourceLocation(),
3665 &Context->Idents.get("__block_impl"));
3666 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003667
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003668 // Generate a funky cast.
3669 llvm::SmallVector<QualType, 8> ArgTypes;
3670
3671 // Push the block argument type.
3672 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003673 if (FTP) {
3674 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003675 E = FTP->arg_type_end(); I && (I != E); ++I) {
3676 QualType t = *I;
3677 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3678 if (isBlockPointerType(t)) {
3679 const BlockPointerType *BPT = t->getAsBlockPointerType();
3680 t = Context->getPointerType(BPT->getPointeeType());
3681 }
3682 ArgTypes.push_back(t);
3683 }
Steve Naroff54055232008-10-27 17:20:55 +00003684 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003685 // Now do the pointer to function cast.
3686 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3687 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3688
3689 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003690
Steve Naroffb2f9e512008-11-03 23:29:32 +00003691 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003692 // Don't forget the parens to enforce the proper binding.
3693 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3694 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003695
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003696 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3697 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3698 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3699
Steve Naroffb2f9e512008-11-03 23:29:32 +00003700 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003701 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3702
3703 llvm::SmallVector<Expr*, 8> BlkExprs;
3704 // Add the implicit argument.
3705 BlkExprs.push_back(BlkCast);
3706 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003707 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3708 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003709 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003710 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003711 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3712 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003713}
3714
3715void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003716 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3717 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003718}
3719
3720void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3721 // FIXME: Add more elaborate code generation required by the ABI.
3722 InsertText(BDRE->getLocStart(), "*", 1);
3723}
3724
Steve Naroffb2f9e512008-11-03 23:29:32 +00003725void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3726 SourceLocation LocStart = CE->getLParenLoc();
3727 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003728
3729 // Need to avoid trying to rewrite synthesized casts.
3730 if (LocStart.isInvalid())
3731 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003732 // Need to avoid trying to rewrite casts contained in macros.
3733 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3734 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003735
Steve Naroff54055232008-10-27 17:20:55 +00003736 const char *startBuf = SM->getCharacterData(LocStart);
3737 const char *endBuf = SM->getCharacterData(LocEnd);
3738
3739 // advance the location to startArgList.
3740 const char *argPtr = startBuf;
3741
3742 while (*argPtr++ && (argPtr < endBuf)) {
3743 switch (*argPtr) {
3744 case '^':
3745 // Replace the '^' with '*'.
3746 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3747 ReplaceText(LocStart, 1, "*", 1);
3748 break;
3749 }
3750 }
3751 return;
3752}
3753
3754void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3755 SourceLocation DeclLoc = FD->getLocation();
3756 unsigned parenCount = 0;
3757
3758 // We have 1 or more arguments that have closure pointers.
3759 const char *startBuf = SM->getCharacterData(DeclLoc);
3760 const char *startArgList = strchr(startBuf, '(');
3761
3762 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3763
3764 parenCount++;
3765 // advance the location to startArgList.
3766 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3767 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3768
3769 const char *argPtr = startArgList;
3770
3771 while (*argPtr++ && parenCount) {
3772 switch (*argPtr) {
3773 case '^':
3774 // Replace the '^' with '*'.
3775 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3776 ReplaceText(DeclLoc, 1, "*", 1);
3777 break;
3778 case '(':
3779 parenCount++;
3780 break;
3781 case ')':
3782 parenCount--;
3783 break;
3784 }
3785 }
3786 return;
3787}
3788
3789bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3790 const FunctionTypeProto *FTP;
3791 const PointerType *PT = QT->getAsPointerType();
3792 if (PT) {
3793 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3794 } else {
3795 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3796 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3797 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3798 }
3799 if (FTP) {
3800 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3801 E = FTP->arg_type_end(); I != E; ++I)
3802 if (isBlockPointerType(*I))
3803 return true;
3804 }
3805 return false;
3806}
3807
3808void RewriteObjC::GetExtentOfArgList(const char *Name,
3809 const char *&LParen, const char *&RParen) {
3810 const char *argPtr = strchr(Name, '(');
3811 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3812
3813 LParen = argPtr; // output the start.
3814 argPtr++; // skip past the left paren.
3815 unsigned parenCount = 1;
3816
3817 while (*argPtr && parenCount) {
3818 switch (*argPtr) {
3819 case '(': parenCount++; break;
3820 case ')': parenCount--; break;
3821 default: break;
3822 }
3823 if (parenCount) argPtr++;
3824 }
3825 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3826 RParen = argPtr; // output the end
3827}
3828
3829void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3830 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3831 RewriteBlockPointerFunctionArgs(FD);
3832 return;
3833 }
3834 // Handle Variables and Typedefs.
3835 SourceLocation DeclLoc = ND->getLocation();
3836 QualType DeclT;
3837 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3838 DeclT = VD->getType();
3839 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3840 DeclT = TDD->getUnderlyingType();
3841 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3842 DeclT = FD->getType();
3843 else
3844 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3845
3846 const char *startBuf = SM->getCharacterData(DeclLoc);
3847 const char *endBuf = startBuf;
3848 // scan backward (from the decl location) for the end of the previous decl.
3849 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3850 startBuf--;
3851
3852 // *startBuf != '^' if we are dealing with a pointer to function that
3853 // may take block argument types (which will be handled below).
3854 if (*startBuf == '^') {
3855 // Replace the '^' with '*', computing a negative offset.
3856 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3857 ReplaceText(DeclLoc, 1, "*", 1);
3858 }
3859 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3860 // Replace the '^' with '*' for arguments.
3861 DeclLoc = ND->getLocation();
3862 startBuf = SM->getCharacterData(DeclLoc);
3863 const char *argListBegin, *argListEnd;
3864 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3865 while (argListBegin < argListEnd) {
3866 if (*argListBegin == '^') {
3867 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3868 ReplaceText(CaretLoc, 1, "*", 1);
3869 }
3870 argListBegin++;
3871 }
3872 }
3873 return;
3874}
3875
3876void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3877 // Add initializers for any closure decl refs.
3878 GetBlockDeclRefExprs(Exp->getBody());
3879 if (BlockDeclRefs.size()) {
3880 // Unique all "by copy" declarations.
3881 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3882 if (!BlockDeclRefs[i]->isByRef())
3883 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3884 // Unique all "by ref" declarations.
3885 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3886 if (BlockDeclRefs[i]->isByRef()) {
3887 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3888 }
3889 // Find any imported blocks...they will need special attention.
3890 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3891 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003892 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003893 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3894 }
3895 }
3896}
3897
Steve Narofffa15fd92008-10-28 20:29:00 +00003898FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3899 IdentifierInfo *ID = &Context->Idents.get(name);
3900 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3901 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3902 ID, FType, FunctionDecl::Extern, false, 0);
3903}
3904
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003905Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003906 Blocks.push_back(Exp);
3907
3908 CollectBlockDeclRefInfo(Exp);
3909 std::string FuncName;
3910
3911 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003912 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003913 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00003914 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003915 // Convert colons to underscores.
3916 std::string::size_type loc = 0;
3917 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3918 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003919 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003920 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00003921
3922 std::string BlockNumber = utostr(Blocks.size()-1);
3923
3924 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3925 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3926
3927 // Get a pointer to the function type so we can cast appropriately.
3928 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3929
3930 FunctionDecl *FD;
3931 Expr *NewRep;
3932
3933 // Simulate a contructor call...
3934 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3935 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3936
3937 llvm::SmallVector<Expr*, 4> InitExprs;
3938
Steve Narofffdc03722008-10-29 21:23:59 +00003939 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003940 FD = SynthBlockInitFunctionDecl(Func.c_str());
3941 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3942 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003943 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003944 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003945
3946 if (ImportedBlockDecls.size()) {
3947 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003948 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3949 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3950 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003951 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003952 InitExprs.push_back(castExpr);
3953
Steve Narofffa15fd92008-10-28 20:29:00 +00003954 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003955 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3956 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3957 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003958 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003959 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003960 }
3961 // Add initializers for any closure decl refs.
3962 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00003963 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00003964 // Output all "by copy" declarations.
3965 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3966 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003967 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003968 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00003969 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003970 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003971 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003972 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003973 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3974 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003975 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003976 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003977 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003978 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003979 }
Steve Narofffdc03722008-10-29 21:23:59 +00003980 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003981 }
3982 // Output all "by ref" declarations.
3983 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3984 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003985 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003986 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3987 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3988 Context->getPointerType(Exp->getType()),
3989 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00003990 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003991 }
3992 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003993 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3994 FType, SourceLocation());
3995 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3996 Context->getPointerType(NewRep->getType()),
3997 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00003998 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003999 BlockDeclRefs.clear();
4000 BlockByRefDecls.clear();
4001 BlockByCopyDecls.clear();
4002 ImportedBlockDecls.clear();
4003 return NewRep;
4004}
4005
4006//===----------------------------------------------------------------------===//
4007// Function Body / Expression rewriting
4008//===----------------------------------------------------------------------===//
4009
Steve Naroffc77a6362008-12-04 16:24:46 +00004010// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4011// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4012// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4013// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4014// Since the rewriter isn't capable of rewriting rewritten code, it's important
4015// we get this right.
4016void RewriteObjC::CollectPropertySetters(Stmt *S) {
4017 // Perform a bottom up traversal of all children.
4018 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4019 CI != E; ++CI)
4020 if (*CI)
4021 CollectPropertySetters(*CI);
4022
4023 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4024 if (BinOp->isAssignmentOp()) {
4025 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4026 PropSetters[PRE] = BinOp;
4027 }
4028 }
4029}
4030
Steve Narofffa15fd92008-10-28 20:29:00 +00004031Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4032 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4033 isa<DoStmt>(S) || isa<ForStmt>(S))
4034 Stmts.push_back(S);
4035 else if (isa<ObjCForCollectionStmt>(S)) {
4036 Stmts.push_back(S);
4037 ObjCBcLabelNo.push_back(++BcLabelCount);
4038 }
4039
4040 SourceRange OrigStmtRange = S->getSourceRange();
4041
4042 // Perform a bottom up rewrite of all children.
4043 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4044 CI != E; ++CI)
4045 if (*CI) {
4046 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4047 if (newStmt)
4048 *CI = newStmt;
4049 }
4050
4051 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4052 // Rewrite the block body in place.
4053 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4054
4055 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004056 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4057 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004058
4059 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4060 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004061 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004062 return blockTranscribed;
4063 }
4064 // Handle specific things.
4065 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4066 return RewriteAtEncode(AtEncode);
4067
4068 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4069 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4070
Steve Naroffc77a6362008-12-04 16:24:46 +00004071 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4072 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4073 if (BinOp) {
4074 // Because the rewriter doesn't allow us to rewrite rewritten code,
4075 // we need to rewrite the right hand side prior to rewriting the setter.
4076 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
4077 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt));
4078 } else {
4079 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004080 }
4081 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004082 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4083 return RewriteAtSelector(AtSelector);
4084
4085 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4086 return RewriteObjCStringLiteral(AtString);
4087
4088 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004089#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004090 // Before we rewrite it, put the original message expression in a comment.
4091 SourceLocation startLoc = MessExpr->getLocStart();
4092 SourceLocation endLoc = MessExpr->getLocEnd();
4093
4094 const char *startBuf = SM->getCharacterData(startLoc);
4095 const char *endBuf = SM->getCharacterData(endLoc);
4096
4097 std::string messString;
4098 messString += "// ";
4099 messString.append(startBuf, endBuf-startBuf+1);
4100 messString += "\n";
4101
4102 // FIXME: Missing definition of
4103 // InsertText(clang::SourceLocation, char const*, unsigned int).
4104 // InsertText(startLoc, messString.c_str(), messString.size());
4105 // Tried this, but it didn't work either...
4106 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004107#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004108 return RewriteMessageExpr(MessExpr);
4109 }
4110
4111 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4112 return RewriteObjCTryStmt(StmtTry);
4113
4114 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4115 return RewriteObjCSynchronizedStmt(StmtTry);
4116
4117 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4118 return RewriteObjCThrowStmt(StmtThrow);
4119
4120 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4121 return RewriteObjCProtocolExpr(ProtocolExp);
4122
4123 if (ObjCForCollectionStmt *StmtForCollection =
4124 dyn_cast<ObjCForCollectionStmt>(S))
4125 return RewriteObjCForCollectionStmt(StmtForCollection,
4126 OrigStmtRange.getEnd());
4127 if (BreakStmt *StmtBreakStmt =
4128 dyn_cast<BreakStmt>(S))
4129 return RewriteBreakStmt(StmtBreakStmt);
4130 if (ContinueStmt *StmtContinueStmt =
4131 dyn_cast<ContinueStmt>(S))
4132 return RewriteContinueStmt(StmtContinueStmt);
4133
4134 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4135 // and cast exprs.
4136 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4137 // FIXME: What we're doing here is modifying the type-specifier that
4138 // precedes the first Decl. In the future the DeclGroup should have
4139 // a separate type-specifier that we can rewrite.
4140 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4141
4142 // Blocks rewrite rules.
4143 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4144 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004145 ScopedDecl *SD = *DI;
4146 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4147 if (isBlockPointerType(ND->getType()))
4148 RewriteBlockPointerDecl(ND);
4149 else if (ND->getType()->isFunctionPointerType())
4150 CheckFunctionPointerDecl(ND->getType(), ND);
4151 }
4152 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4153 if (isBlockPointerType(TD->getUnderlyingType()))
4154 RewriteBlockPointerDecl(TD);
4155 else if (TD->getUnderlyingType()->isFunctionPointerType())
4156 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4157 }
4158 }
4159 }
4160
4161 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4162 RewriteObjCQualifiedInterfaceTypes(CE);
4163
4164 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4165 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4166 assert(!Stmts.empty() && "Statement stack is empty");
4167 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4168 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4169 && "Statement stack mismatch");
4170 Stmts.pop_back();
4171 }
4172 // Handle blocks rewriting.
4173 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4174 if (BDRE->isByRef())
4175 RewriteBlockDeclRefExpr(BDRE);
4176 }
4177 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004178 if (CE->getCallee()->getType()->isBlockPointerType()) {
4179 Stmt *BlockCall = SynthesizeBlockCall(CE);
4180 ReplaceStmt(S, BlockCall);
4181 return BlockCall;
4182 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004183 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004184 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004185 RewriteCastExpr(CE);
4186 }
4187#if 0
4188 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4189 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4190 // Get the new text.
4191 std::string SStr;
4192 llvm::raw_string_ostream Buf(SStr);
4193 Replacement->printPretty(Buf);
4194 const std::string &Str = Buf.str();
4195
4196 printf("CAST = %s\n", &Str[0]);
4197 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4198 delete S;
4199 return Replacement;
4200 }
4201#endif
4202 // Return this stmt unmodified.
4203 return S;
4204}
4205
4206/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4207/// main file of the input.
4208void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4209 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4210 // Since function prototypes don't have ParmDecl's, we check the function
4211 // prototype. This enables us to rewrite function declarations and
4212 // definitions using the same code.
4213 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4214
4215 if (Stmt *Body = FD->getBody()) {
4216 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004217 CollectPropertySetters(Body);
Steve Narofffa15fd92008-10-28 20:29:00 +00004218 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroffc77a6362008-12-04 16:24:46 +00004219
Steve Narofffa15fd92008-10-28 20:29:00 +00004220 // This synthesizes and inserts the block "impl" struct, invoke function,
4221 // and any copy/dispose helper functions.
4222 InsertBlockLiteralsWithinFunction(FD);
4223 CurFunctionDef = 0;
4224 }
4225 return;
4226 }
4227 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4228 if (Stmt *Body = MD->getBody()) {
4229 //Body->dump();
4230 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004231 CollectPropertySetters(Body);
Steve Narofffa15fd92008-10-28 20:29:00 +00004232 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4233 InsertBlockLiteralsWithinMethod(MD);
4234 CurMethodDef = 0;
4235 }
4236 }
4237 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4238 ClassImplementation.push_back(CI);
4239 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4240 CategoryImplementation.push_back(CI);
4241 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4242 RewriteForwardClassDecl(CD);
4243 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4244 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004245 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004246 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004247 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004248 CheckFunctionPointerDecl(VD->getType(), VD);
4249 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004250 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004251 RewriteCastExpr(CE);
4252 }
4253 }
4254 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004255 if (VD->getInit()) {
4256 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004257 CollectPropertySetters(VD->getInit());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004258 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004259 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004260 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004261 GlobalVarDecl = 0;
4262
4263 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004264 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004265 RewriteCastExpr(CE);
4266 }
4267 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004268 return;
4269 }
4270 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4271 if (isBlockPointerType(TD->getUnderlyingType()))
4272 RewriteBlockPointerDecl(TD);
4273 else if (TD->getUnderlyingType()->isFunctionPointerType())
4274 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4275 return;
4276 }
4277 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4278 if (RD->isDefinition()) {
4279 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4280 e = RD->field_end(); i != e; ++i) {
4281 FieldDecl *FD = *i;
4282 if (isBlockPointerType(FD->getType()))
4283 RewriteBlockPointerDecl(FD);
4284 }
4285 }
4286 return;
4287 }
4288 // Nothing yet.
4289}
4290
4291void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4292 // Get the top-level buffer that this corresponds to.
4293
4294 // Rewrite tabs if we care.
4295 //RewriteTabs();
4296
4297 if (Diags.hasErrorOccurred())
4298 return;
4299
4300 // Create the output file.
4301
4302 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4303 llvm::raw_ostream *OutFile;
4304 if (OutFileName == "-") {
4305 OutFile = &llvm::outs();
4306 } else if (!OutFileName.empty()) {
4307 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004308 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004309 OwnedStream.reset(OutFile);
4310 } else if (InFileName == "-") {
4311 OutFile = &llvm::outs();
4312 } else {
4313 llvm::sys::Path Path(InFileName);
4314 Path.eraseSuffix();
4315 Path.appendSuffix("cpp");
4316 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004317 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004318 OwnedStream.reset(OutFile);
4319 }
4320
4321 RewriteInclude();
4322
4323 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4324 Preamble.c_str(), Preamble.size(), false);
4325
Steve Naroff0aab7962008-11-14 14:10:01 +00004326 if (ClassImplementation.size() || CategoryImplementation.size())
4327 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004328
4329 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4330 // we are done.
4331 if (const RewriteBuffer *RewriteBuf =
4332 Rewrite.getRewriteBufferFor(MainFileID)) {
4333 //printf("Changed:\n");
4334 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4335 } else {
4336 fprintf(stderr, "No changes\n");
4337 }
Steve Narofface66252008-11-13 20:07:04 +00004338
Steve Naroff0aab7962008-11-14 14:10:01 +00004339 if (ClassImplementation.size() || CategoryImplementation.size()) {
4340 // Rewrite Objective-c meta data*
4341 std::string ResultStr;
4342 SynthesizeMetaDataIntoBuffer(ResultStr);
4343 // Emit metadata.
4344 *OutFile << ResultStr;
4345 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004346 OutFile->flush();
4347}
4348