blob: 69797366592e29ef4992a9518c35829ab713f74f [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Steve Naroff0113c9d2008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattner77cd2a02007-10-11 00:43:27 +000038namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattner01c57482007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000046 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000051
Ted Kremeneka526c5c2008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000083 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +000099
Steve Naroff54055232008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
107 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000108 VarDecl *GlobalVarDecl;
109
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000110 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000111 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000112 virtual void Initialize(ASTContext &context);
113
114 virtual void InitializeTU(TranslationUnit &TU) {
115 TU.SetOwnsDecls(false);
116 Initialize(TU.getContext());
117 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000118
Chris Lattner8a12c272007-10-11 18:38:32 +0000119
Chris Lattnerf04da132007-10-24 17:06:59 +0000120 // Top Level Driver code.
121 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000122 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000123 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000124 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000125
126 ~RewriteObjC() {}
127
128 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000129
130 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000131 // If replacement succeeded or warning disabled return with no warning.
132 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000133 return;
134
Chris Lattner0a14eee2008-11-18 07:04:44 +0000135 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
136 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000137 }
138
Steve Naroffba92b2e2008-03-27 22:29:16 +0000139 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
140 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000141 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000142 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000143 SilenceRewriteMacroWarning)
144 return;
145
146 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
147 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000148
Chris Lattneraadaf782008-01-31 19:51:04 +0000149 void RemoveText(SourceLocation Loc, unsigned StrLen) {
150 // If removal succeeded or warning disabled return with no warning.
151 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
152 return;
153
154 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
155 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000156
Chris Lattneraadaf782008-01-31 19:51:04 +0000157 void ReplaceText(SourceLocation Start, unsigned OrigLength,
158 const char *NewStr, unsigned NewLength) {
159 // If removal succeeded or warning disabled return with no warning.
160 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
161 SilenceRewriteMacroWarning)
162 return;
163
164 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
165 }
166
Chris Lattnerf04da132007-10-24 17:06:59 +0000167 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000168 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000169 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000170 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000171 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffd40910b2008-12-01 20:33:01 +0000172 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000173 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000174 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000175 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
176 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
177 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
178 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
179 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000180 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000181 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000182 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000183 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000184 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000185 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000186 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000187 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000188 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000189
Chris Lattnerf04da132007-10-24 17:06:59 +0000190 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000191 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000192 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000193 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000194 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000195 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000196 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000197 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000199 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000200 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
201 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
202 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000203 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
204 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000205 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
206 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000207 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000208 Stmt *RewriteBreakStmt(BreakStmt *S);
209 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000210 void SynthCountByEnumWithState(std::string &buf);
211
Steve Naroff09b266e2007-10-30 23:14:51 +0000212 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000213 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000214 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000215 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000216 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000217 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000218 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000219 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000220 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000221 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000222
Chris Lattnerf04da132007-10-24 17:06:59 +0000223 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000224 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000225 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000226
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000227 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000228 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000229
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000230 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
231 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000232 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000233 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000234 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000235 const char *ClassName,
236 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000237
Chris Lattner780f3292008-07-21 21:32:27 +0000238 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
239 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000240 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000241 const char *ClassName,
242 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000243 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000244 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000245 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
246 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000247 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000248 void RewriteImplementations();
249 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000250
251 // Block rewriting.
252 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
253 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
254
255 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
256 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
257
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000258 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000259 void RewriteBlockCall(CallExpr *Exp);
260 void RewriteBlockPointerDecl(NamedDecl *VD);
261 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
262 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
263
264 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
265 const char *funcName, std::string Tag);
266 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
267 const char *funcName, std::string Tag);
268 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
269 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000270 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000271 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
272 const char *FunName);
273
274 void CollectBlockDeclRefInfo(BlockExpr *Exp);
275 void GetBlockCallExprs(Stmt *S);
276 void GetBlockDeclRefExprs(Stmt *S);
277
278 // We avoid calling Type::isBlockPointerType(), since it operates on the
279 // canonical type. We only care if the top-level type is a closure pointer.
280 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
281
282 // FIXME: This predicate seems like it would be useful to add to ASTContext.
283 bool isObjCType(QualType T) {
284 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
285 return false;
286
287 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
288
289 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
290 OCT == Context->getCanonicalType(Context->getObjCClassType()))
291 return true;
292
293 if (const PointerType *PT = OCT->getAsPointerType()) {
294 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
295 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
296 return true;
297 }
298 return false;
299 }
300 bool PointerTypeTakesAnyBlockArguments(QualType QT);
301 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000302 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000303
304 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000305 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000306 };
307}
308
Steve Naroff54055232008-10-27 17:20:55 +0000309void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
310 NamedDecl *D) {
311 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
312 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
313 E = fproto->arg_type_end(); I && (I != E); ++I)
314 if (isBlockPointerType(*I)) {
315 // All the args are checked/rewritten. Don't call twice!
316 RewriteBlockPointerDecl(D);
317 break;
318 }
319 }
320}
321
322void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
323 const PointerType *PT = funcType->getAsPointerType();
324 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
325 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
326}
327
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000328static bool IsHeaderFile(const std::string &Filename) {
329 std::string::size_type DotPos = Filename.rfind('.');
330
331 if (DotPos == std::string::npos) {
332 // no file extension
333 return false;
334 }
335
336 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
337 // C header: .h
338 // C++ header: .hh or .H;
339 return Ext == "h" || Ext == "hh" || Ext == "H";
340}
341
Steve Naroffb29b4272008-04-14 22:03:09 +0000342RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000343 Diagnostic &D, const LangOptions &LOpts)
344 : Diags(D), LangOpts(LOpts) {
345 IsHeader = IsHeaderFile(inFile);
346 InFileName = inFile;
347 OutFileName = outFile;
348 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
349 "rewriting sub-expression within a macro (may not be correct)");
350}
351
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000352ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000353 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000354 Diagnostic &Diags,
355 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000356 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000357}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000358
Steve Naroffb29b4272008-04-14 22:03:09 +0000359void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000360 Context = &context;
361 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000362 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000363 MsgSendFunctionDecl = 0;
364 MsgSendSuperFunctionDecl = 0;
365 MsgSendStretFunctionDecl = 0;
366 MsgSendSuperStretFunctionDecl = 0;
367 MsgSendFpretFunctionDecl = 0;
368 GetClassFunctionDecl = 0;
369 GetMetaClassFunctionDecl = 0;
370 SelGetUidFunctionDecl = 0;
371 CFStringFunctionDecl = 0;
372 GetProtocolFunctionDecl = 0;
373 ConstantStringClassReference = 0;
374 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000375 CurMethodDef = 0;
376 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000377 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000378 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000379 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000380 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000381 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000382
383 // Get the ID and start/end of the main file.
384 MainFileID = SM->getMainFileID();
385 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
386 MainFileStart = MainBuf->getBufferStart();
387 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000388
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000389 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000390
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000391 // declaring objc_selector outside the parameter list removes a silly
392 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000393 if (IsHeader)
394 Preamble = "#pragma once\n";
395 Preamble += "struct objc_selector; struct objc_class;\n";
396 Preamble += "#ifndef OBJC_SUPER\n";
397 Preamble += "struct objc_super { struct objc_object *object; ";
398 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000399 if (LangOpts.Microsoft) {
400 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000401 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
402 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000403 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000404 Preamble += "};\n";
405 Preamble += "#define OBJC_SUPER\n";
406 Preamble += "#endif\n";
407 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
408 Preamble += "typedef struct objc_object Protocol;\n";
409 Preamble += "#define _REWRITER_typedef_Protocol\n";
410 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000411 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000412 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
413 else
414 Preamble += "#define __OBJC_RW_EXTERN extern\n";
415 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000416 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000417 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000418 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000419 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000420 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000421 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000422 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000423 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000424 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000425 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000426 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000427 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000428 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000429 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
430 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
431 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
432 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
433 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000434 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000435 // @synchronized hooks.
436 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
437 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000438 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000439 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
440 Preamble += "struct __objcFastEnumerationState {\n\t";
441 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000442 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000443 Preamble += "unsigned long *mutationsPtr;\n\t";
444 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000445 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000446 Preamble += "#define __FASTENUMERATIONSTATE\n";
447 Preamble += "#endif\n";
448 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
449 Preamble += "struct __NSConstantStringImpl {\n";
450 Preamble += " int *isa;\n";
451 Preamble += " int flags;\n";
452 Preamble += " char *str;\n";
453 Preamble += " long length;\n";
454 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000455 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
456 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
457 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000458 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000459 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000460 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
461 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000462 // Blocks preamble.
463 Preamble += "#ifndef BLOCK_IMPL\n";
464 Preamble += "#define BLOCK_IMPL\n";
465 Preamble += "struct __block_impl {\n";
466 Preamble += " void *isa;\n";
467 Preamble += " int Flags;\n";
468 Preamble += " int Size;\n";
469 Preamble += " void *FuncPtr;\n";
470 Preamble += "};\n";
471 Preamble += "enum {\n";
472 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
473 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
474 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000475 Preamble += "// Runtime copy/destroy helper functions\n";
476 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
477 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
478 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
479 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
480 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
481 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
482 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000483 if (LangOpts.Microsoft) {
484 Preamble += "#undef __OBJC_RW_EXTERN\n";
485 Preamble += "#define __attribute__(X)\n";
486 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000487}
488
489
Chris Lattnerf04da132007-10-24 17:06:59 +0000490//===----------------------------------------------------------------------===//
491// Top Level Driver Code
492//===----------------------------------------------------------------------===//
493
Steve Naroffb29b4272008-04-14 22:03:09 +0000494void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000495 // Two cases: either the decl could be in the main file, or it could be in a
496 // #included file. If the former, rewrite it now. If the later, check to see
497 // if we rewrote the #include/#import.
498 SourceLocation Loc = D->getLocation();
499 Loc = SM->getLogicalLoc(Loc);
500
501 // If this is for a builtin, ignore it.
502 if (Loc.isInvalid()) return;
503
Steve Naroffebf2b562007-10-23 23:50:29 +0000504 // Look for built-in declarations that we need to refer during the rewrite.
505 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000506 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000507 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000508 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000509 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000510 ConstantStringClassReference = FVD;
511 return;
512 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000513 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000514 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000515 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000516 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000517 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000518 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000519 } else if (ObjCForwardProtocolDecl *FP =
520 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000521 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000522 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000523 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000524 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000525 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000526}
527
Chris Lattnerf04da132007-10-24 17:06:59 +0000528//===----------------------------------------------------------------------===//
529// Syntactic (non-AST) Rewriting Code
530//===----------------------------------------------------------------------===//
531
Steve Naroffb29b4272008-04-14 22:03:09 +0000532void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000533 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
534 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
535 const char *MainBufStart = MainBuf.first;
536 const char *MainBufEnd = MainBuf.second;
537 size_t ImportLen = strlen("import");
538 size_t IncludeLen = strlen("include");
539
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000540 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000541 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
542 if (*BufPtr == '#') {
543 if (++BufPtr == MainBufEnd)
544 return;
545 while (*BufPtr == ' ' || *BufPtr == '\t')
546 if (++BufPtr == MainBufEnd)
547 return;
548 if (!strncmp(BufPtr, "import", ImportLen)) {
549 // replace import with include
550 SourceLocation ImportLoc =
551 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000552 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000553 BufPtr += ImportLen;
554 }
555 }
556 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000557}
558
Steve Naroffb29b4272008-04-14 22:03:09 +0000559void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000560 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
561 const char *MainBufStart = MainBuf.first;
562 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000563
Chris Lattnerf04da132007-10-24 17:06:59 +0000564 // Loop over the whole file, looking for tabs.
565 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
566 if (*BufPtr != '\t')
567 continue;
568
569 // Okay, we found a tab. This tab will turn into at least one character,
570 // but it depends on which 'virtual column' it is in. Compute that now.
571 unsigned VCol = 0;
572 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
573 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
574 ++VCol;
575
576 // Okay, now that we know the virtual column, we know how many spaces to
577 // insert. We assume 8-character tab-stops.
578 unsigned Spaces = 8-(VCol & 7);
579
580 // Get the location of the tab.
581 SourceLocation TabLoc =
582 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
583
584 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000585 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000586 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000587}
588
Steve Naroffd40910b2008-12-01 20:33:01 +0000589void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID) {
590 SourceLocation startLoc = PID->getLocStart();
591 InsertText(startLoc, "// ", 3);
592}
Chris Lattner8a12c272007-10-11 18:38:32 +0000593
Steve Naroffb29b4272008-04-14 22:03:09 +0000594void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000595 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000596 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000597
598 // Get the start location and compute the semi location.
599 SourceLocation startLoc = ClassDecl->getLocation();
600 const char *startBuf = SM->getCharacterData(startLoc);
601 const char *semiPtr = strchr(startBuf, ';');
602
603 // Translate to typedef's that forward reference structs with the same name
604 // as the class. As a convenience, we include the original declaration
605 // as a comment.
606 std::string typedefString;
607 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000608 typedefString.append(startBuf, semiPtr-startBuf+1);
609 typedefString += "\n";
610 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000611 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000612 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000613 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000614 typedefString += "\n";
615 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000616 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000617 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000618 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000619 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000620 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000621 }
622
623 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000624 ReplaceText(startLoc, semiPtr-startBuf+1,
625 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000626}
627
Steve Naroffb29b4272008-04-14 22:03:09 +0000628void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000629 SourceLocation LocStart = Method->getLocStart();
630 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000631
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000632 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000633 InsertText(LocStart, "#if 0\n", 6);
634 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000635 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000636 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000637 }
638}
639
Steve Naroffb29b4272008-04-14 22:03:09 +0000640void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000641{
Chris Lattner55d13b42008-03-16 21:23:50 +0000642 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000643 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000644 SourceLocation Loc = Property->getLocation();
645
Chris Lattneraadaf782008-01-31 19:51:04 +0000646 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000647
648 // FIXME: handle properties that are declared across multiple lines.
649 }
650}
651
Steve Naroffb29b4272008-04-14 22:03:09 +0000652void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000653 SourceLocation LocStart = CatDecl->getLocStart();
654
655 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000656 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000657
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000658 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000659 E = CatDecl->instmeth_end(); I != E; ++I)
660 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000661 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000662 E = CatDecl->classmeth_end(); I != E; ++I)
663 RewriteMethodDeclaration(*I);
664
Steve Naroff423cb562007-10-30 13:30:57 +0000665 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000666 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000667}
668
Steve Naroffb29b4272008-04-14 22:03:09 +0000669void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000670 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000671
Steve Naroff752d6ef2007-10-30 16:42:30 +0000672 SourceLocation LocStart = PDecl->getLocStart();
673
674 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000675 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000676
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000677 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000678 E = PDecl->instmeth_end(); I != E; ++I)
679 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000680 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000681 E = PDecl->classmeth_end(); I != E; ++I)
682 RewriteMethodDeclaration(*I);
683
Steve Naroff752d6ef2007-10-30 16:42:30 +0000684 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000685 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000686 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000687
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000688 // Must comment out @optional/@required
689 const char *startBuf = SM->getCharacterData(LocStart);
690 const char *endBuf = SM->getCharacterData(LocEnd);
691 for (const char *p = startBuf; p < endBuf; p++) {
692 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
693 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000694 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000695 ReplaceText(OptionalLoc, strlen("@optional"),
696 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000697
698 }
699 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
700 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000701 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000702 ReplaceText(OptionalLoc, strlen("@required"),
703 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000704
705 }
706 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000707}
708
Steve Naroffb29b4272008-04-14 22:03:09 +0000709void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000710 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000711 if (LocStart.isInvalid())
712 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000713 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000714 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000715}
716
Steve Naroffb29b4272008-04-14 22:03:09 +0000717void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000718 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000719 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000720 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000721 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000722 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000723 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000724 else if (OMD->getResultType()->isFunctionPointerType()) {
725 // needs special handling, since pointer-to-functions have special
726 // syntax (where a decaration models use).
727 QualType retType = OMD->getResultType();
728 if (const PointerType* PT = retType->getAsPointerType()) {
729 QualType PointeeTy = PT->getPointeeType();
730 if ((FPRetType = PointeeTy->getAsFunctionType())) {
731 ResultStr += FPRetType->getResultType().getAsString();
732 ResultStr += "(*";
733 }
734 }
735 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000736 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000737 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000738
739 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000740 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000741
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000742 if (OMD->isInstance())
743 NameStr += "_I_";
744 else
745 NameStr += "_C_";
746
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000747 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000748 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000749
750 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000751 if (ObjCCategoryImplDecl *CID =
752 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000753 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000754 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000755 }
Steve Naroff563b8282008-04-04 22:23:44 +0000756 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000757 {
758 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000759 int len = selString.size();
760 for (int i = 0; i < len; i++)
761 if (selString[i] == ':')
762 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000763 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000764 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000765 // Remember this name for metadata emission
766 MethodInternalNames[OMD] = NameStr;
767 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000768
769 // Rewrite arguments
770 ResultStr += "(";
771
772 // invisible arguments
773 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000774 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000775 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000776 if (!LangOpts.Microsoft) {
777 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
778 ResultStr += "struct ";
779 }
780 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000781 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000782 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000783 }
784 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000785 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000786
787 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000788 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000789 ResultStr += " _cmd";
790
791 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000792 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000793 ParmVarDecl *PDecl = OMD->getParamDecl(i);
794 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000795 if (PDecl->getType()->isObjCQualifiedIdType()) {
796 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000797 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000798 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000799 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000800 if (isBlockPointerType(PDecl->getType())) {
801 // Make sure we convert "t (^)(...)" to "t (*)(...)".
802 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
803 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
804 } else
805 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000806 ResultStr += Name;
807 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000808 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000809 if (OMD->isVariadic())
810 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000811 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000812
Steve Naroff76e429d2008-07-16 14:40:40 +0000813 if (FPRetType) {
814 ResultStr += ")"; // close the precedence "scope" for "*".
815
816 // Now, emit the argument types (if any).
817 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
818 ResultStr += "(";
819 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
820 if (i) ResultStr += ", ";
821 std::string ParamStr = FT->getArgType(i).getAsString();
822 ResultStr += ParamStr;
823 }
824 if (FT->isVariadic()) {
825 if (FT->getNumArgs()) ResultStr += ", ";
826 ResultStr += "...";
827 }
828 ResultStr += ")";
829 } else {
830 ResultStr += "()";
831 }
832 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000833}
Steve Naroffb29b4272008-04-14 22:03:09 +0000834void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000835 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
836 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000837
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000838 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000839 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000840 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000841 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000842
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000843 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000844 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
845 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000846 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000847 ObjCMethodDecl *OMD = *I;
848 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000849 SourceLocation LocStart = OMD->getLocStart();
850 SourceLocation LocEnd = OMD->getBody()->getLocStart();
851
852 const char *startBuf = SM->getCharacterData(LocStart);
853 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000854 ReplaceText(LocStart, endBuf-startBuf,
855 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000856 }
857
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000858 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000859 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
860 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000861 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000862 ObjCMethodDecl *OMD = *I;
863 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000864 SourceLocation LocStart = OMD->getLocStart();
865 SourceLocation LocEnd = OMD->getBody()->getLocStart();
866
867 const char *startBuf = SM->getCharacterData(LocStart);
868 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000869 ReplaceText(LocStart, endBuf-startBuf,
870 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000871 }
Steve Naroffd40910b2008-12-01 20:33:01 +0000872 for (ObjCCategoryImplDecl::propimpl_iterator
873 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
874 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
875 RewritePropertyImplDecl(*I);
876 }
877
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000878 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000879 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000880 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000881 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000882}
883
Steve Naroffb29b4272008-04-14 22:03:09 +0000884void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000885 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000886 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000887 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000888 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000889 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000890 ResultStr += "\n";
891 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000892 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000893 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000894 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000895 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000896 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000897 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000898 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000899 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000900 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000901
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000902 RewriteProperties(ClassDecl->getNumPropertyDecl(),
903 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000904 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000905 E = ClassDecl->instmeth_end(); I != E; ++I)
906 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000907 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000908 E = ClassDecl->classmeth_end(); I != E; ++I)
909 RewriteMethodDeclaration(*I);
910
Steve Naroff2feac5e2007-10-30 03:43:13 +0000911 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000912 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000913}
914
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000915Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
916 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000917 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +0000918 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +0000919 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000920 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
921 // lookup which class implements the instance variable.
922 ObjCInterfaceDecl *clsDeclared = 0;
923 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
924 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
925
926 // Synthesize an explicit cast to gain access to the ivar.
927 std::string RecName = clsDeclared->getIdentifier()->getName();
928 RecName += "_IMPL";
929 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000930 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000931 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +0000932 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
933 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000934 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +0000935 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +0000936 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000937 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
938 IV->getBase()->getLocEnd(),
939 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000940 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +0000941 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000942 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
943 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000944 ReplaceStmt(IV, ME);
945 delete IV;
946 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000947 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000948
949 ReplaceStmt(IV->getBase(), PE);
950 // Cannot delete IV->getBase(), since PE points to it.
951 // Replace the old base with the cast. This is important when doing
952 // embedded rewrites. For example, [newInv->_container addObject:0].
953 IV->setBase(PE);
954 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000955 }
Steve Naroff84472a82008-04-18 21:55:08 +0000956 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000957 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
958
959 // Explicit ivar refs need to have a cast inserted.
960 // FIXME: consider sharing some of this code with the code above.
961 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000962 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000963 // lookup which class implements the instance variable.
964 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000965 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000966 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
967
968 // Synthesize an explicit cast to gain access to the ivar.
969 std::string RecName = clsDeclared->getIdentifier()->getName();
970 RecName += "_IMPL";
971 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000972 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000973 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +0000974 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
975 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000976 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +0000977 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +0000978 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +0000979 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
980 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +0000981 ReplaceStmt(IV->getBase(), PE);
982 // Cannot delete IV->getBase(), since PE points to it.
983 // Replace the old base with the cast. This is important when doing
984 // embedded rewrites. For example, [newInv->_container addObject:0].
985 IV->setBase(PE);
986 return IV;
987 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000988 }
Steve Naroff84472a82008-04-18 21:55:08 +0000989 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000990}
991
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000992/// SynthCountByEnumWithState - To print:
993/// ((unsigned int (*)
994/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
995/// (void *)objc_msgSend)((id)l_collection,
996/// sel_registerName(
997/// "countByEnumeratingWithState:objects:count:"),
998/// &enumState,
999/// (id *)items, (unsigned int)16)
1000///
Steve Naroffb29b4272008-04-14 22:03:09 +00001001void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001002 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1003 "id *, unsigned int))(void *)objc_msgSend)";
1004 buf += "\n\t\t";
1005 buf += "((id)l_collection,\n\t\t";
1006 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1007 buf += "\n\t\t";
1008 buf += "&enumState, "
1009 "(id *)items, (unsigned int)16)";
1010}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001011
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001012/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1013/// statement to exit to its outer synthesized loop.
1014///
Steve Naroffb29b4272008-04-14 22:03:09 +00001015Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001016 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1017 return S;
1018 // replace break with goto __break_label
1019 std::string buf;
1020
1021 SourceLocation startLoc = S->getLocStart();
1022 buf = "goto __break_label_";
1023 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001024 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001025
1026 return 0;
1027}
1028
1029/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1030/// statement to continue with its inner synthesized loop.
1031///
Steve Naroffb29b4272008-04-14 22:03:09 +00001032Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001033 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1034 return S;
1035 // replace continue with goto __continue_label
1036 std::string buf;
1037
1038 SourceLocation startLoc = S->getLocStart();
1039 buf = "goto __continue_label_";
1040 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001041 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001042
1043 return 0;
1044}
1045
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001046/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001047/// It rewrites:
1048/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001049
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001050/// Into:
1051/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001052/// type elem;
1053/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001054/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001055/// id l_collection = (id)collection;
1056/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1057/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001058/// if (limit) {
1059/// unsigned long startMutations = *enumState.mutationsPtr;
1060/// do {
1061/// unsigned long counter = 0;
1062/// do {
1063/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001064/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001065/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001066/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001067/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001068/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001069/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1070/// objects:items count:16]);
1071/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001072/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001073/// }
1074/// else
1075/// elem = nil;
1076/// }
1077///
Steve Naroffb29b4272008-04-14 22:03:09 +00001078Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001079 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001080 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1081 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1082 "ObjCForCollectionStmt Statement stack mismatch");
1083 assert(!ObjCBcLabelNo.empty() &&
1084 "ObjCForCollectionStmt - Label No stack empty");
1085
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001086 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001087 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001088 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001089 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001090 std::string buf;
1091 buf = "\n{\n\t";
1092 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1093 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001094 ScopedDecl* D = DS->getSolitaryDecl();
1095 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001096 elementTypeAsString = ElementType.getAsString();
1097 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001098 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001099 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001100 buf += elementName;
1101 buf += ";\n\t";
1102 }
Chris Lattner06767512008-04-08 05:52:18 +00001103 else {
1104 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001105 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001106 elementTypeAsString
1107 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001108 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001109
1110 // struct __objcFastEnumerationState enumState = { 0 };
1111 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1112 // id items[16];
1113 buf += "id items[16];\n\t";
1114 // id l_collection = (id)
1115 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001116 // Find start location of 'collection' the hard way!
1117 const char *startCollectionBuf = startBuf;
1118 startCollectionBuf += 3; // skip 'for'
1119 startCollectionBuf = strchr(startCollectionBuf, '(');
1120 startCollectionBuf++; // skip '('
1121 // find 'in' and skip it.
1122 while (*startCollectionBuf != ' ' ||
1123 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1124 (*(startCollectionBuf+3) != ' ' &&
1125 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1126 startCollectionBuf++;
1127 startCollectionBuf += 3;
1128
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001129 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001130 ReplaceText(startLoc, startCollectionBuf - startBuf,
1131 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001132 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001133 SourceLocation rightParenLoc = S->getRParenLoc();
1134 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1135 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001136 buf = ";\n\t";
1137
1138 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1139 // objects:items count:16];
1140 // which is synthesized into:
1141 // unsigned int limit =
1142 // ((unsigned int (*)
1143 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1144 // (void *)objc_msgSend)((id)l_collection,
1145 // sel_registerName(
1146 // "countByEnumeratingWithState:objects:count:"),
1147 // (struct __objcFastEnumerationState *)&state,
1148 // (id *)items, (unsigned int)16);
1149 buf += "unsigned long limit =\n\t\t";
1150 SynthCountByEnumWithState(buf);
1151 buf += ";\n\t";
1152 /// if (limit) {
1153 /// unsigned long startMutations = *enumState.mutationsPtr;
1154 /// do {
1155 /// unsigned long counter = 0;
1156 /// do {
1157 /// if (startMutations != *enumState.mutationsPtr)
1158 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001159 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001160 buf += "if (limit) {\n\t";
1161 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1162 buf += "do {\n\t\t";
1163 buf += "unsigned long counter = 0;\n\t\t";
1164 buf += "do {\n\t\t\t";
1165 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1166 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1167 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001168 buf += " = (";
1169 buf += elementTypeAsString;
1170 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001171 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001172 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001173
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001174 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001175 /// } while (counter < limit);
1176 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1177 /// objects:items count:16]);
1178 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001179 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001180 /// }
1181 /// else
1182 /// elem = nil;
1183 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001184 ///
1185 buf = ";\n\t";
1186 buf += "__continue_label_";
1187 buf += utostr(ObjCBcLabelNo.back());
1188 buf += ": ;";
1189 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001190 buf += "} while (counter < limit);\n\t";
1191 buf += "} while (limit = ";
1192 SynthCountByEnumWithState(buf);
1193 buf += ");\n\t";
1194 buf += elementName;
1195 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001196 buf += "__break_label_";
1197 buf += utostr(ObjCBcLabelNo.back());
1198 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001199 buf += "}\n\t";
1200 buf += "else\n\t\t";
1201 buf += elementName;
1202 buf += " = nil;\n";
1203 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001204
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001205 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001206 if (isa<CompoundStmt>(S->getBody())) {
1207 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1208 InsertText(endBodyLoc, buf.c_str(), buf.size());
1209 } else {
1210 /* Need to treat single statements specially. For example:
1211 *
1212 * for (A *a in b) if (stuff()) break;
1213 * for (A *a in b) xxxyy;
1214 *
1215 * The following code simply scans ahead to the semi to find the actual end.
1216 */
1217 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1218 const char *semiBuf = strchr(stmtBuf, ';');
1219 assert(semiBuf && "Can't find ';'");
1220 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1221 InsertText(endBodyLoc, buf.c_str(), buf.size());
1222 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001223 Stmts.pop_back();
1224 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001225 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001226}
1227
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001228/// RewriteObjCSynchronizedStmt -
1229/// This routine rewrites @synchronized(expr) stmt;
1230/// into:
1231/// objc_sync_enter(expr);
1232/// @try stmt @finally { objc_sync_exit(expr); }
1233///
Steve Naroffb29b4272008-04-14 22:03:09 +00001234Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001235 // Get the start location and compute the semi location.
1236 SourceLocation startLoc = S->getLocStart();
1237 const char *startBuf = SM->getCharacterData(startLoc);
1238
1239 assert((*startBuf == '@') && "bogus @synchronized location");
1240
1241 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001242 buf = "objc_sync_enter((id)";
1243 const char *lparenBuf = startBuf;
1244 while (*lparenBuf != '(') lparenBuf++;
1245 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001246 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1247 // the sync expression is typically a message expression that's already
1248 // been rewritten! (which implies the SourceLocation's are invalid).
1249 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001250 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001251 while (*endBuf != ')') endBuf--;
1252 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001253 buf = ");\n";
1254 // declare a new scope with two variables, _stack and _rethrow.
1255 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1256 buf += "int buf[18/*32-bit i386*/];\n";
1257 buf += "char *pointers[4];} _stack;\n";
1258 buf += "id volatile _rethrow = 0;\n";
1259 buf += "objc_exception_try_enter(&_stack);\n";
1260 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001261 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001262 startLoc = S->getSynchBody()->getLocEnd();
1263 startBuf = SM->getCharacterData(startLoc);
1264
Steve Naroffc7089f12008-08-19 13:04:19 +00001265 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001266 SourceLocation lastCurlyLoc = startLoc;
1267 buf = "}\nelse {\n";
1268 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1269 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001270 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001271 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001272 S->getSynchExpr(),
1273 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001274 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001275 std::string syncExprBufS;
1276 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001277 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001278 buf += syncExprBuf.str();
1279 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001280 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1281 buf += "}\n";
1282 buf += "}";
1283
Chris Lattneraadaf782008-01-31 19:51:04 +00001284 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001285 return 0;
1286}
1287
Steve Naroffb29b4272008-04-14 22:03:09 +00001288Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001289 // Get the start location and compute the semi location.
1290 SourceLocation startLoc = S->getLocStart();
1291 const char *startBuf = SM->getCharacterData(startLoc);
1292
1293 assert((*startBuf == '@') && "bogus @try location");
1294
1295 std::string buf;
1296 // declare a new scope with two variables, _stack and _rethrow.
1297 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1298 buf += "int buf[18/*32-bit i386*/];\n";
1299 buf += "char *pointers[4];} _stack;\n";
1300 buf += "id volatile _rethrow = 0;\n";
1301 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001302 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001303
Chris Lattneraadaf782008-01-31 19:51:04 +00001304 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001305
1306 startLoc = S->getTryBody()->getLocEnd();
1307 startBuf = SM->getCharacterData(startLoc);
1308
1309 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001310
Steve Naroff75730982007-11-07 04:08:17 +00001311 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001312 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1313 if (catchList) {
1314 startLoc = startLoc.getFileLocWithOffset(1);
1315 buf = " /* @catch begin */ else {\n";
1316 buf += " id _caught = objc_exception_extract(&_stack);\n";
1317 buf += " objc_exception_try_enter (&_stack);\n";
1318 buf += " if (_setjmp(_stack.buf))\n";
1319 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1320 buf += " else { /* @catch continue */";
1321
1322 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001323 } else { /* no catch list */
1324 buf = "}\nelse {\n";
1325 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1326 buf += "}";
1327 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001328 }
Steve Naroff75730982007-11-07 04:08:17 +00001329 bool sawIdTypedCatch = false;
1330 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001331 while (catchList) {
1332 Stmt *catchStmt = catchList->getCatchParamStmt();
1333
1334 if (catchList == S->getCatchStmts())
1335 buf = "if ("; // we are generating code for the first catch clause
1336 else
1337 buf = "else if (";
1338 startLoc = catchList->getLocStart();
1339 startBuf = SM->getCharacterData(startLoc);
1340
1341 assert((*startBuf == '@') && "bogus @catch location");
1342
1343 const char *lParenLoc = strchr(startBuf, '(');
1344
Steve Naroffbe4b3332008-02-01 22:08:12 +00001345 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001346 // Now rewrite the body...
1347 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001348 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1349 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001350 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1351 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001352 assert((*bodyBuf == '{') && "bogus @catch body location");
1353
1354 buf += "1) { id _tmp = _caught;";
1355 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1356 buf.c_str(), buf.size());
1357 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001358 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001359 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001360 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001361 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001362 sawIdTypedCatch = true;
1363 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001364 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001365
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001366 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001367 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001368 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001369 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001370 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001371 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001372 }
1373 }
1374 // Now rewrite the body...
1375 lastCatchBody = catchList->getCatchBody();
1376 SourceLocation rParenLoc = catchList->getRParenLoc();
1377 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1378 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1379 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1380 assert((*rParenBuf == ')') && "bogus @catch paren location");
1381 assert((*bodyBuf == '{') && "bogus @catch body location");
1382
1383 buf = " = _caught;";
1384 // Here we replace ") {" with "= _caught;" (which initializes and
1385 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001386 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001387 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001388 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001389 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001390 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001391 catchList = catchList->getNextCatchStmt();
1392 }
1393 // Complete the catch list...
1394 if (lastCatchBody) {
1395 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001396 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1397 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001398
Steve Naroff378f47a2008-09-11 15:29:03 +00001399 // Insert the last (implicit) else clause *before* the right curly brace.
1400 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1401 buf = "} /* last catch end */\n";
1402 buf += "else {\n";
1403 buf += " _rethrow = _caught;\n";
1404 buf += " objc_exception_try_exit(&_stack);\n";
1405 buf += "} } /* @catch end */\n";
1406 if (!S->getFinallyStmt())
1407 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001408 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001409
1410 // Set lastCurlyLoc
1411 lastCurlyLoc = lastCatchBody->getLocEnd();
1412 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001413 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001414 startLoc = finalStmt->getLocStart();
1415 startBuf = SM->getCharacterData(startLoc);
1416 assert((*startBuf == '@') && "bogus @finally start");
1417
1418 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001419 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001420
1421 Stmt *body = finalStmt->getFinallyBody();
1422 SourceLocation startLoc = body->getLocStart();
1423 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001424 assert(*SM->getCharacterData(startLoc) == '{' &&
1425 "bogus @finally body location");
1426 assert(*SM->getCharacterData(endLoc) == '}' &&
1427 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001428
1429 startLoc = startLoc.getFileLocWithOffset(1);
1430 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001431 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001432 endLoc = endLoc.getFileLocWithOffset(-1);
1433 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001434 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001435
1436 // Set lastCurlyLoc
1437 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001438 } else { /* no finally clause - make sure we synthesize an implicit one */
1439 buf = "{ /* implicit finally clause */\n";
1440 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1441 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1442 buf += "}";
1443 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001444 }
1445 // Now emit the final closing curly brace...
1446 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1447 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001448 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001449 return 0;
1450}
1451
Steve Naroffb29b4272008-04-14 22:03:09 +00001452Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001453 return 0;
1454}
1455
Steve Naroffb29b4272008-04-14 22:03:09 +00001456Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001457 return 0;
1458}
1459
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001460// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001461// the throw expression is typically a message expression that's already
1462// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001463Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001464 // Get the start location and compute the semi location.
1465 SourceLocation startLoc = S->getLocStart();
1466 const char *startBuf = SM->getCharacterData(startLoc);
1467
1468 assert((*startBuf == '@') && "bogus @throw location");
1469
1470 std::string buf;
1471 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001472 if (S->getThrowExpr())
1473 buf = "objc_exception_throw(";
1474 else // add an implicit argument
1475 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001476
1477 // handle "@ throw" correctly.
1478 const char *wBuf = strchr(startBuf, 'w');
1479 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1480 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1481
Steve Naroff2bd03922007-11-07 15:32:26 +00001482 const char *semiBuf = strchr(startBuf, ';');
1483 assert((*semiBuf == ';') && "@throw: can't find ';'");
1484 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1485 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001486 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001487 return 0;
1488}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001489
Steve Naroffb29b4272008-04-14 22:03:09 +00001490Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001491 // Create a new string expression.
1492 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001493 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001494 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001495 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1496 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001497 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001498 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001499
Chris Lattner07506182007-11-30 22:53:43 +00001500 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001501 delete Exp;
1502 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001503}
1504
Steve Naroffb29b4272008-04-14 22:03:09 +00001505Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001506 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1507 // Create a call to sel_registerName("selName").
1508 llvm::SmallVector<Expr*, 8> SelExprs;
1509 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001510 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1511 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001512 false, argType, SourceLocation(),
1513 SourceLocation()));
1514 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1515 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001516 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001517 delete Exp;
1518 return SelExp;
1519}
1520
Steve Naroffb29b4272008-04-14 22:03:09 +00001521CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001522 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001523 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001524 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001525
1526 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001527 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001528
1529 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001530 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001531 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1532 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001533
1534 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001535
Steve Naroff934f2762007-10-24 22:48:43 +00001536 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1537}
1538
Steve Naroffd5255f52007-11-01 13:24:47 +00001539static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1540 const char *&startRef, const char *&endRef) {
1541 while (startBuf < endBuf) {
1542 if (*startBuf == '<')
1543 startRef = startBuf; // mark the start.
1544 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001545 if (startRef && *startRef == '<') {
1546 endRef = startBuf; // mark the end.
1547 return true;
1548 }
1549 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001550 }
1551 startBuf++;
1552 }
1553 return false;
1554}
1555
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001556static void scanToNextArgument(const char *&argRef) {
1557 int angle = 0;
1558 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1559 if (*argRef == '<')
1560 angle++;
1561 else if (*argRef == '>')
1562 angle--;
1563 argRef++;
1564 }
1565 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1566}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001567
Steve Naroffb29b4272008-04-14 22:03:09 +00001568bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001569
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001570 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001571 return true;
1572
Steve Naroffd5255f52007-11-01 13:24:47 +00001573 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001574 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001575 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001576 return true; // we have "Class <Protocol> *".
1577 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001578 return false;
1579}
1580
Steve Naroff4f95b752008-07-29 18:15:38 +00001581void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1582 QualType Type = E->getType();
1583 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001584 SourceLocation Loc, EndLoc;
1585
1586 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1587 Loc = ECE->getLParenLoc();
1588 EndLoc = ECE->getRParenLoc();
1589 } else {
1590 Loc = E->getLocStart();
1591 EndLoc = E->getLocEnd();
1592 }
1593 // This will defend against trying to rewrite synthesized expressions.
1594 if (Loc.isInvalid() || EndLoc.isInvalid())
1595 return;
1596
Steve Naroff4f95b752008-07-29 18:15:38 +00001597 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001598 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001599 const char *startRef = 0, *endRef = 0;
1600 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1601 // Get the locations of the startRef, endRef.
1602 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1603 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1604 // Comment out the protocol references.
1605 InsertText(LessLoc, "/*", 2);
1606 InsertText(GreaterLoc, "*/", 2);
1607 }
1608 }
1609}
1610
Steve Naroffb29b4272008-04-14 22:03:09 +00001611void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001612 SourceLocation Loc;
1613 QualType Type;
1614 const FunctionTypeProto *proto = 0;
1615 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1616 Loc = VD->getLocation();
1617 Type = VD->getType();
1618 }
1619 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1620 Loc = FD->getLocation();
1621 // Check for ObjC 'id' and class types that have been adorned with protocol
1622 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1623 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1624 assert(funcType && "missing function type");
1625 proto = dyn_cast<FunctionTypeProto>(funcType);
1626 if (!proto)
1627 return;
1628 Type = proto->getResultType();
1629 }
1630 else
1631 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001632
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001633 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001634 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001635
1636 const char *endBuf = SM->getCharacterData(Loc);
1637 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001638 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001639 startBuf--; // scan backward (from the decl location) for return type.
1640 const char *startRef = 0, *endRef = 0;
1641 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1642 // Get the locations of the startRef, endRef.
1643 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1644 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1645 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001646 InsertText(LessLoc, "/*", 2);
1647 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001648 }
1649 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001650 if (!proto)
1651 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001652 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001653 const char *startBuf = SM->getCharacterData(Loc);
1654 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001655 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1656 if (needToScanForQualifiers(proto->getArgType(i))) {
1657 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001658
Steve Naroffd5255f52007-11-01 13:24:47 +00001659 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001660 // scan forward (from the decl location) for argument types.
1661 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001662 const char *startRef = 0, *endRef = 0;
1663 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1664 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001665 SourceLocation LessLoc =
1666 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1667 SourceLocation GreaterLoc =
1668 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001669 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001670 InsertText(LessLoc, "/*", 2);
1671 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001672 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001673 startBuf = ++endBuf;
1674 }
1675 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001676 // If the function name is derived from a macro expansion, then the
1677 // argument buffer will not follow the name. Need to speak with Chris.
1678 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001679 startBuf++; // scan forward (from the decl location) for argument types.
1680 startBuf++;
1681 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001682 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001683}
1684
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001685// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001686void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001687 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1688 llvm::SmallVector<QualType, 16> ArgTys;
1689 ArgTys.push_back(Context->getPointerType(
1690 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001691 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001692 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001693 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001694 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001695 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001696 SelGetUidIdent, getFuncType,
1697 FunctionDecl::Extern, false, 0);
1698}
1699
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001700// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001701void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001702 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1703 llvm::SmallVector<QualType, 16> ArgTys;
1704 ArgTys.push_back(Context->getPointerType(
1705 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001706 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001707 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001708 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001709 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001710 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001711 SelGetProtoIdent, getFuncType,
1712 FunctionDecl::Extern, false, 0);
1713}
1714
Steve Naroffb29b4272008-04-14 22:03:09 +00001715void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001716 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001717 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001718 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001719 return;
1720 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001721 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001722}
1723
Steve Naroffc0a123c2008-03-11 17:37:02 +00001724// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001725void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001726 if (SuperContructorFunctionDecl)
1727 return;
1728 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1729 llvm::SmallVector<QualType, 16> ArgTys;
1730 QualType argT = Context->getObjCIdType();
1731 assert(!argT.isNull() && "Can't find 'id' type");
1732 ArgTys.push_back(argT);
1733 ArgTys.push_back(argT);
1734 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1735 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001736 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001737 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001738 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001739 msgSendIdent, msgSendType,
1740 FunctionDecl::Extern, false, 0);
1741}
1742
Steve Naroff09b266e2007-10-30 23:14:51 +00001743// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001744void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001745 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1746 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001747 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001748 assert(!argT.isNull() && "Can't find 'id' type");
1749 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001750 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001751 assert(!argT.isNull() && "Can't find 'SEL' type");
1752 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001753 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001754 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001755 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001756 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001757 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001758 msgSendIdent, msgSendType,
1759 FunctionDecl::Extern, false, 0);
1760}
1761
Steve Naroff874e2322007-11-15 10:28:18 +00001762// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001763void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001764 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1765 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001766 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001767 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001768 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001769 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1770 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1771 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001772 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001773 assert(!argT.isNull() && "Can't find 'SEL' type");
1774 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001775 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001776 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001777 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001778 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001779 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001780 msgSendIdent, msgSendType,
1781 FunctionDecl::Extern, false, 0);
1782}
1783
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001784// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001785void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001786 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1787 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001788 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001789 assert(!argT.isNull() && "Can't find 'id' type");
1790 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001791 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001792 assert(!argT.isNull() && "Can't find 'SEL' type");
1793 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001794 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001795 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001796 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001797 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001798 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001799 msgSendIdent, msgSendType,
1800 FunctionDecl::Extern, false, 0);
1801}
1802
1803// SynthMsgSendSuperStretFunctionDecl -
1804// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001805void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001806 IdentifierInfo *msgSendIdent =
1807 &Context->Idents.get("objc_msgSendSuper_stret");
1808 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001809 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001810 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001811 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001812 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1813 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1814 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001815 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001816 assert(!argT.isNull() && "Can't find 'SEL' type");
1817 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001818 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001819 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001820 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001821 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001822 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001823 msgSendIdent, msgSendType,
1824 FunctionDecl::Extern, false, 0);
1825}
1826
Steve Naroff1284db82008-05-08 22:02:18 +00001827// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001828void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001829 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1830 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001831 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001832 assert(!argT.isNull() && "Can't find 'id' type");
1833 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001834 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001835 assert(!argT.isNull() && "Can't find 'SEL' type");
1836 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001837 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001838 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001839 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001840 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001841 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001842 msgSendIdent, msgSendType,
1843 FunctionDecl::Extern, false, 0);
1844}
1845
Steve Naroff09b266e2007-10-30 23:14:51 +00001846// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001847void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001848 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1849 llvm::SmallVector<QualType, 16> ArgTys;
1850 ArgTys.push_back(Context->getPointerType(
1851 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001852 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001853 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001854 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001855 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001856 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001857 getClassIdent, getClassType,
1858 FunctionDecl::Extern, false, 0);
1859}
1860
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001861// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001862void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001863 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1864 llvm::SmallVector<QualType, 16> ArgTys;
1865 ArgTys.push_back(Context->getPointerType(
1866 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001867 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001868 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001869 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001870 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001871 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001872 getClassIdent, getClassType,
1873 FunctionDecl::Extern, false, 0);
1874}
1875
Steve Naroffb29b4272008-04-14 22:03:09 +00001876Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001877 QualType strType = getConstantStringStructType();
1878
1879 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001880
1881 std::string tmpName = InFileName;
1882 unsigned i;
1883 for (i=0; i < tmpName.length(); i++) {
1884 char c = tmpName.at(i);
1885 // replace any non alphanumeric characters with '_'.
1886 if (!isalpha(c) && (c < '0' || c > '9'))
1887 tmpName[i] = '_';
1888 }
1889 S += tmpName;
1890 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001891 S += utostr(NumObjCStringLiterals++);
1892
Steve Naroffba92b2e2008-03-27 22:29:16 +00001893 Preamble += "static __NSConstantStringImpl " + S;
1894 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1895 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001896 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001897 std::string prettyBufS;
1898 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001899 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001900 Preamble += prettyBuf.str();
1901 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001902 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001903 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001904
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001905 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001906 &Context->Idents.get(S.c_str()), strType,
1907 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001908 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1909 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1910 Context->getPointerType(DRE->getType()),
1911 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001912 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001913 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001914 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001915 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001916 delete Exp;
1917 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001918}
1919
Steve Naroffb29b4272008-04-14 22:03:09 +00001920ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001921 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00001922 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001923
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00001924 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
1925 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001926 assert(PT);
1927 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1928 return IT->getDecl();
1929 }
1930 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001931}
1932
1933// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001934QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001935 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001936 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001937 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001938 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001939 QualType FieldTypes[2];
1940
1941 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001942 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001943 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001944 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001945 // Create fields
1946 FieldDecl *FieldDecls[2];
1947
1948 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001949 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001950 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001951
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001952 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00001953 }
1954 return Context->getTagDeclType(SuperStructDecl);
1955}
1956
Steve Naroffb29b4272008-04-14 22:03:09 +00001957QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001958 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001959 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001960 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001961 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001962 QualType FieldTypes[4];
1963
1964 // struct objc_object *receiver;
1965 FieldTypes[0] = Context->getObjCIdType();
1966 // int flags;
1967 FieldTypes[1] = Context->IntTy;
1968 // char *str;
1969 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1970 // long length;
1971 FieldTypes[3] = Context->LongTy;
1972 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001973 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001974
1975 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001976 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001977 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001978
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001979 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001980 }
1981 return Context->getTagDeclType(ConstantStringDecl);
1982}
1983
Steve Naroffb29b4272008-04-14 22:03:09 +00001984Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001985 if (!SelGetUidFunctionDecl)
1986 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001987 if (!MsgSendFunctionDecl)
1988 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001989 if (!MsgSendSuperFunctionDecl)
1990 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001991 if (!MsgSendStretFunctionDecl)
1992 SynthMsgSendStretFunctionDecl();
1993 if (!MsgSendSuperStretFunctionDecl)
1994 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001995 if (!MsgSendFpretFunctionDecl)
1996 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001997 if (!GetClassFunctionDecl)
1998 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001999 if (!GetMetaClassFunctionDecl)
2000 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002001
Steve Naroff874e2322007-11-15 10:28:18 +00002002 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002003 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2004 // May need to use objc_msgSend_stret() as well.
2005 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002006 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002007 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002008 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002009 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002010 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002011 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002012 }
Steve Naroff874e2322007-11-15 10:28:18 +00002013
Steve Naroff934f2762007-10-24 22:48:43 +00002014 // Synthesize a call to objc_msgSend().
2015 llvm::SmallVector<Expr*, 8> MsgExprs;
2016 IdentifierInfo *clsName = Exp->getClassName();
2017
2018 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2019 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002020 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2021 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002022 if (!strcmp(clsName->getName(), "super")) {
2023 MsgSendFlavor = MsgSendSuperFunctionDecl;
2024 if (MsgSendStretFlavor)
2025 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2026 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2027
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002028 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002029 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002030
2031 llvm::SmallVector<Expr*, 4> InitExprs;
2032
2033 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002034 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002035 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002036 Context->getObjCIdType(),
2037 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002038 llvm::SmallVector<Expr*, 8> ClsExprs;
2039 QualType argType = Context->getPointerType(Context->CharTy);
2040 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2041 SuperDecl->getIdentifier()->getLength(),
2042 false, argType, SourceLocation(),
2043 SourceLocation()));
2044 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2045 &ClsExprs[0],
2046 ClsExprs.size());
2047 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002048 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002049 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002050 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002051 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002052 // struct objc_super
2053 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002054 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002055
Steve Naroff23f41272008-03-11 18:14:26 +00002056 if (LangOpts.Microsoft) {
2057 SynthSuperContructorFunctionDecl();
2058 // Simulate a contructor call...
2059 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2060 superType, SourceLocation());
2061 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2062 superType, SourceLocation());
2063 } else {
2064 // (struct objc_super) { <exprs from above> }
2065 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2066 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002067 SourceLocation(), false);
2068 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2069 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002070 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002071 // struct objc_super *
2072 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2073 Context->getPointerType(SuperRep->getType()),
2074 SourceLocation());
2075 MsgExprs.push_back(Unop);
2076 } else {
2077 llvm::SmallVector<Expr*, 8> ClsExprs;
2078 QualType argType = Context->getPointerType(Context->CharTy);
2079 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2080 clsName->getLength(),
2081 false, argType, SourceLocation(),
2082 SourceLocation()));
2083 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2084 &ClsExprs[0],
2085 ClsExprs.size());
2086 MsgExprs.push_back(Cls);
2087 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002088 } else { // instance message.
2089 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002090
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002091 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002092 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002093 if (MsgSendStretFlavor)
2094 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002095 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2096
2097 llvm::SmallVector<Expr*, 4> InitExprs;
2098
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002099 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002100 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002101 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002102 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002103 SourceLocation()),
2104 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002105 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002106
2107 llvm::SmallVector<Expr*, 8> ClsExprs;
2108 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002109 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2110 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002111 false, argType, SourceLocation(),
2112 SourceLocation()));
2113 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002114 &ClsExprs[0],
2115 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002116 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002117 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002118 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002119 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002120 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002121 // struct objc_super
2122 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002123 Expr *SuperRep;
2124
2125 if (LangOpts.Microsoft) {
2126 SynthSuperContructorFunctionDecl();
2127 // Simulate a contructor call...
2128 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2129 superType, SourceLocation());
2130 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2131 superType, SourceLocation());
2132 } else {
2133 // (struct objc_super) { <exprs from above> }
2134 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2135 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002136 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002137 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2138 }
Steve Naroff874e2322007-11-15 10:28:18 +00002139 // struct objc_super *
2140 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2141 Context->getPointerType(SuperRep->getType()),
2142 SourceLocation());
2143 MsgExprs.push_back(Unop);
2144 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002145 // Remove all type-casts because it may contain objc-style types; e.g.
2146 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002147 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002148 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002149 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002150 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002151 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002152 MsgExprs.push_back(recExpr);
2153 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002154 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002155 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002156 llvm::SmallVector<Expr*, 8> SelExprs;
2157 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002158 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2159 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002160 false, argType, SourceLocation(),
2161 SourceLocation()));
2162 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2163 &SelExprs[0], SelExprs.size());
2164 MsgExprs.push_back(SelExp);
2165
2166 // Now push any user supplied arguments.
2167 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002168 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002169 // Make all implicit casts explicit...ICE comes in handy:-)
2170 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2171 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002172 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002173 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002174 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002175 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002176 }
2177 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002178 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002179 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002180 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002181 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002182 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002183 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002184 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002185 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002186 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002187 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002188 // We've transferred the ownership to MsgExprs. Null out the argument in
2189 // the original expression, since we will delete it below.
2190 Exp->setArg(i, 0);
2191 }
Steve Naroffab972d32007-11-04 22:37:50 +00002192 // Generate the funky cast.
2193 CastExpr *cast;
2194 llvm::SmallVector<QualType, 8> ArgTypes;
2195 QualType returnType;
2196
2197 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002198 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2199 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2200 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002201 ArgTypes.push_back(Context->getObjCIdType());
2202 ArgTypes.push_back(Context->getObjCSelType());
2203 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002204 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002205 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002206 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2207 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002208 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002209 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2210 if (isBlockPointerType(t)) {
2211 const BlockPointerType *BPT = t->getAsBlockPointerType();
2212 t = Context->getPointerType(BPT->getPointeeType());
2213 }
Steve Naroff352336b2007-11-05 14:36:37 +00002214 ArgTypes.push_back(t);
2215 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002216 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2217 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002218 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002219 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002220 }
2221 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002222 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002223
2224 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002225 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2226 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002227
2228 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2229 // If we don't do this cast, we get the following bizarre warning/note:
2230 // xx.m:13: warning: function called through a non-compatible type
2231 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002232 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002233 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002234 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002235
Steve Naroffab972d32007-11-04 22:37:50 +00002236 // Now do the "normal" pointer to function cast.
2237 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002238 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002239 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002240 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002241 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002242 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002243
2244 // Don't forget the parens to enforce the proper binding.
2245 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2246
2247 const FunctionType *FT = msgSendType->getAsFunctionType();
2248 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2249 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002250 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002251 if (MsgSendStretFlavor) {
2252 // We have the method which returns a struct/union. Must also generate
2253 // call to objc_msgSend_stret and hang both varieties on a conditional
2254 // expression which dictate which one to envoke depending on size of
2255 // method's return type.
2256
2257 // Create a reference to the objc_msgSend_stret() declaration.
2258 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2259 SourceLocation());
2260 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002261 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002262 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002263 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002264 // Now do the "normal" pointer to function cast.
2265 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002266 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002267 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002268 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002269 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002270
2271 // Don't forget the parens to enforce the proper binding.
2272 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2273
2274 FT = msgSendType->getAsFunctionType();
2275 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2276 FT->getResultType(), SourceLocation());
2277
2278 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002279 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2280 returnType.getAsOpaquePtr(),
2281 Context->getSizeType(),
2282 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002283 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2284 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2285 // For X86 it is more complicated and some kind of target specific routine
2286 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002287 unsigned IntSize =
2288 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002289 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2290 Context->IntTy,
2291 SourceLocation());
2292 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2293 BinaryOperator::LE,
2294 Context->IntTy,
2295 SourceLocation());
2296 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2297 ConditionalOperator *CondExpr =
2298 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002299 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002300 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002301 return ReplacingStmt;
2302}
2303
Steve Naroffb29b4272008-04-14 22:03:09 +00002304Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002305 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002306
Steve Naroff934f2762007-10-24 22:48:43 +00002307 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002308 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002309
Chris Lattnere64b7772007-10-24 16:57:36 +00002310 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002311 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002312}
2313
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002314/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2315/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002316Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002317 if (!GetProtocolFunctionDecl)
2318 SynthGetProtocolFunctionDecl();
2319 // Create a call to objc_getProtocol("ProtocolName").
2320 llvm::SmallVector<Expr*, 8> ProtoExprs;
2321 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002322 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2323 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002324 false, argType, SourceLocation(),
2325 SourceLocation()));
2326 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2327 &ProtoExprs[0],
2328 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002329 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002330 delete Exp;
2331 return ProtoExp;
2332
2333}
2334
Steve Naroffbaf58c32008-05-31 14:15:04 +00002335bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2336 const char *endBuf) {
2337 while (startBuf < endBuf) {
2338 if (*startBuf == '#') {
2339 // Skip whitespace.
2340 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2341 ;
2342 if (!strncmp(startBuf, "if", strlen("if")) ||
2343 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2344 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2345 !strncmp(startBuf, "define", strlen("define")) ||
2346 !strncmp(startBuf, "undef", strlen("undef")) ||
2347 !strncmp(startBuf, "else", strlen("else")) ||
2348 !strncmp(startBuf, "elif", strlen("elif")) ||
2349 !strncmp(startBuf, "endif", strlen("endif")) ||
2350 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2351 !strncmp(startBuf, "include", strlen("include")) ||
2352 !strncmp(startBuf, "import", strlen("import")) ||
2353 !strncmp(startBuf, "include_next", strlen("include_next")))
2354 return true;
2355 }
2356 startBuf++;
2357 }
2358 return false;
2359}
2360
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002361/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002362/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002363void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002364 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002365 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002366 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002367 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002368 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002369 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002370 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002371 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002372 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002373 SourceLocation LocStart = CDecl->getLocStart();
2374 SourceLocation LocEnd = CDecl->getLocEnd();
2375
2376 const char *startBuf = SM->getCharacterData(LocStart);
2377 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002378
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002379 // If no ivars and no root or if its root, directly or indirectly,
2380 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002381 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2382 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002383 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002384 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002385 return;
2386 }
2387
2388 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002389 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002390 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002391 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002392 if (LangOpts.Microsoft)
2393 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002394
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002395 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002396 const char *cursor = strchr(startBuf, '{');
2397 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002398 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002399 // If the buffer contains preprocessor directives, we do more fine-grained
2400 // rewrites. This is intended to fix code that looks like (which occurs in
2401 // NSURL.h, for example):
2402 //
2403 // #ifdef XYZ
2404 // @interface Foo : NSObject
2405 // #else
2406 // @interface FooBar : NSObject
2407 // #endif
2408 // {
2409 // int i;
2410 // }
2411 // @end
2412 //
2413 // This clause is segregated to avoid breaking the common case.
2414 if (BufferContainsPPDirectives(startBuf, cursor)) {
2415 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2416 CDecl->getClassLoc();
2417 const char *endHeader = SM->getCharacterData(L);
2418 endHeader += Lexer::MeasureTokenLength(L, *SM);
2419
Chris Lattner3db6cae2008-07-21 18:19:38 +00002420 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002421 // advance to the end of the referenced protocols.
2422 while (endHeader < cursor && *endHeader != '>') endHeader++;
2423 endHeader++;
2424 }
2425 // rewrite the original header
2426 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2427 } else {
2428 // rewrite the original header *without* disturbing the '{'
2429 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2430 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002431 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002432 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002433 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002434 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002435 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002436 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002437
2438 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002439 SourceLocation OnePastCurly =
2440 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2441 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002442 }
2443 cursor++; // past '{'
2444
2445 // Now comment out any visibility specifiers.
2446 while (cursor < endBuf) {
2447 if (*cursor == '@') {
2448 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002449 // Skip whitespace.
2450 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2451 /*scan*/;
2452
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002453 // FIXME: presence of @public, etc. inside comment results in
2454 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002455 if (!strncmp(cursor, "public", strlen("public")) ||
2456 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002457 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002458 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002459 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002460 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002461 // FIXME: If there are cases where '<' is used in ivar declaration part
2462 // of user code, then scan the ivar list and use needToScanForQualifiers
2463 // for type checking.
2464 else if (*cursor == '<') {
2465 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002466 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002467 cursor = strchr(cursor, '>');
2468 cursor++;
2469 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002470 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002471 } else if (*cursor == '^') { // rewrite block specifier.
2472 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2473 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002474 }
Steve Narofffea763e82007-11-14 19:25:57 +00002475 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002476 }
Steve Narofffea763e82007-11-14 19:25:57 +00002477 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002478 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002479 } else { // we don't have any instance variables - insert super struct.
2480 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2481 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002482 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002483 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002484 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002485 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002486 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002487 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002488 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002489 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002490 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002491}
2492
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002493// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002494/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002495void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002496 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002497 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002498 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002499 const char *ClassName,
2500 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002501 if (MethodBegin == MethodEnd) return;
2502
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002503 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002504 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002505 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002506 SEL _cmd;
2507 char *method_types;
2508 void *_imp;
2509 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002510 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002511 Result += "\nstruct _objc_method {\n";
2512 Result += "\tSEL _cmd;\n";
2513 Result += "\tchar *method_types;\n";
2514 Result += "\tvoid *_imp;\n";
2515 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002516
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002517 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002518 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002519
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002520 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002521
2522 /* struct {
2523 struct _objc_method_list *next_method;
2524 int method_count;
2525 struct _objc_method method_list[];
2526 }
2527 */
2528 Result += "\nstatic struct {\n";
2529 Result += "\tstruct _objc_method_list *next_method;\n";
2530 Result += "\tint method_count;\n";
2531 Result += "\tstruct _objc_method method_list[";
2532 Result += utostr(MethodEnd-MethodBegin);
2533 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002534 Result += prefix;
2535 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2536 Result += "_METHODS_";
2537 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002538 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002539 Result += IsInstanceMethod ? "inst" : "cls";
2540 Result += "_meth\")))= ";
2541 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002542
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002543 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002544 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002545 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002546 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002547 Result += "\", \"";
2548 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002549 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002550 Result += MethodInternalNames[*MethodBegin];
2551 Result += "}\n";
2552 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2553 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002554 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002555 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002556 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002557 Result += "\", \"";
2558 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002559 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002560 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002561 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002562 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002563 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002564}
2565
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002566/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002567void RewriteObjC::
2568RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2569 const char *prefix,
2570 const char *ClassName,
2571 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002572 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002573 if (Protocols.empty()) return;
2574
2575 for (unsigned i = 0; i != Protocols.size(); i++) {
2576 ObjCProtocolDecl *PDecl = Protocols[i];
2577 // Output struct protocol_methods holder of method selector and type.
2578 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2579 /* struct protocol_methods {
2580 SEL _cmd;
2581 char *method_types;
2582 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002583 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002584 Result += "\nstruct protocol_methods {\n";
2585 Result += "\tSEL _cmd;\n";
2586 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002587 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002588
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002589 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002590 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002591 // Do not synthesize the protocol more than once.
2592 if (ObjCSynthesizedProtocols.count(PDecl))
2593 continue;
2594
2595 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2596 unsigned NumMethods = PDecl->getNumInstanceMethods();
2597 /* struct _objc_protocol_method_list {
2598 int protocol_method_count;
2599 struct protocol_methods protocols[];
2600 }
2601 */
2602 Result += "\nstatic struct {\n";
2603 Result += "\tint protocol_method_count;\n";
2604 Result += "\tstruct protocol_methods protocols[";
2605 Result += utostr(NumMethods);
2606 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002607 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002608 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2609 "{\n\t" + utostr(NumMethods) + "\n";
2610
2611 // Output instance methods declared in this protocol.
2612 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2613 E = PDecl->instmeth_end(); I != E; ++I) {
2614 if (I == PDecl->instmeth_begin())
2615 Result += "\t ,{{(SEL)\"";
2616 else
2617 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002618 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002619 std::string MethodTypeString;
2620 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2621 Result += "\", \"";
2622 Result += MethodTypeString;
2623 Result += "\"}\n";
2624 }
2625 Result += "\t }\n};\n";
2626 }
2627
2628 // Output class methods declared in this protocol.
2629 int NumMethods = PDecl->getNumClassMethods();
2630 if (NumMethods > 0) {
2631 /* struct _objc_protocol_method_list {
2632 int protocol_method_count;
2633 struct protocol_methods protocols[];
2634 }
2635 */
2636 Result += "\nstatic struct {\n";
2637 Result += "\tint protocol_method_count;\n";
2638 Result += "\tstruct protocol_methods protocols[";
2639 Result += utostr(NumMethods);
2640 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002641 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002642 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2643 "{\n\t";
2644 Result += utostr(NumMethods);
2645 Result += "\n";
2646
2647 // Output instance methods declared in this protocol.
2648 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2649 E = PDecl->classmeth_end(); I != E; ++I) {
2650 if (I == PDecl->classmeth_begin())
2651 Result += "\t ,{{(SEL)\"";
2652 else
2653 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002654 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002655 std::string MethodTypeString;
2656 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2657 Result += "\", \"";
2658 Result += MethodTypeString;
2659 Result += "\"}\n";
2660 }
2661 Result += "\t }\n};\n";
2662 }
2663
2664 // Output:
2665 /* struct _objc_protocol {
2666 // Objective-C 1.0 extensions
2667 struct _objc_protocol_extension *isa;
2668 char *protocol_name;
2669 struct _objc_protocol **protocol_list;
2670 struct _objc_protocol_method_list *instance_methods;
2671 struct _objc_protocol_method_list *class_methods;
2672 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002673 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002674 static bool objc_protocol = false;
2675 if (!objc_protocol) {
2676 Result += "\nstruct _objc_protocol {\n";
2677 Result += "\tstruct _objc_protocol_extension *isa;\n";
2678 Result += "\tchar *protocol_name;\n";
2679 Result += "\tstruct _objc_protocol **protocol_list;\n";
2680 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2681 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2682 Result += "};\n";
2683
2684 objc_protocol = true;
2685 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002686
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002687 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002688 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002689 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2690 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002691 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002692 Result += "\", 0, ";
2693 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2694 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002695 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002696 Result += ", ";
2697 }
2698 else
2699 Result += "0, ";
2700 if (PDecl->getNumClassMethods() > 0) {
2701 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002702 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002703 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002704 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002705 else
2706 Result += "0\n";
2707 Result += "};\n";
2708
2709 // Mark this protocol as having been generated.
2710 if (!ObjCSynthesizedProtocols.insert(PDecl))
2711 assert(false && "protocol already synthesized");
2712 }
2713 // Output the top lovel protocol meta-data for the class.
2714 /* struct _objc_protocol_list {
2715 struct _objc_protocol_list *next;
2716 int protocol_count;
2717 struct _objc_protocol *class_protocols[];
2718 }
2719 */
2720 Result += "\nstatic struct {\n";
2721 Result += "\tstruct _objc_protocol_list *next;\n";
2722 Result += "\tint protocol_count;\n";
2723 Result += "\tstruct _objc_protocol *class_protocols[";
2724 Result += utostr(Protocols.size());
2725 Result += "];\n} _OBJC_";
2726 Result += prefix;
2727 Result += "_PROTOCOLS_";
2728 Result += ClassName;
2729 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2730 "{\n\t0, ";
2731 Result += utostr(Protocols.size());
2732 Result += "\n";
2733
2734 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002735 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002736 Result += " \n";
2737
2738 for (unsigned i = 1; i != Protocols.size(); i++) {
2739 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002740 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002741 Result += "\n";
2742 }
2743 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002744}
2745
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002746/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002747/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002748void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002749 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002750 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002751 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002752 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002753 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2754 CDecl = CDecl->getNextClassCategory())
2755 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2756 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002757
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002758 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002759 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002760 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002761
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002762 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002763 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002764 true, "CATEGORY_", FullCategoryName.c_str(),
2765 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002766
2767 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002768 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002769 false, "CATEGORY_", FullCategoryName.c_str(),
2770 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002771
2772 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002773 // Null CDecl is case of a category implementation with no category interface
2774 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002775 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002776 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002777
2778 /* struct _objc_category {
2779 char *category_name;
2780 char *class_name;
2781 struct _objc_method_list *instance_methods;
2782 struct _objc_method_list *class_methods;
2783 struct _objc_protocol_list *protocols;
2784 // Objective-C 1.0 extensions
2785 uint32_t size; // sizeof (struct _objc_category)
2786 struct _objc_property_list *instance_properties; // category's own
2787 // @property decl.
2788 };
2789 */
2790
2791 static bool objc_category = false;
2792 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002793 Result += "\nstruct _objc_category {\n";
2794 Result += "\tchar *category_name;\n";
2795 Result += "\tchar *class_name;\n";
2796 Result += "\tstruct _objc_method_list *instance_methods;\n";
2797 Result += "\tstruct _objc_method_list *class_methods;\n";
2798 Result += "\tstruct _objc_protocol_list *protocols;\n";
2799 Result += "\tunsigned int size;\n";
2800 Result += "\tstruct _objc_property_list *instance_properties;\n";
2801 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002802 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002803 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002804 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2805 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002806 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002807 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002808 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002809 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002810 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002811
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002812 if (IDecl->getNumInstanceMethods() > 0) {
2813 Result += "\t, (struct _objc_method_list *)"
2814 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2815 Result += FullCategoryName;
2816 Result += "\n";
2817 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002818 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002819 Result += "\t, 0\n";
2820 if (IDecl->getNumClassMethods() > 0) {
2821 Result += "\t, (struct _objc_method_list *)"
2822 "&_OBJC_CATEGORY_CLASS_METHODS_";
2823 Result += FullCategoryName;
2824 Result += "\n";
2825 }
2826 else
2827 Result += "\t, 0\n";
2828
Chris Lattner780f3292008-07-21 21:32:27 +00002829 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002830 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2831 Result += FullCategoryName;
2832 Result += "\n";
2833 }
2834 else
2835 Result += "\t, 0\n";
2836 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002837}
2838
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002839/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2840/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002841void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002842 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002843 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002844 if (ivar->isBitField()) {
2845 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2846 // place all bitfields at offset 0.
2847 Result += "0";
2848 } else {
2849 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002850 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002851 if (LangOpts.Microsoft)
2852 Result += "_IMPL";
2853 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002854 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002855 Result += ")";
2856 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002857}
2858
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002859//===----------------------------------------------------------------------===//
2860// Meta Data Emission
2861//===----------------------------------------------------------------------===//
2862
Steve Naroffb29b4272008-04-14 22:03:09 +00002863void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002864 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002865 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002866
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002867 // Explictly declared @interface's are already synthesized.
2868 if (CDecl->ImplicitInterfaceDecl()) {
2869 // FIXME: Implementation of a class with no @interface (legacy) doese not
2870 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002871 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002872 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002873
Chris Lattnerbe6df082007-12-12 07:56:42 +00002874 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002875 unsigned NumIvars = !IDecl->ivar_empty()
2876 ? IDecl->ivar_size()
2877 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002878 if (NumIvars > 0) {
2879 static bool objc_ivar = false;
2880 if (!objc_ivar) {
2881 /* struct _objc_ivar {
2882 char *ivar_name;
2883 char *ivar_type;
2884 int ivar_offset;
2885 };
2886 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002887 Result += "\nstruct _objc_ivar {\n";
2888 Result += "\tchar *ivar_name;\n";
2889 Result += "\tchar *ivar_type;\n";
2890 Result += "\tint ivar_offset;\n";
2891 Result += "};\n";
2892
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002893 objc_ivar = true;
2894 }
2895
Steve Naroff946a6932008-03-11 00:12:29 +00002896 /* struct {
2897 int ivar_count;
2898 struct _objc_ivar ivar_list[nIvars];
2899 };
2900 */
2901 Result += "\nstatic struct {\n";
2902 Result += "\tint ivar_count;\n";
2903 Result += "\tstruct _objc_ivar ivar_list[";
2904 Result += utostr(NumIvars);
2905 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002906 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00002907 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002908 "{\n\t";
2909 Result += utostr(NumIvars);
2910 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002911
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002912 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002913 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002914 IVI = IDecl->ivar_begin();
2915 IVE = IDecl->ivar_end();
2916 } else {
2917 IVI = CDecl->ivar_begin();
2918 IVE = CDecl->ivar_end();
2919 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002920 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002921 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002922 Result += "\", \"";
2923 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002924 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002925 Result += StrEncoding;
2926 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002927 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002928 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002929 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002930 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002931 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002932 Result += "\", \"";
2933 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002934 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002935 Result += StrEncoding;
2936 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002937 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002938 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002939 }
2940
2941 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002942 }
2943
2944 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002945 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00002946 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002947
2948 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002949 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00002950 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002951
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002952 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00002953 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00002954 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002955
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002956
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002957 // Declaration of class/meta-class metadata
2958 /* struct _objc_class {
2959 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002960 const char *super_class_name;
2961 char *name;
2962 long version;
2963 long info;
2964 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002965 struct _objc_ivar_list *ivars;
2966 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002967 struct objc_cache *cache;
2968 struct objc_protocol_list *protocols;
2969 const char *ivar_layout;
2970 struct _objc_class_ext *ext;
2971 };
2972 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002973 static bool objc_class = false;
2974 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002975 Result += "\nstruct _objc_class {\n";
2976 Result += "\tstruct _objc_class *isa;\n";
2977 Result += "\tconst char *super_class_name;\n";
2978 Result += "\tchar *name;\n";
2979 Result += "\tlong version;\n";
2980 Result += "\tlong info;\n";
2981 Result += "\tlong instance_size;\n";
2982 Result += "\tstruct _objc_ivar_list *ivars;\n";
2983 Result += "\tstruct _objc_method_list *methods;\n";
2984 Result += "\tstruct objc_cache *cache;\n";
2985 Result += "\tstruct _objc_protocol_list *protocols;\n";
2986 Result += "\tconst char *ivar_layout;\n";
2987 Result += "\tstruct _objc_class_ext *ext;\n";
2988 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002989 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002990 }
2991
2992 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002993 ObjCInterfaceDecl *RootClass = 0;
2994 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002995 while (SuperClass) {
2996 RootClass = SuperClass;
2997 SuperClass = SuperClass->getSuperClass();
2998 }
2999 SuperClass = CDecl->getSuperClass();
3000
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003001 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003002 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003003 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003004 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003005 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003006 Result += "\"";
3007
3008 if (SuperClass) {
3009 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003010 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003011 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003012 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003013 Result += "\"";
3014 }
3015 else {
3016 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003017 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003018 Result += "\"";
3019 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003020 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003021 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003022 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003023 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003024 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003025 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003026 Result += "\n";
3027 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003028 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003029 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003030 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003031 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003032 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003033 Result += ",0,0\n";
3034 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003035 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003036 Result += "\t,0,0,0,0\n";
3037 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003038
3039 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003040 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003041 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003042 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003043 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003044 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003045 if (SuperClass) {
3046 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003047 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003048 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003049 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003050 Result += "\"";
3051 }
3052 else {
3053 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003054 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003055 Result += "\"";
3056 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003057 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003058 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003059 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003060 Result += ",0";
3061 else {
3062 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003063 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003064 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003065 if (LangOpts.Microsoft)
3066 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003067 Result += ")";
3068 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003069 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003070 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003071 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003072 Result += "\n\t";
3073 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003074 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003075 Result += ",0";
3076 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003077 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003078 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003079 Result += ", 0\n\t";
3080 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003081 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003082 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003083 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003084 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003085 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003086 Result += ", 0,0\n";
3087 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003088 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003089 Result += ",0,0,0\n";
3090 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003091}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003092
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003093/// RewriteImplementations - This routine rewrites all method implementations
3094/// and emits meta-data.
3095
Steve Narofface66252008-11-13 20:07:04 +00003096void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003097 int ClsDefCount = ClassImplementation.size();
3098 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003099
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003100 // Rewrite implemented methods
3101 for (int i = 0; i < ClsDefCount; i++)
3102 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003103
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003104 for (int i = 0; i < CatDefCount; i++)
3105 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003106}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003107
Steve Narofface66252008-11-13 20:07:04 +00003108void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3109 int ClsDefCount = ClassImplementation.size();
3110 int CatDefCount = CategoryImplementation.size();
3111
Steve Naroff5df5b762008-05-07 21:23:49 +00003112 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003113 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003114 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003115 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003116 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003117
3118 // For each implemented category, write out all its meta data.
3119 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003120 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003121
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003122 // Write objc_symtab metadata
3123 /*
3124 struct _objc_symtab
3125 {
3126 long sel_ref_cnt;
3127 SEL *refs;
3128 short cls_def_cnt;
3129 short cat_def_cnt;
3130 void *defs[cls_def_cnt + cat_def_cnt];
3131 };
3132 */
3133
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003134 Result += "\nstruct _objc_symtab {\n";
3135 Result += "\tlong sel_ref_cnt;\n";
3136 Result += "\tSEL *refs;\n";
3137 Result += "\tshort cls_def_cnt;\n";
3138 Result += "\tshort cat_def_cnt;\n";
3139 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3140 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003141
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003142 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003143 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003144 Result += "\t0, 0, " + utostr(ClsDefCount)
3145 + ", " + utostr(CatDefCount) + "\n";
3146 for (int i = 0; i < ClsDefCount; i++) {
3147 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003148 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003149 Result += "\n";
3150 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003151
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003152 for (int i = 0; i < CatDefCount; i++) {
3153 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003154 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003155 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003156 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003157 Result += "\n";
3158 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003159
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003160 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003161
3162 // Write objc_module metadata
3163
3164 /*
3165 struct _objc_module {
3166 long version;
3167 long size;
3168 const char *name;
3169 struct _objc_symtab *symtab;
3170 }
3171 */
3172
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003173 Result += "\nstruct _objc_module {\n";
3174 Result += "\tlong version;\n";
3175 Result += "\tlong size;\n";
3176 Result += "\tconst char *name;\n";
3177 Result += "\tstruct _objc_symtab *symtab;\n";
3178 Result += "};\n\n";
3179 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003180 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003181 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3182 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003183 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003184
3185 if (LangOpts.Microsoft) {
3186 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003187 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003188 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3189 Result += "&_OBJC_MODULES;\n";
3190 Result += "#pragma data_seg(pop)\n\n";
3191 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003192}
Chris Lattner311ff022007-10-16 22:36:42 +00003193
Steve Naroff54055232008-10-27 17:20:55 +00003194std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3195 const char *funcName,
3196 std::string Tag) {
3197 const FunctionType *AFT = CE->getFunctionType();
3198 QualType RT = AFT->getResultType();
3199 std::string StructRef = "struct " + Tag;
3200 std::string S = "static " + RT.getAsString() + " __" +
3201 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003202
Steve Naroff54055232008-10-27 17:20:55 +00003203 BlockDecl *BD = CE->getBlockDecl();
3204
3205 if (isa<FunctionTypeNoProto>(AFT)) {
3206 S += "()";
3207 } else if (BD->param_empty()) {
3208 S += "(" + StructRef + " *__cself)";
3209 } else {
3210 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3211 assert(FT && "SynthesizeBlockFunc: No function proto");
3212 S += '(';
3213 // first add the implicit argument.
3214 S += StructRef + " *__cself, ";
3215 std::string ParamStr;
3216 for (BlockDecl::param_iterator AI = BD->param_begin(),
3217 E = BD->param_end(); AI != E; ++AI) {
3218 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003219 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003220 (*AI)->getType().getAsStringInternal(ParamStr);
3221 S += ParamStr;
3222 }
3223 if (FT->isVariadic()) {
3224 if (!BD->param_empty()) S += ", ";
3225 S += "...";
3226 }
3227 S += ')';
3228 }
3229 S += " {\n";
3230
3231 // Create local declarations to avoid rewriting all closure decl ref exprs.
3232 // First, emit a declaration for all "by ref" decls.
3233 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3234 E = BlockByRefDecls.end(); I != E; ++I) {
3235 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003236 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003237 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003238 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003239 }
3240 // Next, emit a declaration for all "by copy" declarations.
3241 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3242 E = BlockByCopyDecls.end(); I != E; ++I) {
3243 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003244 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003245 // Handle nested closure invocation. For example:
3246 //
3247 // void (^myImportedClosure)(void);
3248 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3249 //
3250 // void (^anotherClosure)(void);
3251 // anotherClosure = ^(void) {
3252 // myImportedClosure(); // import and invoke the closure
3253 // };
3254 //
3255 if (isBlockPointerType((*I)->getType()))
3256 S += "struct __block_impl *";
3257 else
3258 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003259 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003260 }
3261 std::string RewrittenStr = RewrittenBlockExprs[CE];
3262 const char *cstr = RewrittenStr.c_str();
3263 while (*cstr++ != '{') ;
3264 S += cstr;
3265 S += "\n";
3266 return S;
3267}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003268
Steve Naroff54055232008-10-27 17:20:55 +00003269std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3270 const char *funcName,
3271 std::string Tag) {
3272 std::string StructRef = "struct " + Tag;
3273 std::string S = "static void __";
3274
3275 S += funcName;
3276 S += "_block_copy_" + utostr(i);
3277 S += "(" + StructRef;
3278 S += "*dst, " + StructRef;
3279 S += "*src) {";
3280 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3281 E = ImportedBlockDecls.end(); I != E; ++I) {
3282 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003283 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003284 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003285 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003286 S += ");}";
3287 }
3288 S += "\nstatic void __";
3289 S += funcName;
3290 S += "_block_dispose_" + utostr(i);
3291 S += "(" + StructRef;
3292 S += "*src) {";
3293 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3294 E = ImportedBlockDecls.end(); I != E; ++I) {
3295 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003296 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003297 S += ");";
3298 }
3299 S += "}\n";
3300 return S;
3301}
3302
3303std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3304 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003305 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003306 std::string Constructor = " " + Tag;
3307
3308 S += " {\n struct __block_impl impl;\n";
3309
3310 if (hasCopyDisposeHelpers)
3311 S += " void *copy;\n void *dispose;\n";
3312
3313 Constructor += "(void *fp";
3314
3315 if (hasCopyDisposeHelpers)
3316 Constructor += ", void *copyHelp, void *disposeHelp";
3317
3318 if (BlockDeclRefs.size()) {
3319 // Output all "by copy" declarations.
3320 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3321 E = BlockByCopyDecls.end(); I != E; ++I) {
3322 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003323 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003324 std::string ArgName = "_" + FieldName;
3325 // Handle nested closure invocation. For example:
3326 //
3327 // void (^myImportedBlock)(void);
3328 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3329 //
3330 // void (^anotherBlock)(void);
3331 // anotherBlock = ^(void) {
3332 // myImportedBlock(); // import and invoke the closure
3333 // };
3334 //
3335 if (isBlockPointerType((*I)->getType())) {
3336 S += "struct __block_impl *";
3337 Constructor += ", void *" + ArgName;
3338 } else {
3339 (*I)->getType().getAsStringInternal(FieldName);
3340 (*I)->getType().getAsStringInternal(ArgName);
3341 Constructor += ", " + ArgName;
3342 }
3343 S += FieldName + ";\n";
3344 }
3345 // Output all "by ref" declarations.
3346 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3347 E = BlockByRefDecls.end(); I != E; ++I) {
3348 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003349 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003350 std::string ArgName = "_" + FieldName;
3351 // Handle nested closure invocation. For example:
3352 //
3353 // void (^myImportedBlock)(void);
3354 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3355 //
3356 // void (^anotherBlock)(void);
3357 // anotherBlock = ^(void) {
3358 // myImportedBlock(); // import and invoke the closure
3359 // };
3360 //
3361 if (isBlockPointerType((*I)->getType())) {
3362 S += "struct __block_impl *";
3363 Constructor += ", void *" + ArgName;
3364 } else {
3365 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3366 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3367 Constructor += ", " + ArgName;
3368 }
3369 S += FieldName + "; // by ref\n";
3370 }
3371 // Finish writing the constructor.
3372 // FIXME: handle NSConcreteGlobalBlock.
3373 Constructor += ", int flags=0) {\n";
3374 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3375 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3376
3377 if (hasCopyDisposeHelpers)
3378 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3379
3380 // Initialize all "by copy" arguments.
3381 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3382 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003383 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003384 Constructor += " ";
3385 if (isBlockPointerType((*I)->getType()))
3386 Constructor += Name + " = (struct __block_impl *)_";
3387 else
3388 Constructor += Name + " = _";
3389 Constructor += Name + ";\n";
3390 }
3391 // Initialize all "by ref" arguments.
3392 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3393 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003394 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003395 Constructor += " ";
3396 if (isBlockPointerType((*I)->getType()))
3397 Constructor += Name + " = (struct __block_impl *)_";
3398 else
3399 Constructor += Name + " = _";
3400 Constructor += Name + ";\n";
3401 }
3402 } else {
3403 // Finish writing the constructor.
3404 // FIXME: handle NSConcreteGlobalBlock.
3405 Constructor += ", int flags=0) {\n";
3406 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3407 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3408 if (hasCopyDisposeHelpers)
3409 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3410 }
3411 Constructor += " ";
3412 Constructor += "}\n";
3413 S += Constructor;
3414 S += "};\n";
3415 return S;
3416}
3417
3418void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3419 const char *FunName) {
3420 // Insert closures that were part of the function.
3421 for (unsigned i = 0; i < Blocks.size(); i++) {
3422
3423 CollectBlockDeclRefInfo(Blocks[i]);
3424
3425 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3426
3427 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3428 ImportedBlockDecls.size() > 0);
3429
3430 InsertText(FunLocStart, CI.c_str(), CI.size());
3431
3432 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3433
3434 InsertText(FunLocStart, CF.c_str(), CF.size());
3435
3436 if (ImportedBlockDecls.size()) {
3437 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3438 InsertText(FunLocStart, HF.c_str(), HF.size());
3439 }
3440
3441 BlockDeclRefs.clear();
3442 BlockByRefDecls.clear();
3443 BlockByCopyDecls.clear();
3444 BlockCallExprs.clear();
3445 ImportedBlockDecls.clear();
3446 }
3447 Blocks.clear();
3448 RewrittenBlockExprs.clear();
3449}
3450
3451void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3452 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003453 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003454
3455 SynthesizeBlockLiterals(FunLocStart, FuncName);
3456}
3457
3458void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003459 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3460 //SourceLocation FunLocStart = MD->getLocStart();
3461 // FIXME: This hack works around a bug in Rewrite.InsertText().
3462 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003463 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003464 // Convert colons to underscores.
3465 std::string::size_type loc = 0;
3466 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3467 FuncName.replace(loc, 1, "_");
3468
3469 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3470}
3471
3472void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3473 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3474 CI != E; ++CI)
3475 if (*CI) {
3476 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3477 GetBlockDeclRefExprs(CBE->getBody());
3478 else
3479 GetBlockDeclRefExprs(*CI);
3480 }
3481 // Handle specific things.
3482 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3483 // FIXME: Handle enums.
3484 if (!isa<FunctionDecl>(CDRE->getDecl()))
3485 BlockDeclRefs.push_back(CDRE);
3486 return;
3487}
3488
3489void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3490 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3491 CI != E; ++CI)
3492 if (*CI) {
3493 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3494 GetBlockCallExprs(CBE->getBody());
3495 else
3496 GetBlockCallExprs(*CI);
3497 }
3498
3499 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3500 if (CE->getCallee()->getType()->isBlockPointerType()) {
3501 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3502 }
3503 }
3504 return;
3505}
3506
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003507Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003508 // Navigate to relevant type information.
3509 const char *closureName = 0;
3510 const BlockPointerType *CPT = 0;
3511
3512 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003513 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003514 CPT = DRE->getType()->getAsBlockPointerType();
3515 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003516 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003517 CPT = CDRE->getType()->getAsBlockPointerType();
3518 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003519 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003520 CPT = MExpr->getType()->getAsBlockPointerType();
3521 } else {
3522 assert(1 && "RewriteBlockClass: Bad type");
3523 }
3524 assert(CPT && "RewriteBlockClass: Bad type");
3525 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3526 assert(FT && "RewriteBlockClass: Bad type");
3527 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3528 // FTP will be null for closures that don't take arguments.
3529
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003530 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3531 SourceLocation(),
3532 &Context->Idents.get("__block_impl"));
3533 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003534
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003535 // Generate a funky cast.
3536 llvm::SmallVector<QualType, 8> ArgTypes;
3537
3538 // Push the block argument type.
3539 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003540 if (FTP) {
3541 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003542 E = FTP->arg_type_end(); I && (I != E); ++I) {
3543 QualType t = *I;
3544 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3545 if (isBlockPointerType(t)) {
3546 const BlockPointerType *BPT = t->getAsBlockPointerType();
3547 t = Context->getPointerType(BPT->getPointeeType());
3548 }
3549 ArgTypes.push_back(t);
3550 }
Steve Naroff54055232008-10-27 17:20:55 +00003551 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003552 // Now do the pointer to function cast.
3553 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3554 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3555
3556 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003557
Steve Naroffb2f9e512008-11-03 23:29:32 +00003558 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003559 // Don't forget the parens to enforce the proper binding.
3560 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3561 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003562
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003563 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3564 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3565 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3566
Steve Naroffb2f9e512008-11-03 23:29:32 +00003567 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003568 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3569
3570 llvm::SmallVector<Expr*, 8> BlkExprs;
3571 // Add the implicit argument.
3572 BlkExprs.push_back(BlkCast);
3573 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003574 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3575 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003576 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003577 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003578 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3579 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003580}
3581
3582void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003583 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3584 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003585}
3586
3587void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3588 // FIXME: Add more elaborate code generation required by the ABI.
3589 InsertText(BDRE->getLocStart(), "*", 1);
3590}
3591
Steve Naroffb2f9e512008-11-03 23:29:32 +00003592void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3593 SourceLocation LocStart = CE->getLParenLoc();
3594 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003595
3596 // Need to avoid trying to rewrite synthesized casts.
3597 if (LocStart.isInvalid())
3598 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003599 // Need to avoid trying to rewrite casts contained in macros.
3600 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3601 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003602
Steve Naroff54055232008-10-27 17:20:55 +00003603 const char *startBuf = SM->getCharacterData(LocStart);
3604 const char *endBuf = SM->getCharacterData(LocEnd);
3605
3606 // advance the location to startArgList.
3607 const char *argPtr = startBuf;
3608
3609 while (*argPtr++ && (argPtr < endBuf)) {
3610 switch (*argPtr) {
3611 case '^':
3612 // Replace the '^' with '*'.
3613 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3614 ReplaceText(LocStart, 1, "*", 1);
3615 break;
3616 }
3617 }
3618 return;
3619}
3620
3621void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3622 SourceLocation DeclLoc = FD->getLocation();
3623 unsigned parenCount = 0;
3624
3625 // We have 1 or more arguments that have closure pointers.
3626 const char *startBuf = SM->getCharacterData(DeclLoc);
3627 const char *startArgList = strchr(startBuf, '(');
3628
3629 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3630
3631 parenCount++;
3632 // advance the location to startArgList.
3633 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3634 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3635
3636 const char *argPtr = startArgList;
3637
3638 while (*argPtr++ && parenCount) {
3639 switch (*argPtr) {
3640 case '^':
3641 // Replace the '^' with '*'.
3642 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3643 ReplaceText(DeclLoc, 1, "*", 1);
3644 break;
3645 case '(':
3646 parenCount++;
3647 break;
3648 case ')':
3649 parenCount--;
3650 break;
3651 }
3652 }
3653 return;
3654}
3655
3656bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3657 const FunctionTypeProto *FTP;
3658 const PointerType *PT = QT->getAsPointerType();
3659 if (PT) {
3660 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3661 } else {
3662 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3663 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3664 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3665 }
3666 if (FTP) {
3667 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3668 E = FTP->arg_type_end(); I != E; ++I)
3669 if (isBlockPointerType(*I))
3670 return true;
3671 }
3672 return false;
3673}
3674
3675void RewriteObjC::GetExtentOfArgList(const char *Name,
3676 const char *&LParen, const char *&RParen) {
3677 const char *argPtr = strchr(Name, '(');
3678 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3679
3680 LParen = argPtr; // output the start.
3681 argPtr++; // skip past the left paren.
3682 unsigned parenCount = 1;
3683
3684 while (*argPtr && parenCount) {
3685 switch (*argPtr) {
3686 case '(': parenCount++; break;
3687 case ')': parenCount--; break;
3688 default: break;
3689 }
3690 if (parenCount) argPtr++;
3691 }
3692 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3693 RParen = argPtr; // output the end
3694}
3695
3696void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3697 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3698 RewriteBlockPointerFunctionArgs(FD);
3699 return;
3700 }
3701 // Handle Variables and Typedefs.
3702 SourceLocation DeclLoc = ND->getLocation();
3703 QualType DeclT;
3704 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3705 DeclT = VD->getType();
3706 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3707 DeclT = TDD->getUnderlyingType();
3708 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3709 DeclT = FD->getType();
3710 else
3711 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3712
3713 const char *startBuf = SM->getCharacterData(DeclLoc);
3714 const char *endBuf = startBuf;
3715 // scan backward (from the decl location) for the end of the previous decl.
3716 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3717 startBuf--;
3718
3719 // *startBuf != '^' if we are dealing with a pointer to function that
3720 // may take block argument types (which will be handled below).
3721 if (*startBuf == '^') {
3722 // Replace the '^' with '*', computing a negative offset.
3723 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3724 ReplaceText(DeclLoc, 1, "*", 1);
3725 }
3726 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3727 // Replace the '^' with '*' for arguments.
3728 DeclLoc = ND->getLocation();
3729 startBuf = SM->getCharacterData(DeclLoc);
3730 const char *argListBegin, *argListEnd;
3731 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3732 while (argListBegin < argListEnd) {
3733 if (*argListBegin == '^') {
3734 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3735 ReplaceText(CaretLoc, 1, "*", 1);
3736 }
3737 argListBegin++;
3738 }
3739 }
3740 return;
3741}
3742
3743void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3744 // Add initializers for any closure decl refs.
3745 GetBlockDeclRefExprs(Exp->getBody());
3746 if (BlockDeclRefs.size()) {
3747 // Unique all "by copy" declarations.
3748 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3749 if (!BlockDeclRefs[i]->isByRef())
3750 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3751 // Unique all "by ref" declarations.
3752 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3753 if (BlockDeclRefs[i]->isByRef()) {
3754 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3755 }
3756 // Find any imported blocks...they will need special attention.
3757 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3758 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003759 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003760 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3761 }
3762 }
3763}
3764
Steve Narofffa15fd92008-10-28 20:29:00 +00003765FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3766 IdentifierInfo *ID = &Context->Idents.get(name);
3767 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3768 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3769 ID, FType, FunctionDecl::Extern, false, 0);
3770}
3771
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003772Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003773 Blocks.push_back(Exp);
3774
3775 CollectBlockDeclRefInfo(Exp);
3776 std::string FuncName;
3777
3778 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003779 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003780 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00003781 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003782 // Convert colons to underscores.
3783 std::string::size_type loc = 0;
3784 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3785 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003786 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003787 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00003788
3789 std::string BlockNumber = utostr(Blocks.size()-1);
3790
3791 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3792 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3793
3794 // Get a pointer to the function type so we can cast appropriately.
3795 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3796
3797 FunctionDecl *FD;
3798 Expr *NewRep;
3799
3800 // Simulate a contructor call...
3801 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3802 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3803
3804 llvm::SmallVector<Expr*, 4> InitExprs;
3805
Steve Narofffdc03722008-10-29 21:23:59 +00003806 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003807 FD = SynthBlockInitFunctionDecl(Func.c_str());
3808 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3809 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003810 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003811 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003812
3813 if (ImportedBlockDecls.size()) {
3814 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003815 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3816 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3817 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003818 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003819 InitExprs.push_back(castExpr);
3820
Steve Narofffa15fd92008-10-28 20:29:00 +00003821 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003822 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3823 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3824 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003825 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003826 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003827 }
3828 // Add initializers for any closure decl refs.
3829 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00003830 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00003831 // Output all "by copy" declarations.
3832 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3833 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003834 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003835 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00003836 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003837 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003838 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003839 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003840 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3841 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003842 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003843 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003844 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003845 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003846 }
Steve Narofffdc03722008-10-29 21:23:59 +00003847 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003848 }
3849 // Output all "by ref" declarations.
3850 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3851 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003852 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003853 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3854 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3855 Context->getPointerType(Exp->getType()),
3856 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00003857 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003858 }
3859 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003860 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3861 FType, SourceLocation());
3862 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3863 Context->getPointerType(NewRep->getType()),
3864 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00003865 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003866 BlockDeclRefs.clear();
3867 BlockByRefDecls.clear();
3868 BlockByCopyDecls.clear();
3869 ImportedBlockDecls.clear();
3870 return NewRep;
3871}
3872
3873//===----------------------------------------------------------------------===//
3874// Function Body / Expression rewriting
3875//===----------------------------------------------------------------------===//
3876
3877Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3878 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3879 isa<DoStmt>(S) || isa<ForStmt>(S))
3880 Stmts.push_back(S);
3881 else if (isa<ObjCForCollectionStmt>(S)) {
3882 Stmts.push_back(S);
3883 ObjCBcLabelNo.push_back(++BcLabelCount);
3884 }
3885
3886 SourceRange OrigStmtRange = S->getSourceRange();
3887
3888 // Perform a bottom up rewrite of all children.
3889 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3890 CI != E; ++CI)
3891 if (*CI) {
3892 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3893 if (newStmt)
3894 *CI = newStmt;
3895 }
3896
3897 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
3898 // Rewrite the block body in place.
3899 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
3900
3901 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003902 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
3903 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00003904
3905 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
3906 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003907 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00003908 return blockTranscribed;
3909 }
3910 // Handle specific things.
3911 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
3912 return RewriteAtEncode(AtEncode);
3913
3914 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
3915 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
3916
3917 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
3918 return RewriteAtSelector(AtSelector);
3919
3920 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
3921 return RewriteObjCStringLiteral(AtString);
3922
3923 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
3924 // Before we rewrite it, put the original message expression in a comment.
3925 SourceLocation startLoc = MessExpr->getLocStart();
3926 SourceLocation endLoc = MessExpr->getLocEnd();
3927
3928 const char *startBuf = SM->getCharacterData(startLoc);
3929 const char *endBuf = SM->getCharacterData(endLoc);
3930
3931 std::string messString;
3932 messString += "// ";
3933 messString.append(startBuf, endBuf-startBuf+1);
3934 messString += "\n";
3935
3936 // FIXME: Missing definition of
3937 // InsertText(clang::SourceLocation, char const*, unsigned int).
3938 // InsertText(startLoc, messString.c_str(), messString.size());
3939 // Tried this, but it didn't work either...
3940 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
3941 return RewriteMessageExpr(MessExpr);
3942 }
3943
3944 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
3945 return RewriteObjCTryStmt(StmtTry);
3946
3947 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
3948 return RewriteObjCSynchronizedStmt(StmtTry);
3949
3950 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
3951 return RewriteObjCThrowStmt(StmtThrow);
3952
3953 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
3954 return RewriteObjCProtocolExpr(ProtocolExp);
3955
3956 if (ObjCForCollectionStmt *StmtForCollection =
3957 dyn_cast<ObjCForCollectionStmt>(S))
3958 return RewriteObjCForCollectionStmt(StmtForCollection,
3959 OrigStmtRange.getEnd());
3960 if (BreakStmt *StmtBreakStmt =
3961 dyn_cast<BreakStmt>(S))
3962 return RewriteBreakStmt(StmtBreakStmt);
3963 if (ContinueStmt *StmtContinueStmt =
3964 dyn_cast<ContinueStmt>(S))
3965 return RewriteContinueStmt(StmtContinueStmt);
3966
3967 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
3968 // and cast exprs.
3969 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
3970 // FIXME: What we're doing here is modifying the type-specifier that
3971 // precedes the first Decl. In the future the DeclGroup should have
3972 // a separate type-specifier that we can rewrite.
3973 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
3974
3975 // Blocks rewrite rules.
3976 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
3977 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003978 ScopedDecl *SD = *DI;
3979 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
3980 if (isBlockPointerType(ND->getType()))
3981 RewriteBlockPointerDecl(ND);
3982 else if (ND->getType()->isFunctionPointerType())
3983 CheckFunctionPointerDecl(ND->getType(), ND);
3984 }
3985 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
3986 if (isBlockPointerType(TD->getUnderlyingType()))
3987 RewriteBlockPointerDecl(TD);
3988 else if (TD->getUnderlyingType()->isFunctionPointerType())
3989 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
3990 }
3991 }
3992 }
3993
3994 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
3995 RewriteObjCQualifiedInterfaceTypes(CE);
3996
3997 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3998 isa<DoStmt>(S) || isa<ForStmt>(S)) {
3999 assert(!Stmts.empty() && "Statement stack is empty");
4000 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4001 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4002 && "Statement stack mismatch");
4003 Stmts.pop_back();
4004 }
4005 // Handle blocks rewriting.
4006 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4007 if (BDRE->isByRef())
4008 RewriteBlockDeclRefExpr(BDRE);
4009 }
4010 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004011 if (CE->getCallee()->getType()->isBlockPointerType()) {
4012 Stmt *BlockCall = SynthesizeBlockCall(CE);
4013 ReplaceStmt(S, BlockCall);
4014 return BlockCall;
4015 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004016 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004017 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004018 RewriteCastExpr(CE);
4019 }
4020#if 0
4021 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4022 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4023 // Get the new text.
4024 std::string SStr;
4025 llvm::raw_string_ostream Buf(SStr);
4026 Replacement->printPretty(Buf);
4027 const std::string &Str = Buf.str();
4028
4029 printf("CAST = %s\n", &Str[0]);
4030 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4031 delete S;
4032 return Replacement;
4033 }
4034#endif
4035 // Return this stmt unmodified.
4036 return S;
4037}
4038
4039/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4040/// main file of the input.
4041void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4042 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4043 // Since function prototypes don't have ParmDecl's, we check the function
4044 // prototype. This enables us to rewrite function declarations and
4045 // definitions using the same code.
4046 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4047
4048 if (Stmt *Body = FD->getBody()) {
4049 CurFunctionDef = FD;
4050 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4051 // This synthesizes and inserts the block "impl" struct, invoke function,
4052 // and any copy/dispose helper functions.
4053 InsertBlockLiteralsWithinFunction(FD);
4054 CurFunctionDef = 0;
4055 }
4056 return;
4057 }
4058 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4059 if (Stmt *Body = MD->getBody()) {
4060 //Body->dump();
4061 CurMethodDef = MD;
4062 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4063 InsertBlockLiteralsWithinMethod(MD);
4064 CurMethodDef = 0;
4065 }
4066 }
4067 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4068 ClassImplementation.push_back(CI);
4069 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4070 CategoryImplementation.push_back(CI);
4071 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4072 RewriteForwardClassDecl(CD);
4073 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4074 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004075 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004076 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004077 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004078 CheckFunctionPointerDecl(VD->getType(), VD);
4079 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004080 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004081 RewriteCastExpr(CE);
4082 }
4083 }
4084 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004085 if (VD->getInit()) {
4086 GlobalVarDecl = VD;
4087 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004088 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004089 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004090 GlobalVarDecl = 0;
4091
4092 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004093 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004094 RewriteCastExpr(CE);
4095 }
4096 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004097 return;
4098 }
4099 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4100 if (isBlockPointerType(TD->getUnderlyingType()))
4101 RewriteBlockPointerDecl(TD);
4102 else if (TD->getUnderlyingType()->isFunctionPointerType())
4103 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4104 return;
4105 }
4106 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4107 if (RD->isDefinition()) {
4108 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4109 e = RD->field_end(); i != e; ++i) {
4110 FieldDecl *FD = *i;
4111 if (isBlockPointerType(FD->getType()))
4112 RewriteBlockPointerDecl(FD);
4113 }
4114 }
4115 return;
4116 }
4117 // Nothing yet.
4118}
4119
4120void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4121 // Get the top-level buffer that this corresponds to.
4122
4123 // Rewrite tabs if we care.
4124 //RewriteTabs();
4125
4126 if (Diags.hasErrorOccurred())
4127 return;
4128
4129 // Create the output file.
4130
4131 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4132 llvm::raw_ostream *OutFile;
4133 if (OutFileName == "-") {
4134 OutFile = &llvm::outs();
4135 } else if (!OutFileName.empty()) {
4136 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004137 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004138 OwnedStream.reset(OutFile);
4139 } else if (InFileName == "-") {
4140 OutFile = &llvm::outs();
4141 } else {
4142 llvm::sys::Path Path(InFileName);
4143 Path.eraseSuffix();
4144 Path.appendSuffix("cpp");
4145 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004146 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004147 OwnedStream.reset(OutFile);
4148 }
4149
4150 RewriteInclude();
4151
4152 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4153 Preamble.c_str(), Preamble.size(), false);
4154
Steve Naroff0aab7962008-11-14 14:10:01 +00004155 if (ClassImplementation.size() || CategoryImplementation.size())
4156 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004157
4158 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4159 // we are done.
4160 if (const RewriteBuffer *RewriteBuf =
4161 Rewrite.getRewriteBufferFor(MainFileID)) {
4162 //printf("Changed:\n");
4163 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4164 } else {
4165 fprintf(stderr, "No changes\n");
4166 }
Steve Narofface66252008-11-13 20:07:04 +00004167
Steve Naroff0aab7962008-11-14 14:10:01 +00004168 if (ClassImplementation.size() || CategoryImplementation.size()) {
4169 // Rewrite Objective-c meta data*
4170 std::string ResultStr;
4171 SynthesizeMetaDataIntoBuffer(ResultStr);
4172 // Emit metadata.
4173 *OutFile << ResultStr;
4174 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004175 OutFile->flush();
4176}
4177