blob: 0e81df72c595e7a2c14c6a9169fa77d9c96bb9d3 [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
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/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"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.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"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner2c64b7b2007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Ted Kremeneka526c5c2008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Steve Naroffebf2b562007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Fariborz Jahanianb586cce2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Steve Naroff874e2322007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Steve Naroff621edce2009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Steve Naroffa7b402d2008-03-28 22:26:09 +0000115 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000116 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000120
Steve Naroffba92b2e2008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000122
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff54055232008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroff4c3580e2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000151
Steve Naroff54055232008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Steve Naroffb619d952008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000158 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000159 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Steve Naroff4c3580e2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000182
Steve Naroffb619d952008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff4c3580e2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000195 }
Steve Naroffb619d952008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
198 // Measaure the old text.
199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Benjamin Kramerd999b372010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattneraadaf782008-01-31 19:51:04 +0000232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramerd999b372010-02-14 14:14:16 +0000233 llvm::StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000234 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000235 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240 }
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattnerf04da132007-10-24 17:06:59 +0000242 // Syntactic Rewriting.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000243 void RewriteInclude();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000244 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000245 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
246 ObjCImplementationDecl *IMD,
247 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000248 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000249 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000250 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
251 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000252 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
253 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000254 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
255 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000256 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
257 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
258 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
259 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000260 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000261 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000262 void RewriteBlockPointerType(std::string& Str, QualType Type);
263 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000266 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000267 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000268 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000271 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000272 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnerf04da132007-10-24 17:06:59 +0000274 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000275 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000276 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Steve Naroff8599e7a2008-12-08 16:43:47 +0000278 Stmt *CurrentBody;
279 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnere64b7772007-10-24 16:57:36 +0000281 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000282 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
283 bool &replaced);
284 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000285 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
286 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000287 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000288 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000289 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000290 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000291 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000292 void WarnAboutReturnGotoStmts(Stmt *S);
293 void HasReturnStmts(Stmt *S, bool &hasReturns);
294 void RewriteTryReturnStmts(Stmt *S);
295 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000296 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000297 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000298 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000299 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
300 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000301 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000302 Expr **args, unsigned nargs,
303 SourceLocation StartLoc=SourceLocation(),
304 SourceLocation EndLoc=SourceLocation());
305 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
306 SourceLocation StartLoc=SourceLocation(),
307 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000308 Stmt *RewriteBreakStmt(BreakStmt *S);
309 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000310 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Steve Naroff09b266e2007-10-30 23:14:51 +0000312 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000313 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000314 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000315 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000316 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000317 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000318 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000319 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000320 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000321 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chris Lattnerf04da132007-10-24 17:06:59 +0000323 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000324 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000325 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000327 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000328 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Douglas Gregor653f1b12009-04-23 01:02:12 +0000330 template<typename MethodIterator>
331 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
332 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000333 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000334 llvm::StringRef prefix,
335 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000336 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Steve Naroff621edce2009-04-29 16:37:50 +0000338 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000339 llvm::StringRef prefix,
340 llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000341 std::string &Result);
342 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000343 llvm::StringRef prefix,
344 llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000345 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000346 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000347 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000348 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000349 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000350 void RewriteImplementations();
351 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Steve Naroff54055232008-10-27 17:20:55 +0000353 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000354 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000355 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Steve Naroff54055232008-10-27 17:20:55 +0000357 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
358 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000359
360 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000361 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000362 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000363 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000364 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000365 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000366 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000367
368 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000369 llvm::StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000370 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000371 llvm::StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000372 std::string SynthesizeBlockImpl(BlockExpr *CE,
373 std::string Tag, std::string Desc);
374 std::string SynthesizeBlockDescriptor(std::string DescTag,
375 std::string ImplTag,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000376 int i, llvm::StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000377 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000378 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000379 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000380 llvm::StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000381 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Steve Naroff54055232008-10-27 17:20:55 +0000383 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000384 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000385 void GetInnerBlockDeclRefExprs(Stmt *S,
386 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000387 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Steve Naroff54055232008-10-27 17:20:55 +0000389 // We avoid calling Type::isBlockPointerType(), since it operates on the
390 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000391 bool isTopLevelBlockPointerType(QualType T) {
392 return isa<BlockPointerType>(T);
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000395 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
396 /// to a function pointer type and upon success, returns true; false
397 /// otherwise.
398 bool convertBlockPointerToFunctionPointer(QualType &T) {
399 if (isTopLevelBlockPointerType(T)) {
400 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
401 T = Context->getPointerType(BPT->getPointeeType());
402 return true;
403 }
404 return false;
405 }
406
Steve Naroff54055232008-10-27 17:20:55 +0000407 // FIXME: This predicate seems like it would be useful to add to ASTContext.
408 bool isObjCType(QualType T) {
409 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
410 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Steve Naroff54055232008-10-27 17:20:55 +0000412 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Steve Naroff54055232008-10-27 17:20:55 +0000414 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
415 OCT == Context->getCanonicalType(Context->getObjCClassType()))
416 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Ted Kremenek6217b802009-07-29 21:53:49 +0000418 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000419 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000420 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000421 return true;
422 }
423 return false;
424 }
425 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000426 void GetExtentOfArgList(const char *Name, const char *&LParen,
427 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000428 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Daniel Dunbar4087f272010-08-17 22:39:59 +0000430 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000431 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
432 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Steve Naroff621edce2009-04-29 16:37:50 +0000434 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000435 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000436 if (From[i] == '"')
437 To += "\\\"";
438 else
439 To += From[i];
440 }
441 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000442 };
John McCall9d125032010-01-15 18:39:57 +0000443
444 // Helper function: create a CStyleCastExpr with trivial type source info.
445 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000446 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000447 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf871d0c2010-08-07 06:22:56 +0000448 return CStyleCastExpr::Create(*Ctx, Ty, Kind, E, 0, TInfo,
449 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000450 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000451}
452
Mike Stump1eb44332009-09-09 15:08:12 +0000453void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
454 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000455 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000456 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000457 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000458 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000459 // All the args are checked/rewritten. Don't call twice!
460 RewriteBlockPointerDecl(D);
461 break;
462 }
463 }
464}
465
466void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000467 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000468 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000469 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000470}
471
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000472static bool IsHeaderFile(const std::string &Filename) {
473 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000475 if (DotPos == std::string::npos) {
476 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000477 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000480 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
481 // C header: .h
482 // C++ header: .hh or .H;
483 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000484}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000485
Eli Friedman66d6f042009-05-18 22:20:00 +0000486RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000487 Diagnostic &D, const LangOptions &LOpts,
488 bool silenceMacroWarn)
489 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
490 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000491 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000492 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000493 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000494 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000495 "rewriter doesn't support user-specified control flow semantics "
496 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000497}
498
Eli Friedmanbce831b2009-05-18 22:29:17 +0000499ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
500 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000501 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000502 const LangOptions &LOpts,
503 bool SilenceRewriteMacroWarning) {
504 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000505}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000506
Steve Naroffb29b4272008-04-14 22:03:09 +0000507void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000508 Context = &context;
509 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000510 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000511 MsgSendFunctionDecl = 0;
512 MsgSendSuperFunctionDecl = 0;
513 MsgSendStretFunctionDecl = 0;
514 MsgSendSuperStretFunctionDecl = 0;
515 MsgSendFpretFunctionDecl = 0;
516 GetClassFunctionDecl = 0;
517 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000518 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000519 SelGetUidFunctionDecl = 0;
520 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000521 ConstantStringClassReference = 0;
522 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000523 CurMethodDef = 0;
524 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000525 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000526 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000527 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000528 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000529 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000530 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000531 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000532 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000533 PropParentMap = 0;
534 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000535 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000536 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000538 // Get the ID and start/end of the main file.
539 MainFileID = SM->getMainFileID();
540 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
541 MainFileStart = MainBuf->getBufferStart();
542 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Chris Lattner2c78b872009-04-14 23:22:57 +0000544 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000546 // declaring objc_selector outside the parameter list removes a silly
547 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000548 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000549 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000550 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000551 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000552 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000553 if (LangOpts.Microsoft) {
554 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000555 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
556 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000557 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000558 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000560 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
561 Preamble += "typedef struct objc_object Protocol;\n";
562 Preamble += "#define _REWRITER_typedef_Protocol\n";
563 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000564 if (LangOpts.Microsoft) {
565 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
566 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
567 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000568 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000569 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000570 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000571 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000572 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000573 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000574 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000575 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000576 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000577 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000578 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000579 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000580 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000581 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
582 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000583 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000584 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000585 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
586 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
587 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
588 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
589 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000590 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000591 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000592 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
593 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
594 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000595 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
596 Preamble += "struct __objcFastEnumerationState {\n\t";
597 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000598 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000599 Preamble += "unsigned long *mutationsPtr;\n\t";
600 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000601 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000602 Preamble += "#define __FASTENUMERATIONSTATE\n";
603 Preamble += "#endif\n";
604 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
605 Preamble += "struct __NSConstantStringImpl {\n";
606 Preamble += " int *isa;\n";
607 Preamble += " int flags;\n";
608 Preamble += " char *str;\n";
609 Preamble += " long length;\n";
610 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000611 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
612 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
613 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000614 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000615 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000616 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
617 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000618 // Blocks preamble.
619 Preamble += "#ifndef BLOCK_IMPL\n";
620 Preamble += "#define BLOCK_IMPL\n";
621 Preamble += "struct __block_impl {\n";
622 Preamble += " void *isa;\n";
623 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000624 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000625 Preamble += " void *FuncPtr;\n";
626 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000627 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000628 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000629 Preamble += "extern \"C\" __declspec(dllexport) "
630 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000631 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
632 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
633 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
634 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000635 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
636 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000637 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
638 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
639 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000640 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000641 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000642 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
643 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000644 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000645 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000646 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000647 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000648 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000649 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000650 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000651 Preamble += "#define __weak\n";
652 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000653 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
654 // as this avoids warning in any 64bit/32bit compilation model.
655 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000656}
657
658
Chris Lattnerf04da132007-10-24 17:06:59 +0000659//===----------------------------------------------------------------------===//
660// Top Level Driver Code
661//===----------------------------------------------------------------------===//
662
Chris Lattner682bf922009-03-29 16:50:03 +0000663void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000664 if (Diags.hasErrorOccurred())
665 return;
666
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000667 // Two cases: either the decl could be in the main file, or it could be in a
668 // #included file. If the former, rewrite it now. If the later, check to see
669 // if we rewrote the #include/#import.
670 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000671 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000673 // If this is for a builtin, ignore it.
674 if (Loc.isInvalid()) return;
675
Steve Naroffebf2b562007-10-23 23:50:29 +0000676 // Look for built-in declarations that we need to refer during the rewrite.
677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000678 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000679 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000680 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000681 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000682 ConstantStringClassReference = FVD;
683 return;
684 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000685 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000686 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000687 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000688 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000689 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000690 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000691 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000692 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000693 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000694 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
695 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000696 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
697 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000698 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000699 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000700 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000701 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000702 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000703 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000704}
705
Chris Lattnerf04da132007-10-24 17:06:59 +0000706//===----------------------------------------------------------------------===//
707// Syntactic (non-AST) Rewriting Code
708//===----------------------------------------------------------------------===//
709
Steve Naroffb29b4272008-04-14 22:03:09 +0000710void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000711 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000712 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
713 const char *MainBufStart = MainBuf.begin();
714 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000715 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000717 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000718 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
719 if (*BufPtr == '#') {
720 if (++BufPtr == MainBufEnd)
721 return;
722 while (*BufPtr == ' ' || *BufPtr == '\t')
723 if (++BufPtr == MainBufEnd)
724 return;
725 if (!strncmp(BufPtr, "import", ImportLen)) {
726 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000727 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000728 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000729 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000730 BufPtr += ImportLen;
731 }
732 }
733 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000734}
735
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000736static std::string getIvarAccessString(ObjCIvarDecl *OID) {
737 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000738 std::string S;
739 S = "((struct ";
740 S += ClassDecl->getIdentifier()->getName();
741 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000742 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000743 return S;
744}
745
Steve Naroffa0876e82008-12-02 17:36:43 +0000746void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
747 ObjCImplementationDecl *IMD,
748 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000749 static bool objcGetPropertyDefined = false;
750 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000751 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000752 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000753 const char *startBuf = SM->getCharacterData(startLoc);
754 assert((*startBuf == '@') && "bogus @synthesize location");
755 const char *semiBuf = strchr(startBuf, ';');
756 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000757 SourceLocation onePastSemiLoc =
758 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000759
760 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
761 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Steve Naroffeb0646c2008-12-02 15:48:25 +0000763 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000764 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000767 if (!OID)
768 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000769 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000770 if (!PD->getGetterMethodDecl()->isDefined()) {
771 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
772 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
773 ObjCPropertyDecl::OBJC_PR_copy));
774 std::string Getr;
775 if (GenGetProperty && !objcGetPropertyDefined) {
776 objcGetPropertyDefined = true;
777 // FIXME. Is this attribute correct in all cases?
778 Getr = "\nextern \"C\" __declspec(dllimport) "
779 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000780 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000781 RewriteObjCMethodDecl(OID->getContainingInterface(),
782 PD->getGetterMethodDecl(), Getr);
783 Getr += "{ ";
784 // Synthesize an explicit cast to gain access to the ivar.
785 // See objc-act.c:objc_synthesize_new_getter() for details.
786 if (GenGetProperty) {
787 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
788 Getr += "typedef ";
789 const FunctionType *FPRetType = 0;
790 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
791 FPRetType);
792 Getr += " _TYPE";
793 if (FPRetType) {
794 Getr += ")"; // close the precedence "scope" for "*".
795
796 // Now, emit the argument types (if any).
797 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
798 Getr += "(";
799 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
800 if (i) Getr += ", ";
801 std::string ParamStr = FT->getArgType(i).getAsString(
802 Context->PrintingPolicy);
803 Getr += ParamStr;
804 }
805 if (FT->isVariadic()) {
806 if (FT->getNumArgs()) Getr += ", ";
807 Getr += "...";
808 }
809 Getr += ")";
810 } else
811 Getr += "()";
812 }
813 Getr += ";\n";
814 Getr += "return (_TYPE)";
815 Getr += "objc_getProperty(self, _cmd, ";
816 SynthesizeIvarOffsetComputation(OID, Getr);
817 Getr += ", 1)";
818 }
819 else
820 Getr += "return " + getIvarAccessString(OID);
821 Getr += "; }";
822 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000823 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000824
825 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000826 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Steve Naroffeb0646c2008-12-02 15:48:25 +0000828 // Generate the 'setter' function.
829 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000830 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
831 ObjCPropertyDecl::OBJC_PR_copy);
832 if (GenSetProperty && !objcSetPropertyDefined) {
833 objcSetPropertyDefined = true;
834 // FIXME. Is this attribute correct in all cases?
835 Setr = "\nextern \"C\" __declspec(dllimport) "
836 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
837 }
838
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000839 RewriteObjCMethodDecl(OID->getContainingInterface(),
840 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000841 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000842 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000843 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000844 if (GenSetProperty) {
845 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000846 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000847 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000848 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000849 Setr += ", ";
850 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
851 Setr += "0, ";
852 else
853 Setr += "1, ";
854 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
855 Setr += "1)";
856 else
857 Setr += "0)";
858 }
859 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000860 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000861 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000862 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000863 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000864 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000865}
Chris Lattner8a12c272007-10-11 18:38:32 +0000866
Steve Naroffb29b4272008-04-14 22:03:09 +0000867void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000868 // Get the start location and compute the semi location.
869 SourceLocation startLoc = ClassDecl->getLocation();
870 const char *startBuf = SM->getCharacterData(startLoc);
871 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Chris Lattnerf04da132007-10-24 17:06:59 +0000873 // Translate to typedef's that forward reference structs with the same name
874 // as the class. As a convenience, we include the original declaration
875 // as a comment.
876 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000877 typedefString += "// @class ";
878 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
879 I != E; ++I) {
880 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
881 typedefString += ForwardDecl->getNameAsString();
882 if (I+1 != E)
883 typedefString += ", ";
884 else
885 typedefString += ";\n";
886 }
887
Chris Lattner67956052009-02-20 18:04:31 +0000888 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
889 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000890 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000891 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000892 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000893 typedefString += "\n";
894 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000895 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000896 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000897 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000898 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000899 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000900 }
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Steve Naroff934f2762007-10-24 22:48:43 +0000902 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000903 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000904}
905
Steve Naroffb29b4272008-04-14 22:03:09 +0000906void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000907 // When method is a synthesized one, such as a getter/setter there is
908 // nothing to rewrite.
909 if (Method->isSynthesized())
910 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000911 SourceLocation LocStart = Method->getLocStart();
912 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Chris Lattner30fc9332009-02-04 01:06:56 +0000914 if (SM->getInstantiationLineNumber(LocEnd) >
915 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000916 InsertText(LocStart, "#if 0\n");
917 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000918 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000919 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000920 }
921}
922
Mike Stump1eb44332009-09-09 15:08:12 +0000923void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000924 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Benjamin Kramerd999b372010-02-14 14:14:16 +0000926 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000927 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000928}
929
Steve Naroffb29b4272008-04-14 22:03:09 +0000930void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000931 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Steve Naroff423cb562007-10-30 13:30:57 +0000933 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000934 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000936 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
937 E = CatDecl->prop_end(); I != E; ++I)
938 RewriteProperty(*I);
939
Mike Stump1eb44332009-09-09 15:08:12 +0000940 for (ObjCCategoryDecl::instmeth_iterator
941 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000942 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000943 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000944 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000945 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000946 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000947 RewriteMethodDeclaration(*I);
948
Steve Naroff423cb562007-10-30 13:30:57 +0000949 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000950 ReplaceText(CatDecl->getAtEndRange().getBegin(),
951 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000952}
953
Steve Naroffb29b4272008-04-14 22:03:09 +0000954void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000955 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Steve Naroff752d6ef2007-10-30 16:42:30 +0000957 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000958 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000959
960 for (ObjCProtocolDecl::instmeth_iterator
961 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000962 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000963 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000964 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000965 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000966 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000967 RewriteMethodDeclaration(*I);
968
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000969 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
970 E = PDecl->prop_end(); I != E; ++I)
971 RewriteProperty(*I);
972
Steve Naroff752d6ef2007-10-30 16:42:30 +0000973 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000974 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000975 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000976
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000977 // Must comment out @optional/@required
978 const char *startBuf = SM->getCharacterData(LocStart);
979 const char *endBuf = SM->getCharacterData(LocEnd);
980 for (const char *p = startBuf; p < endBuf; p++) {
981 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000982 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000983 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000985 }
986 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000987 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000988 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000990 }
991 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000992}
993
Steve Naroffb29b4272008-04-14 22:03:09 +0000994void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000995 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000996 if (LocStart.isInvalid())
997 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000998 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000999 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001000}
1001
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001002void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1003 const FunctionType *&FPRetType) {
1004 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001005 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001006 else if (T->isFunctionPointerType() ||
1007 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001008 // needs special handling, since pointer-to-functions have special
1009 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001010 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001011 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001012 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001013 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001014 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001015 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001016 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001017 ResultStr += FPRetType->getResultType().getAsString(
1018 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001019 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001020 }
1021 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001022 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001023}
1024
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001025void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1026 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001027 std::string &ResultStr) {
1028 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1029 const FunctionType *FPRetType = 0;
1030 ResultStr += "\nstatic ";
1031 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001032 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001034 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001035 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001037 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001038 NameStr += "_I_";
1039 else
1040 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001042 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001043 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001044
1045 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001046 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001047 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001048 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001049 }
Mike Stump1eb44332009-09-09 15:08:12 +00001050 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001051 {
1052 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001053 int len = selString.size();
1054 for (int i = 0; i < len; i++)
1055 if (selString[i] == ':')
1056 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001057 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001058 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001059 // Remember this name for metadata emission
1060 MethodInternalNames[OMD] = NameStr;
1061 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001063 // Rewrite arguments
1064 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001066 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001067 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001068 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001069 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001070 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001071 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001072 ResultStr += "struct ";
1073 }
1074 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001075 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001076 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001077 }
1078 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001079 ResultStr += Context->getObjCClassType().getAsString(
1080 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001082 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001083 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001084 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001086 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001087 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1088 E = OMD->param_end(); PI != E; ++PI) {
1089 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001090 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001091 if (PDecl->getType()->isObjCQualifiedIdType()) {
1092 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001093 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001094 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001095 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001096 QualType QT = PDecl->getType();
1097 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1098 if (convertBlockPointerToFunctionPointer(QT))
1099 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1100 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001101 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001102 ResultStr += Name;
1103 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001104 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001105 if (OMD->isVariadic())
1106 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001107 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Steve Naroff76e429d2008-07-16 14:40:40 +00001109 if (FPRetType) {
1110 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Steve Naroff76e429d2008-07-16 14:40:40 +00001112 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001113 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001114 ResultStr += "(";
1115 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1116 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001117 std::string ParamStr = FT->getArgType(i).getAsString(
1118 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001119 ResultStr += ParamStr;
1120 }
1121 if (FT->isVariadic()) {
1122 if (FT->getNumArgs()) ResultStr += ", ";
1123 ResultStr += "...";
1124 }
1125 ResultStr += ")";
1126 } else {
1127 ResultStr += "()";
1128 }
1129 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001130}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001131void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001132 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1133 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001134
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001135 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001137 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001138 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1139 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001140 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001141 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001142 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001143 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001144 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001145 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001146
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001147 const char *startBuf = SM->getCharacterData(LocStart);
1148 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001149 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150 }
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001152 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001153 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1154 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001155 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001156 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001157 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001158 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001159 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001160 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001162 const char *startBuf = SM->getCharacterData(LocStart);
1163 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001164 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001165 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001166 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001167 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001168 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001169 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001170 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001171 }
1172
Benjamin Kramerd999b372010-02-14 14:14:16 +00001173 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001174}
1175
Steve Naroffb29b4272008-04-14 22:03:09 +00001176void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001177 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001178 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001179 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001180 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001181 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001182 ResultStr += "\n";
1183 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001184 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001185 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001186 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001187 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001188 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001189 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001190 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001191 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001192 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001193
1194 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001195 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001196 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001197 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001198 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001199 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001200 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001201 for (ObjCInterfaceDecl::classmeth_iterator
1202 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001203 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001204 RewriteMethodDeclaration(*I);
1205
Steve Naroff2feac5e2007-10-30 03:43:13 +00001206 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001207 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1208 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001209}
1210
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001211Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001212 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001213 ObjCMethodDecl *OMD = 0;
1214 QualType Ty;
1215 Selector Sel;
1216 Stmt *Receiver;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001217 bool Super = false;
1218 QualType SuperTy;
1219 SourceLocation SuperLocation;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001220 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001221 // This allows us to reuse all the fun and games in SynthMessageExpr().
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001222 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
1223 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1224 OMD = PDecl->getSetterMethodDecl();
1225 Ty = PDecl->getType();
1226 Sel = PDecl->getSetterName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001227 Super = PropRefExpr->isSuperReceiver();
1228 if (!Super)
1229 Receiver = PropRefExpr->getBase();
1230 else {
1231 SuperTy = PropRefExpr->getSuperType();
1232 SuperLocation = PropRefExpr->getSuperLocation();
1233 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001234 }
1235 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1236 dyn_cast<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS())) {
1237 OMD = ImplicitRefExpr->getSetterMethod();
1238 Sel = OMD->getSelector();
1239 Ty = ImplicitRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001240 Super = ImplicitRefExpr->isSuperReceiver();
1241 if (!Super)
1242 Receiver = ImplicitRefExpr->getBase();
1243 else {
1244 SuperTy = ImplicitRefExpr->getSuperType();
1245 SuperLocation = ImplicitRefExpr->getSuperLocation();
1246 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001247 }
1248
1249 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroffc77a6362008-12-04 16:24:46 +00001250 llvm::SmallVector<Expr *, 1> ExprVec;
1251 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001253 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1254 if (PropGetters[Exp])
1255 // This allows us to handle chain/nested property/implicit getters.
1256 Receiver = PropGetters[Exp];
1257
1258 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001259 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001260 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001261 Ty.getNonReferenceType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001262 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001263 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001264 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001265 SuperTy,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001266 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001267 &ExprVec[0], 1,
1268 /*FIXME:*/SourceLocation());
1269 else
1270 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001271 Ty.getNonReferenceType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001272 /*FIXME: */SourceLocation(),
1273 cast<Expr>(Receiver),
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001274 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001275 &ExprVec[0], 1,
1276 /*FIXME:*/SourceLocation());
Steve Naroffc77a6362008-12-04 16:24:46 +00001277 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Steve Naroffc77a6362008-12-04 16:24:46 +00001279 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001280 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001281 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001282 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1283 // to things that stay around.
1284 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001285 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001286}
1287
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001288Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1289 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001290 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001291 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001292 ObjCMethodDecl *OMD = 0;
1293 QualType Ty;
1294 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001295 bool Super = false;
1296 QualType SuperTy;
1297 SourceLocation SuperLocation;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001298 if (ObjCPropertyRefExpr *PropRefExpr =
1299 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
1300 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1301 OMD = PDecl->getGetterMethodDecl();
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001302 Ty = PDecl->getType();
1303 Sel = PDecl->getGetterName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001304 Super = PropRefExpr->isSuperReceiver();
1305 if (!Super)
1306 Receiver = PropRefExpr->getBase();
1307 else {
1308 SuperTy = PropRefExpr->getSuperType();
1309 SuperLocation = PropRefExpr->getSuperLocation();
1310 }
Steve Naroff8599e7a2008-12-08 16:43:47 +00001311 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001312 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1313 dyn_cast<ObjCImplicitSetterGetterRefExpr>(PropOrGetterRefExpr)) {
1314 OMD = ImplicitRefExpr->getGetterMethod();
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001315 Sel = OMD->getSelector();
1316 Ty = ImplicitRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001317 Super = ImplicitRefExpr->isSuperReceiver();
1318 if (!Super)
1319 Receiver = ImplicitRefExpr->getBase();
1320 else {
1321 SuperTy = ImplicitRefExpr->getSuperType();
1322 SuperLocation = ImplicitRefExpr->getSuperLocation();
1323 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001324 }
1325
1326 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1327
1328 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1329 if (PropGetters[Exp])
1330 // This allows us to handle chain/nested property/implicit getters.
1331 Receiver = PropGetters[Exp];
1332
1333 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001334 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001335 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001336 Ty.getNonReferenceType(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001337 /*FIXME?*/SourceLocation(),
1338 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001339 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001340 SuperTy,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001341 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001342 0, 0,
1343 /*FIXME:*/SourceLocation());
1344 else
1345 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001346 Ty.getNonReferenceType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001347 /*FIXME:*/SourceLocation(),
1348 cast<Expr>(Receiver),
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001349 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001350 0, 0,
1351 /*FIXME:*/SourceLocation());
Steve Naroff15f081d2008-12-03 00:56:33 +00001352
Steve Naroff4c3580e2008-12-04 23:50:32 +00001353 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001354
1355 if (!PropParentMap)
1356 PropParentMap = new ParentMap(CurrentBody);
1357
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001358 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
1359 if (Parent && (isa<ObjCPropertyRefExpr>(Parent) ||
1360 isa<ObjCImplicitSetterGetterRefExpr>(Parent))) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001361 // We stash away the ReplacingStmt since actually doing the
1362 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001363 PropGetters[PropOrGetterRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001364 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1365 // to things that stay around.
1366 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001367 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001368 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001369 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001370 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001371 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1372 // to things that stay around.
1373 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001374 return ReplacingStmt;
1375 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001376}
1377
Mike Stump1eb44332009-09-09 15:08:12 +00001378Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001379 SourceLocation OrigStart,
1380 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001381 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001382 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001383 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001384 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001385 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001386 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001387 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001388 // lookup which class implements the instance variable.
1389 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001390 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001391 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001392 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Steve Narofff0757612008-05-08 17:52:16 +00001394 // Synthesize an explicit cast to gain access to the ivar.
1395 std::string RecName = clsDeclared->getIdentifier()->getName();
1396 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001397 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001398 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001399 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001400 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1401 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001402 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCall2de56d12010-08-25 11:45:40 +00001403 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00001404 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001405 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001406 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1407 IV->getBase()->getLocEnd(),
1408 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001409 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001410 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001411 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001412 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1413 IV->getLocation(),
1414 D->getType());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001415 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001416 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001417 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001418 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001419 // Cannot delete IV->getBase(), since PE points to it.
1420 // Replace the old base with the cast. This is important when doing
1421 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001422 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001423 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001424 }
Steve Naroff84472a82008-04-18 21:55:08 +00001425 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001426 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Steve Naroff9f525972008-05-06 23:20:07 +00001428 // Explicit ivar refs need to have a cast inserted.
1429 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001430 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001431 ObjCInterfaceType *iFaceDecl =
1432 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001433 // lookup which class implements the instance variable.
1434 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001435 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001436 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001437 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Steve Naroff9f525972008-05-06 23:20:07 +00001439 // Synthesize an explicit cast to gain access to the ivar.
1440 std::string RecName = clsDeclared->getIdentifier()->getName();
1441 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001442 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001443 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001444 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001445 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1446 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001447 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCall2de56d12010-08-25 11:45:40 +00001448 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00001449 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001450 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001451 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001452 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001453 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001454 // Cannot delete IV->getBase(), since PE points to it.
1455 // Replace the old base with the cast. This is important when doing
1456 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001457 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001458 return IV;
1459 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001460 }
Steve Naroff84472a82008-04-18 21:55:08 +00001461 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001462}
1463
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001464Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1465 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1466 CI != E; ++CI) {
1467 if (*CI) {
1468 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1469 if (newStmt)
1470 *CI = newStmt;
1471 }
1472 }
1473 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1474 SourceRange OrigStmtRange = S->getSourceRange();
1475 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1476 replaced);
1477 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001478 }
1479 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1480 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1481 return newStmt;
1482 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001483 return S;
1484}
1485
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001486/// SynthCountByEnumWithState - To print:
1487/// ((unsigned int (*)
1488/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001489/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001490/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001491/// "countByEnumeratingWithState:objects:count:"),
1492/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001493/// (id *)items, (unsigned int)16)
1494///
Steve Naroffb29b4272008-04-14 22:03:09 +00001495void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001496 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1497 "id *, unsigned int))(void *)objc_msgSend)";
1498 buf += "\n\t\t";
1499 buf += "((id)l_collection,\n\t\t";
1500 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1501 buf += "\n\t\t";
1502 buf += "&enumState, "
1503 "(id *)items, (unsigned int)16)";
1504}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001505
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001506/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1507/// statement to exit to its outer synthesized loop.
1508///
Steve Naroffb29b4272008-04-14 22:03:09 +00001509Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001510 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1511 return S;
1512 // replace break with goto __break_label
1513 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001515 SourceLocation startLoc = S->getLocStart();
1516 buf = "goto __break_label_";
1517 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001518 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001519
1520 return 0;
1521}
1522
1523/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1524/// statement to continue with its inner synthesized loop.
1525///
Steve Naroffb29b4272008-04-14 22:03:09 +00001526Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001527 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1528 return S;
1529 // replace continue with goto __continue_label
1530 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001532 SourceLocation startLoc = S->getLocStart();
1533 buf = "goto __continue_label_";
1534 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001535 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001537 return 0;
1538}
1539
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001540/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001541/// It rewrites:
1542/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001544/// Into:
1545/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001546/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001547/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001548/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001549/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001550/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001551/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001552/// if (limit) {
1553/// unsigned long startMutations = *enumState.mutationsPtr;
1554/// do {
1555/// unsigned long counter = 0;
1556/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001557/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001558/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001559/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001560/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001561/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001562/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001563/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001564/// objects:items count:16]);
1565/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001566/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001567/// }
1568/// else
1569/// elem = nil;
1570/// }
1571///
Steve Naroffb29b4272008-04-14 22:03:09 +00001572Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001573 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001574 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001575 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001576 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001577 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001578 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001580 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001581 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar4087f272010-08-17 22:39:59 +00001582 llvm::StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001583 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001584 std::string buf;
1585 buf = "\n{\n\t";
1586 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1587 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001588 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001589 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001590 if (ElementType->isObjCQualifiedIdType() ||
1591 ElementType->isObjCQualifiedInterfaceType())
1592 // Simply use 'id' for all qualified types.
1593 elementTypeAsString = "id";
1594 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001595 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001596 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001597 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001598 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001599 buf += elementName;
1600 buf += ";\n\t";
1601 }
Chris Lattner06767512008-04-08 05:52:18 +00001602 else {
1603 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001604 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001605 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1606 if (VD->getType()->isObjCQualifiedIdType() ||
1607 VD->getType()->isObjCQualifiedInterfaceType())
1608 // Simply use 'id' for all qualified types.
1609 elementTypeAsString = "id";
1610 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001611 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001612 }
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001614 // struct __objcFastEnumerationState enumState = { 0 };
1615 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1616 // id items[16];
1617 buf += "id items[16];\n\t";
1618 // id l_collection = (id)
1619 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001620 // Find start location of 'collection' the hard way!
1621 const char *startCollectionBuf = startBuf;
1622 startCollectionBuf += 3; // skip 'for'
1623 startCollectionBuf = strchr(startCollectionBuf, '(');
1624 startCollectionBuf++; // skip '('
1625 // find 'in' and skip it.
1626 while (*startCollectionBuf != ' ' ||
1627 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1628 (*(startCollectionBuf+3) != ' ' &&
1629 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1630 startCollectionBuf++;
1631 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001632
1633 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001634 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001635 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001636 SourceLocation rightParenLoc = S->getRParenLoc();
1637 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1638 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001639 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001641 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1642 // objects:items count:16];
1643 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001644 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001645 // ((unsigned int (*)
1646 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001647 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001648 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001649 // "countByEnumeratingWithState:objects:count:"),
1650 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001651 // (id *)items, (unsigned int)16);
1652 buf += "unsigned long limit =\n\t\t";
1653 SynthCountByEnumWithState(buf);
1654 buf += ";\n\t";
1655 /// if (limit) {
1656 /// unsigned long startMutations = *enumState.mutationsPtr;
1657 /// do {
1658 /// unsigned long counter = 0;
1659 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001660 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001661 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001662 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001663 buf += "if (limit) {\n\t";
1664 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1665 buf += "do {\n\t\t";
1666 buf += "unsigned long counter = 0;\n\t\t";
1667 buf += "do {\n\t\t\t";
1668 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1669 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1670 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001671 buf += " = (";
1672 buf += elementTypeAsString;
1673 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001674 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001675 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001677 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001678 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001679 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001680 /// objects:items count:16]);
1681 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001682 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001683 /// }
1684 /// else
1685 /// elem = nil;
1686 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001687 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001688 buf = ";\n\t";
1689 buf += "__continue_label_";
1690 buf += utostr(ObjCBcLabelNo.back());
1691 buf += ": ;";
1692 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001693 buf += "} while (counter < limit);\n\t";
1694 buf += "} while (limit = ";
1695 SynthCountByEnumWithState(buf);
1696 buf += ");\n\t";
1697 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001698 buf += " = ((";
1699 buf += elementTypeAsString;
1700 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001701 buf += "__break_label_";
1702 buf += utostr(ObjCBcLabelNo.back());
1703 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001704 buf += "}\n\t";
1705 buf += "else\n\t\t";
1706 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001707 buf += " = ((";
1708 buf += elementTypeAsString;
1709 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001710 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001712 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001713 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001714 if (isa<CompoundStmt>(S->getBody())) {
1715 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001716 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001717 } else {
1718 /* Need to treat single statements specially. For example:
1719 *
1720 * for (A *a in b) if (stuff()) break;
1721 * for (A *a in b) xxxyy;
1722 *
1723 * The following code simply scans ahead to the semi to find the actual end.
1724 */
1725 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1726 const char *semiBuf = strchr(stmtBuf, ';');
1727 assert(semiBuf && "Can't find ';'");
1728 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001729 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001730 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001731 Stmts.pop_back();
1732 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001733 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001734}
1735
Mike Stump1eb44332009-09-09 15:08:12 +00001736/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001737/// This routine rewrites @synchronized(expr) stmt;
1738/// into:
1739/// objc_sync_enter(expr);
1740/// @try stmt @finally { objc_sync_exit(expr); }
1741///
Steve Naroffb29b4272008-04-14 22:03:09 +00001742Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001743 // Get the start location and compute the semi location.
1744 SourceLocation startLoc = S->getLocStart();
1745 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001747 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001748
1749 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001750 buf = "objc_sync_enter((id)";
1751 const char *lparenBuf = startBuf;
1752 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001753 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001754 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1755 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001756 // been rewritten! (which implies the SourceLocation's are invalid).
1757 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001758 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001759 while (*endBuf != ')') endBuf--;
1760 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001761 buf = ");\n";
1762 // declare a new scope with two variables, _stack and _rethrow.
1763 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1764 buf += "int buf[18/*32-bit i386*/];\n";
1765 buf += "char *pointers[4];} _stack;\n";
1766 buf += "id volatile _rethrow = 0;\n";
1767 buf += "objc_exception_try_enter(&_stack);\n";
1768 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001769 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001770 startLoc = S->getSynchBody()->getLocEnd();
1771 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Steve Naroffc7089f12008-08-19 13:04:19 +00001773 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001774 SourceLocation lastCurlyLoc = startLoc;
1775 buf = "}\nelse {\n";
1776 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001777 buf += "}\n";
1778 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001779 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001780
1781 std::string syncBuf;
1782 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001783 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00001784 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00001785 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001786 std::string syncExprBufS;
1787 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001788 syncExpr->printPretty(syncExprBuf, *Context, 0,
1789 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001790 syncBuf += syncExprBuf.str();
1791 syncBuf += ");";
1792
1793 buf += syncBuf;
1794 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001795 buf += "}\n";
1796 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Benjamin Kramerd999b372010-02-14 14:14:16 +00001798 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001799
1800 bool hasReturns = false;
1801 HasReturnStmts(S->getSynchBody(), hasReturns);
1802 if (hasReturns)
1803 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1804
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001805 return 0;
1806}
1807
Steve Naroffb85e77a2009-12-05 21:43:12 +00001808void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1809{
Steve Naroff8c565152008-12-05 17:03:39 +00001810 // Perform a bottom up traversal of all children.
1811 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1812 CI != E; ++CI)
1813 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001814 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001815
Steve Naroffb85e77a2009-12-05 21:43:12 +00001816 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001817 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001818 TryFinallyContainsReturnDiag);
1819 }
1820 return;
1821}
1822
Steve Naroffb85e77a2009-12-05 21:43:12 +00001823void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1824{
1825 // Perform a bottom up traversal of all children.
1826 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1827 CI != E; ++CI)
1828 if (*CI)
1829 HasReturnStmts(*CI, hasReturns);
1830
1831 if (isa<ReturnStmt>(S))
1832 hasReturns = true;
1833 return;
1834}
1835
1836void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1837 // Perform a bottom up traversal of all children.
1838 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1839 CI != E; ++CI)
1840 if (*CI) {
1841 RewriteTryReturnStmts(*CI);
1842 }
1843 if (isa<ReturnStmt>(S)) {
1844 SourceLocation startLoc = S->getLocStart();
1845 const char *startBuf = SM->getCharacterData(startLoc);
1846
1847 const char *semiBuf = strchr(startBuf, ';');
1848 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1849 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1850
1851 std::string buf;
1852 buf = "{ objc_exception_try_exit(&_stack); return";
1853
Benjamin Kramerd999b372010-02-14 14:14:16 +00001854 ReplaceText(startLoc, 6, buf);
1855 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001856 }
1857 return;
1858}
1859
1860void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1861 // Perform a bottom up traversal of all children.
1862 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1863 CI != E; ++CI)
1864 if (*CI) {
1865 RewriteSyncReturnStmts(*CI, syncExitBuf);
1866 }
1867 if (isa<ReturnStmt>(S)) {
1868 SourceLocation startLoc = S->getLocStart();
1869 const char *startBuf = SM->getCharacterData(startLoc);
1870
1871 const char *semiBuf = strchr(startBuf, ';');
1872 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1873 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1874
1875 std::string buf;
1876 buf = "{ objc_exception_try_exit(&_stack);";
1877 buf += syncExitBuf;
1878 buf += " return";
1879
Benjamin Kramerd999b372010-02-14 14:14:16 +00001880 ReplaceText(startLoc, 6, buf);
1881 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001882 }
1883 return;
1884}
1885
Steve Naroffb29b4272008-04-14 22:03:09 +00001886Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001887 // Get the start location and compute the semi location.
1888 SourceLocation startLoc = S->getLocStart();
1889 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Steve Naroff75730982007-11-07 04:08:17 +00001891 assert((*startBuf == '@') && "bogus @try location");
1892
1893 std::string buf;
1894 // declare a new scope with two variables, _stack and _rethrow.
1895 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1896 buf += "int buf[18/*32-bit i386*/];\n";
1897 buf += "char *pointers[4];} _stack;\n";
1898 buf += "id volatile _rethrow = 0;\n";
1899 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001900 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001901
Benjamin Kramerd999b372010-02-14 14:14:16 +00001902 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Steve Naroff75730982007-11-07 04:08:17 +00001904 startLoc = S->getTryBody()->getLocEnd();
1905 startBuf = SM->getCharacterData(startLoc);
1906
1907 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Steve Naroff75730982007-11-07 04:08:17 +00001909 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001910 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001911 startLoc = startLoc.getFileLocWithOffset(1);
1912 buf = " /* @catch begin */ else {\n";
1913 buf += " id _caught = objc_exception_extract(&_stack);\n";
1914 buf += " objc_exception_try_enter (&_stack);\n";
1915 buf += " if (_setjmp(_stack.buf))\n";
1916 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1917 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Benjamin Kramerd999b372010-02-14 14:14:16 +00001919 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001920 } else { /* no catch list */
1921 buf = "}\nelse {\n";
1922 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1923 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001924 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001925 }
Steve Naroff75730982007-11-07 04:08:17 +00001926 bool sawIdTypedCatch = false;
1927 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001928 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1929 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001930 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001931
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001932 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001933 buf = "if ("; // we are generating code for the first catch clause
1934 else
1935 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001936 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001937 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Steve Naroff75730982007-11-07 04:08:17 +00001939 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Steve Naroff75730982007-11-07 04:08:17 +00001941 const char *lParenLoc = strchr(startBuf, '(');
1942
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001943 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001944 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001945 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001946 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1947 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001948 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001949 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001950 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Steve Naroffe12e6922008-02-01 20:02:07 +00001952 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001953 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001954 } else if (catchDecl) {
1955 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001956 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001957 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001958 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001959 sawIdTypedCatch = true;
John McCall506b57e2010-05-17 21:00:27 +00001960 } else if (const ObjCObjectPointerType *Ptr =
1961 t->getAs<ObjCObjectPointerType>()) {
1962 // Should be a pointer to a class.
1963 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1964 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001965 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001966 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001967 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001968 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001969 }
1970 }
1971 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001972 lastCatchBody = Catch->getCatchBody();
1973 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001974 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1975 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1976 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1977 assert((*rParenBuf == ')') && "bogus @catch paren location");
1978 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Mike Stump1eb44332009-09-09 15:08:12 +00001980 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001981 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001982 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001983 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001984 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001985 }
Steve Naroff75730982007-11-07 04:08:17 +00001986 }
1987 // Complete the catch list...
1988 if (lastCatchBody) {
1989 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001990 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1991 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Steve Naroff378f47a2008-09-11 15:29:03 +00001993 // Insert the last (implicit) else clause *before* the right curly brace.
1994 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1995 buf = "} /* last catch end */\n";
1996 buf += "else {\n";
1997 buf += " _rethrow = _caught;\n";
1998 buf += " objc_exception_try_exit(&_stack);\n";
1999 buf += "} } /* @catch end */\n";
2000 if (!S->getFinallyStmt())
2001 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002002 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Steve Naroff75730982007-11-07 04:08:17 +00002004 // Set lastCurlyLoc
2005 lastCurlyLoc = lastCatchBody->getLocEnd();
2006 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002007 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002008 startLoc = finalStmt->getLocStart();
2009 startBuf = SM->getCharacterData(startLoc);
2010 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Benjamin Kramerd999b372010-02-14 14:14:16 +00002012 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Steve Naroff75730982007-11-07 04:08:17 +00002014 Stmt *body = finalStmt->getFinallyBody();
2015 SourceLocation startLoc = body->getLocStart();
2016 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002017 assert(*SM->getCharacterData(startLoc) == '{' &&
2018 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002019 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002020 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Steve Naroff75730982007-11-07 04:08:17 +00002022 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002023 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002024 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002025 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Steve Naroff75730982007-11-07 04:08:17 +00002027 // Set lastCurlyLoc
2028 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Steve Naroff8c565152008-12-05 17:03:39 +00002030 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002031 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002032 } else { /* no finally clause - make sure we synthesize an implicit one */
2033 buf = "{ /* implicit finally clause */\n";
2034 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2035 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2036 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002037 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002038
2039 // Now check for any return/continue/go statements within the @try.
2040 // The implicit finally clause won't called if the @try contains any
2041 // jump statements.
2042 bool hasReturns = false;
2043 HasReturnStmts(S->getTryBody(), hasReturns);
2044 if (hasReturns)
2045 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002046 }
2047 // Now emit the final closing curly brace...
2048 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002049 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002050 return 0;
2051}
2052
Mike Stump1eb44332009-09-09 15:08:12 +00002053// This can't be done with ReplaceStmt(S, ThrowExpr), since
2054// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002055// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002056Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002057 // Get the start location and compute the semi location.
2058 SourceLocation startLoc = S->getLocStart();
2059 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Steve Naroff2bd03922007-11-07 15:32:26 +00002061 assert((*startBuf == '@') && "bogus @throw location");
2062
2063 std::string buf;
2064 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002065 if (S->getThrowExpr())
2066 buf = "objc_exception_throw(";
2067 else // add an implicit argument
2068 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002070 // handle "@ throw" correctly.
2071 const char *wBuf = strchr(startBuf, 'w');
2072 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002073 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Steve Naroff2bd03922007-11-07 15:32:26 +00002075 const char *semiBuf = strchr(startBuf, ';');
2076 assert((*semiBuf == ';') && "@throw: can't find ';'");
2077 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002078 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002079 return 0;
2080}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002081
Steve Naroffb29b4272008-04-14 22:03:09 +00002082Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002083 // Create a new string expression.
2084 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002085 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002086 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002087 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2088 StrEncoding.length(), false,StrType,
2089 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002090 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Chris Lattner07506182007-11-30 22:53:43 +00002092 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002093 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002094 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002095}
2096
Steve Naroffb29b4272008-04-14 22:03:09 +00002097Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002098 if (!SelGetUidFunctionDecl)
2099 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002100 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2101 // Create a call to sel_registerName("selName").
2102 llvm::SmallVector<Expr*, 8> SelExprs;
2103 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002104 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002105 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002106 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002107 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002108 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2109 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002110 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002111 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002112 return SelExp;
2113}
2114
Steve Naroffb29b4272008-04-14 22:03:09 +00002115CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002116 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2117 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002118 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002119 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Steve Naroffebf2b562007-10-23 23:50:29 +00002121 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002122 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Steve Naroffebf2b562007-10-23 23:50:29 +00002124 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002125 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002126 ImplicitCastExpr *ICE =
John McCall2de56d12010-08-25 11:45:40 +00002127 ImplicitCastExpr::Create(*Context, pToFunc, CK_Unknown,
John McCall5baba9d2010-08-25 10:28:54 +00002128 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002129
John McCall183700f2009-09-21 23:43:11 +00002130 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002131
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002132 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002133 new (Context) CallExpr(*Context, ICE, args, nargs,
2134 FT->getCallResultType(*Context), EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002135 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002136}
2137
Steve Naroffd5255f52007-11-01 13:24:47 +00002138static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2139 const char *&startRef, const char *&endRef) {
2140 while (startBuf < endBuf) {
2141 if (*startBuf == '<')
2142 startRef = startBuf; // mark the start.
2143 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002144 if (startRef && *startRef == '<') {
2145 endRef = startBuf; // mark the end.
2146 return true;
2147 }
2148 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002149 }
2150 startBuf++;
2151 }
2152 return false;
2153}
2154
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002155static void scanToNextArgument(const char *&argRef) {
2156 int angle = 0;
2157 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2158 if (*argRef == '<')
2159 angle++;
2160 else if (*argRef == '>')
2161 angle--;
2162 argRef++;
2163 }
2164 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2165}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002166
Steve Naroffb29b4272008-04-14 22:03:09 +00002167bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002168 if (T->isObjCQualifiedIdType())
2169 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002170 if (const PointerType *PT = T->getAs<PointerType>()) {
2171 if (PT->getPointeeType()->isObjCQualifiedIdType())
2172 return true;
2173 }
2174 if (T->isObjCObjectPointerType()) {
2175 T = T->getPointeeType();
2176 return T->isObjCQualifiedInterfaceType();
2177 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002178 if (T->isArrayType()) {
2179 QualType ElemTy = Context->getBaseElementType(T);
2180 return needToScanForQualifiers(ElemTy);
2181 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002182 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002183}
2184
Steve Naroff4f95b752008-07-29 18:15:38 +00002185void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2186 QualType Type = E->getType();
2187 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002188 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Steve Naroffcda658e2008-11-19 21:15:47 +00002190 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2191 Loc = ECE->getLParenLoc();
2192 EndLoc = ECE->getRParenLoc();
2193 } else {
2194 Loc = E->getLocStart();
2195 EndLoc = E->getLocEnd();
2196 }
2197 // This will defend against trying to rewrite synthesized expressions.
2198 if (Loc.isInvalid() || EndLoc.isInvalid())
2199 return;
2200
Steve Naroff4f95b752008-07-29 18:15:38 +00002201 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002202 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002203 const char *startRef = 0, *endRef = 0;
2204 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2205 // Get the locations of the startRef, endRef.
2206 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2207 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2208 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002209 InsertText(LessLoc, "/*");
2210 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002211 }
2212 }
2213}
2214
Steve Naroffb29b4272008-04-14 22:03:09 +00002215void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002216 SourceLocation Loc;
2217 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002218 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002219 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2220 Loc = VD->getLocation();
2221 Type = VD->getType();
2222 }
2223 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2224 Loc = FD->getLocation();
2225 // Check for ObjC 'id' and class types that have been adorned with protocol
2226 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002227 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002228 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002229 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002230 if (!proto)
2231 return;
2232 Type = proto->getResultType();
2233 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002234 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2235 Loc = FD->getLocation();
2236 Type = FD->getType();
2237 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002238 else
2239 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002241 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002242 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Steve Naroffd5255f52007-11-01 13:24:47 +00002244 const char *endBuf = SM->getCharacterData(Loc);
2245 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002246 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002247 startBuf--; // scan backward (from the decl location) for return type.
2248 const char *startRef = 0, *endRef = 0;
2249 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2250 // Get the locations of the startRef, endRef.
2251 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2252 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2253 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002254 InsertText(LessLoc, "/*");
2255 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002256 }
2257 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002258 if (!proto)
2259 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002260 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002261 const char *startBuf = SM->getCharacterData(Loc);
2262 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002263 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2264 if (needToScanForQualifiers(proto->getArgType(i))) {
2265 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Steve Naroffd5255f52007-11-01 13:24:47 +00002267 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002268 // scan forward (from the decl location) for argument types.
2269 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002270 const char *startRef = 0, *endRef = 0;
2271 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2272 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002273 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002274 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002275 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002276 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002277 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002278 InsertText(LessLoc, "/*");
2279 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002280 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002281 startBuf = ++endBuf;
2282 }
2283 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002284 // If the function name is derived from a macro expansion, then the
2285 // argument buffer will not follow the name. Need to speak with Chris.
2286 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002287 startBuf++; // scan forward (from the decl location) for argument types.
2288 startBuf++;
2289 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002290 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002291}
2292
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002293void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2294 QualType QT = ND->getType();
2295 const Type* TypePtr = QT->getAs<Type>();
2296 if (!isa<TypeOfExprType>(TypePtr))
2297 return;
2298 while (isa<TypeOfExprType>(TypePtr)) {
2299 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2300 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2301 TypePtr = QT->getAs<Type>();
2302 }
2303 // FIXME. This will not work for multiple declarators; as in:
2304 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002305 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002306 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2307 const char *startBuf = SM->getCharacterData(DeclLoc);
2308 if (ND->getInit()) {
2309 std::string Name(ND->getNameAsString());
2310 TypeAsString += " " + Name + " = ";
2311 Expr *E = ND->getInit();
2312 SourceLocation startLoc;
2313 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2314 startLoc = ECE->getLParenLoc();
2315 else
2316 startLoc = E->getLocStart();
2317 startLoc = SM->getInstantiationLoc(startLoc);
2318 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002319 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002320 }
2321 else {
2322 SourceLocation X = ND->getLocEnd();
2323 X = SM->getInstantiationLoc(X);
2324 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002325 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002326 }
2327}
2328
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002329// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002330void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002331 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2332 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002333 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002334 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002335 &ArgTys[0], ArgTys.size(),
2336 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002337 false, false, 0, 0,
2338 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002339 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002340 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002341 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002342 SC_Extern,
2343 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002344}
2345
Steve Naroffb29b4272008-04-14 22:03:09 +00002346void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002347 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002348 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002349 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002350 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002351 return;
2352 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002353 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002354}
2355
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002356void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2357 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002358 const char *argPtr = TypeString.c_str();
2359 if (!strchr(argPtr, '^')) {
2360 Str += TypeString;
2361 return;
2362 }
2363 while (*argPtr) {
2364 Str += (*argPtr == '^' ? '*' : *argPtr);
2365 argPtr++;
2366 }
2367}
2368
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002369// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002370void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2371 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002372 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002373 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002374 const char *argPtr = TypeString.c_str();
2375 int paren = 0;
2376 while (*argPtr) {
2377 switch (*argPtr) {
2378 case '(':
2379 Str += *argPtr;
2380 paren++;
2381 break;
2382 case ')':
2383 Str += *argPtr;
2384 paren--;
2385 break;
2386 case '^':
2387 Str += '*';
2388 if (paren == 1)
2389 Str += VD->getNameAsString();
2390 break;
2391 default:
2392 Str += *argPtr;
2393 break;
2394 }
2395 argPtr++;
2396 }
2397}
2398
2399
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002400void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2401 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2402 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2403 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2404 if (!proto)
2405 return;
2406 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002407 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002408 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002409 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002410 FdStr += "(";
2411 unsigned numArgs = proto->getNumArgs();
2412 for (unsigned i = 0; i < numArgs; i++) {
2413 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002414 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002415 if (i+1 < numArgs)
2416 FdStr += ", ";
2417 }
2418 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002419 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002420 CurFunctionDeclToDeclareForBlock = 0;
2421}
2422
Steve Naroffc0a123c2008-03-11 17:37:02 +00002423// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002424void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002425 if (SuperContructorFunctionDecl)
2426 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002427 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002428 llvm::SmallVector<QualType, 16> ArgTys;
2429 QualType argT = Context->getObjCIdType();
2430 assert(!argT.isNull() && "Can't find 'id' type");
2431 ArgTys.push_back(argT);
2432 ArgTys.push_back(argT);
2433 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2434 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002435 false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002436 false, false, 0, 0,
2437 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002438 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002439 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002440 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002441 SC_Extern,
2442 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002443}
2444
Steve Naroff09b266e2007-10-30 23:14:51 +00002445// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002446void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002447 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2448 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002449 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002450 assert(!argT.isNull() && "Can't find 'id' type");
2451 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002452 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002453 assert(!argT.isNull() && "Can't find 'SEL' type");
2454 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002455 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002456 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002457 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002458 false, false, 0, 0,
2459 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002460 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002461 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002462 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002463 SC_Extern,
2464 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002465}
2466
Steve Naroff874e2322007-11-15 10:28:18 +00002467// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002468void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002469 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2470 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002471 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002472 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002473 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002474 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2475 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2476 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002477 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002478 assert(!argT.isNull() && "Can't find 'SEL' type");
2479 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002480 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002481 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002482 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002483 false, false, 0, 0,
2484 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002485 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002486 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002487 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002488 SC_Extern,
2489 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002490}
2491
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002492// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002493void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002494 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2495 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002496 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002497 assert(!argT.isNull() && "Can't find 'id' type");
2498 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002499 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002500 assert(!argT.isNull() && "Can't find 'SEL' type");
2501 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002502 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002503 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002504 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002505 false, false, 0, 0,
2506 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002507 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002508 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002509 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002510 SC_Extern,
2511 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002512}
2513
Mike Stump1eb44332009-09-09 15:08:12 +00002514// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002515// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002516void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002517 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002518 &Context->Idents.get("objc_msgSendSuper_stret");
2519 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002520 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002521 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002522 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002523 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2524 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2525 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002526 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002527 assert(!argT.isNull() && "Can't find 'SEL' type");
2528 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002529 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002530 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002531 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002532 false, false, 0, 0,
2533 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002534 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002535 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002536 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002537 SC_Extern,
2538 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002539}
2540
Steve Naroff1284db82008-05-08 22:02:18 +00002541// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002542void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002543 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2544 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002545 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002546 assert(!argT.isNull() && "Can't find 'id' type");
2547 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002548 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002549 assert(!argT.isNull() && "Can't find 'SEL' type");
2550 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002551 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002552 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002553 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002554 false, false, 0, 0,
2555 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002556 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002557 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002558 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002559 SC_Extern,
2560 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002561}
2562
Steve Naroff09b266e2007-10-30 23:14:51 +00002563// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002564void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002565 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2566 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002567 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002568 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002569 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002570 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002571 false, false, 0, 0,
2572 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002573 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002574 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002575 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002576 SC_Extern,
2577 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002578}
2579
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002580// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2581void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2582 IdentifierInfo *getSuperClassIdent =
2583 &Context->Idents.get("class_getSuperclass");
2584 llvm::SmallVector<QualType, 16> ArgTys;
2585 ArgTys.push_back(Context->getObjCClassType());
2586 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2587 &ArgTys[0], ArgTys.size(),
2588 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002589 false, false, 0, 0,
2590 FunctionType::ExtInfo());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002591 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002592 SourceLocation(),
2593 getSuperClassIdent,
2594 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002595 SC_Extern,
2596 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002597 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002598}
2599
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002600// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002601void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002602 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2603 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002604 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002605 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002606 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002607 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002608 false, false, 0, 0,
2609 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002610 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002611 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002612 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002613 SC_Extern,
2614 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002615}
2616
Steve Naroffb29b4272008-04-14 22:03:09 +00002617Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002618 QualType strType = getConstantStringStructType();
2619
2620 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002621
2622 std::string tmpName = InFileName;
2623 unsigned i;
2624 for (i=0; i < tmpName.length(); i++) {
2625 char c = tmpName.at(i);
2626 // replace any non alphanumeric characters with '_'.
2627 if (!isalpha(c) && (c < '0' || c > '9'))
2628 tmpName[i] = '_';
2629 }
2630 S += tmpName;
2631 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002632 S += utostr(NumObjCStringLiterals++);
2633
Steve Naroffba92b2e2008-03-27 22:29:16 +00002634 Preamble += "static __NSConstantStringImpl " + S;
2635 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2636 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002637 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002638 std::string prettyBufS;
2639 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002640 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2641 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002642 Preamble += prettyBuf.str();
2643 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002644 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002645
2646 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002647 &Context->Idents.get(S), strType, 0,
John McCalld931b082010-08-26 03:08:43 +00002648 SC_Static, SC_None);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002649 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002650 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002651 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002652 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002653 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002654 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall2de56d12010-08-25 11:45:40 +00002655 CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002656 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002657 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002658 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002659}
2660
Steve Naroff874e2322007-11-15 10:28:18 +00002661// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002662QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002663 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002664 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002665 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002666 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002667 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002668
Steve Naroff874e2322007-11-15 10:28:18 +00002669 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002670 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002671 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002672 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002673
Steve Naroff874e2322007-11-15 10:28:18 +00002674 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002675 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002676 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2677 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002678 FieldTypes[i], 0,
2679 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002680 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002681 }
Mike Stump1eb44332009-09-09 15:08:12 +00002682
Douglas Gregor838db382010-02-11 01:19:42 +00002683 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002684 }
2685 return Context->getTagDeclType(SuperStructDecl);
2686}
2687
Steve Naroffb29b4272008-04-14 22:03:09 +00002688QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002689 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002690 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002691 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002692 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002693 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002694
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002695 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002696 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002697 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002698 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002699 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002700 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002701 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002702 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002703
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002704 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002705 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002706 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2707 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002708 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002709 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002710 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002711 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002712 }
2713
Douglas Gregor838db382010-02-11 01:19:42 +00002714 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002715 }
2716 return Context->getTagDeclType(ConstantStringDecl);
2717}
2718
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002719Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2720 SourceLocation StartLoc,
2721 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002722 if (!SelGetUidFunctionDecl)
2723 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002724 if (!MsgSendFunctionDecl)
2725 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002726 if (!MsgSendSuperFunctionDecl)
2727 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002728 if (!MsgSendStretFunctionDecl)
2729 SynthMsgSendStretFunctionDecl();
2730 if (!MsgSendSuperStretFunctionDecl)
2731 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002732 if (!MsgSendFpretFunctionDecl)
2733 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002734 if (!GetClassFunctionDecl)
2735 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002736 if (!GetSuperClassFunctionDecl)
2737 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002738 if (!GetMetaClassFunctionDecl)
2739 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Steve Naroff874e2322007-11-15 10:28:18 +00002741 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002742 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2743 // May need to use objc_msgSend_stret() as well.
2744 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002745 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2746 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002747 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002748 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002749 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002750 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002751 }
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Steve Naroff934f2762007-10-24 22:48:43 +00002753 // Synthesize a call to objc_msgSend().
2754 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002755 switch (Exp->getReceiverKind()) {
2756 case ObjCMessageExpr::SuperClass: {
2757 MsgSendFlavor = MsgSendSuperFunctionDecl;
2758 if (MsgSendStretFlavor)
2759 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2760 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002761
Douglas Gregor04badcf2010-04-21 00:45:42 +00002762 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Douglas Gregor04badcf2010-04-21 00:45:42 +00002764 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002765
Douglas Gregor04badcf2010-04-21 00:45:42 +00002766 // set the receiver to self, the first argument to all methods.
2767 InitExprs.push_back(
2768 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002769 CK_Unknown,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002770 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2771 Context->getObjCIdType(),
2772 SourceLocation()))
2773 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002774
Douglas Gregor04badcf2010-04-21 00:45:42 +00002775 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2776 llvm::SmallVector<Expr*, 8> ClsExprs;
2777 QualType argType = Context->getPointerType(Context->CharTy);
2778 ClsExprs.push_back(StringLiteral::Create(*Context,
2779 ClassDecl->getIdentifier()->getNameStart(),
2780 ClassDecl->getIdentifier()->getLength(),
2781 false, argType, SourceLocation()));
2782 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2783 &ClsExprs[0],
2784 ClsExprs.size(),
2785 StartLoc,
2786 EndLoc);
2787 // (Class)objc_getClass("CurrentClass")
2788 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2789 Context->getObjCClassType(),
John McCall2de56d12010-08-25 11:45:40 +00002790 CK_Unknown, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002791 ClsExprs.clear();
2792 ClsExprs.push_back(ArgExpr);
2793 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2794 &ClsExprs[0], ClsExprs.size(),
2795 StartLoc, EndLoc);
2796
2797 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2798 // To turn off a warning, type-cast to 'id'
2799 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2800 NoTypeInfoCStyleCastExpr(Context,
2801 Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002802 CK_Unknown, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002803 // struct objc_super
2804 QualType superType = getSuperStructType();
2805 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002806
Douglas Gregor04badcf2010-04-21 00:45:42 +00002807 if (LangOpts.Microsoft) {
2808 SynthSuperContructorFunctionDecl();
2809 // Simulate a contructor call...
2810 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2811 superType, SourceLocation());
2812 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2813 InitExprs.size(),
2814 superType, SourceLocation());
2815 // The code for super is a little tricky to prevent collision with
2816 // the structure definition in the header. The rewriter has it's own
2817 // internal definition (__rw_objc_super) that is uses. This is why
2818 // we need the cast below. For example:
2819 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2820 //
John McCall2de56d12010-08-25 11:45:40 +00002821 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002822 Context->getPointerType(SuperRep->getType()),
2823 SourceLocation());
2824 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2825 Context->getPointerType(superType),
John McCall2de56d12010-08-25 11:45:40 +00002826 CK_Unknown, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002827 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002828 // (struct objc_super) { <exprs from above> }
2829 InitListExpr *ILE =
2830 new (Context) InitListExpr(*Context, SourceLocation(),
2831 &InitExprs[0], InitExprs.size(),
2832 SourceLocation());
2833 TypeSourceInfo *superTInfo
2834 = Context->getTrivialTypeSourceInfo(superType);
2835 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2836 superType, ILE, false);
2837 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002838 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002839 Context->getPointerType(SuperRep->getType()),
2840 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002841 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002842 MsgExprs.push_back(SuperRep);
2843 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002844 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002845
2846 case ObjCMessageExpr::Class: {
2847 llvm::SmallVector<Expr*, 8> ClsExprs;
2848 QualType argType = Context->getPointerType(Context->CharTy);
2849 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002850 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002851 IdentifierInfo *clsName = Class->getIdentifier();
2852 ClsExprs.push_back(StringLiteral::Create(*Context,
2853 clsName->getNameStart(),
2854 clsName->getLength(),
2855 false, argType,
2856 SourceLocation()));
2857 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2858 &ClsExprs[0],
2859 ClsExprs.size(),
2860 StartLoc, EndLoc);
2861 MsgExprs.push_back(Cls);
2862 break;
2863 }
2864
2865 case ObjCMessageExpr::SuperInstance:{
2866 MsgSendFlavor = MsgSendSuperFunctionDecl;
2867 if (MsgSendStretFlavor)
2868 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2869 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2870 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2871 llvm::SmallVector<Expr*, 4> InitExprs;
2872
2873 InitExprs.push_back(
2874 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002875 CK_Unknown,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002876 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2877 Context->getObjCIdType(),
2878 SourceLocation()))
2879 ); // set the 'receiver'.
2880
2881 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2882 llvm::SmallVector<Expr*, 8> ClsExprs;
2883 QualType argType = Context->getPointerType(Context->CharTy);
2884 ClsExprs.push_back(StringLiteral::Create(*Context,
2885 ClassDecl->getIdentifier()->getNameStart(),
2886 ClassDecl->getIdentifier()->getLength(),
2887 false, argType, SourceLocation()));
2888 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2889 &ClsExprs[0],
2890 ClsExprs.size(),
2891 StartLoc, EndLoc);
2892 // (Class)objc_getClass("CurrentClass")
2893 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2894 Context->getObjCClassType(),
John McCall2de56d12010-08-25 11:45:40 +00002895 CK_Unknown, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002896 ClsExprs.clear();
2897 ClsExprs.push_back(ArgExpr);
2898 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2899 &ClsExprs[0], ClsExprs.size(),
2900 StartLoc, EndLoc);
2901
2902 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2903 // To turn off a warning, type-cast to 'id'
2904 InitExprs.push_back(
2905 // set 'super class', using class_getSuperclass().
2906 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002907 CK_Unknown, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002908 // struct objc_super
2909 QualType superType = getSuperStructType();
2910 Expr *SuperRep;
2911
2912 if (LangOpts.Microsoft) {
2913 SynthSuperContructorFunctionDecl();
2914 // Simulate a contructor call...
2915 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2916 superType, SourceLocation());
2917 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2918 InitExprs.size(),
2919 superType, SourceLocation());
2920 // The code for super is a little tricky to prevent collision with
2921 // the structure definition in the header. The rewriter has it's own
2922 // internal definition (__rw_objc_super) that is uses. This is why
2923 // we need the cast below. For example:
2924 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2925 //
John McCall2de56d12010-08-25 11:45:40 +00002926 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002927 Context->getPointerType(SuperRep->getType()),
2928 SourceLocation());
2929 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2930 Context->getPointerType(superType),
John McCall2de56d12010-08-25 11:45:40 +00002931 CK_Unknown, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002932 } else {
2933 // (struct objc_super) { <exprs from above> }
2934 InitListExpr *ILE =
2935 new (Context) InitListExpr(*Context, SourceLocation(),
2936 &InitExprs[0], InitExprs.size(),
2937 SourceLocation());
2938 TypeSourceInfo *superTInfo
2939 = Context->getTrivialTypeSourceInfo(superType);
2940 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2941 superType, ILE, false);
2942 }
2943 MsgExprs.push_back(SuperRep);
2944 break;
2945 }
2946
2947 case ObjCMessageExpr::Instance: {
2948 // Remove all type-casts because it may contain objc-style types; e.g.
2949 // Foo<Proto> *.
2950 Expr *recExpr = Exp->getInstanceReceiver();
2951 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2952 recExpr = CE->getSubExpr();
2953 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002954 CK_Unknown, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002955 MsgExprs.push_back(recExpr);
2956 break;
2957 }
2958 }
2959
Steve Naroffbeaf2992007-11-03 11:27:19 +00002960 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002961 llvm::SmallVector<Expr*, 8> SelExprs;
2962 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002963 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002964 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002965 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002966 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002967 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002968 &SelExprs[0], SelExprs.size(),
2969 StartLoc,
2970 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002971 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002972
Steve Naroff934f2762007-10-24 22:48:43 +00002973 // Now push any user supplied arguments.
2974 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002975 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002976 // Make all implicit casts explicit...ICE comes in handy:-)
2977 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2978 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002979 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002980 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002981 : ICE->getType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002982 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002983 (void)convertBlockPointerToFunctionPointer(type);
John McCall2de56d12010-08-25 11:45:40 +00002984 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00002985 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002986 }
2987 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002988 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002989 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002990 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002991 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002992 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002993 CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002994 }
Mike Stump1eb44332009-09-09 15:08:12 +00002995 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002996 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002997 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2998 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002999 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003000 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003001 }
Steve Naroffab972d32007-11-04 22:37:50 +00003002 // Generate the funky cast.
3003 CastExpr *cast;
3004 llvm::SmallVector<QualType, 8> ArgTypes;
3005 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003006
Steve Naroffab972d32007-11-04 22:37:50 +00003007 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003008 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3009 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3010 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003011 ArgTypes.push_back(Context->getObjCIdType());
3012 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003013 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003014 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003015 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3016 E = OMD->param_end(); PI != E; ++PI) {
3017 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003018 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003019 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003020 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003021 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003022 ArgTypes.push_back(t);
3023 }
Chris Lattner89951a82009-02-20 18:43:26 +00003024 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3025 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003026 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003027 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003028 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003029 }
3030 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003031 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003032
Steve Naroffab972d32007-11-04 22:37:50 +00003033 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003034 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003035 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003036
Mike Stump1eb44332009-09-09 15:08:12 +00003037 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003038 // If we don't do this cast, we get the following bizarre warning/note:
3039 // xx.m:13: warning: function called through a non-compatible type
3040 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003041 cast = NoTypeInfoCStyleCastExpr(Context,
3042 Context->getPointerType(Context->VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00003043 CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Steve Naroffab972d32007-11-04 22:37:50 +00003045 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003046 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003047 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00003048 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00003049 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003050 false, false, 0, 0,
3051 FunctionType::ExtInfo());
Steve Naroffab972d32007-11-04 22:37:50 +00003052 castType = Context->getPointerType(castType);
John McCall2de56d12010-08-25 11:45:40 +00003053 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00003054 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003055
3056 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003057 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003058
John McCall183700f2009-09-21 23:43:11 +00003059 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003060 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003061 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003062 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003063 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003064 if (MsgSendStretFlavor) {
3065 // We have the method which returns a struct/union. Must also generate
3066 // call to objc_msgSend_stret and hang both varieties on a conditional
3067 // expression which dictate which one to envoke depending on size of
3068 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003069
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003070 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003071 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003072 SourceLocation());
3073 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003074 cast = NoTypeInfoCStyleCastExpr(Context,
3075 Context->getPointerType(Context->VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00003076 CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003077 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003078 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003079 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00003080 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003081 false, false, 0, 0,
3082 FunctionType::ExtInfo());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003083 castType = Context->getPointerType(castType);
John McCall2de56d12010-08-25 11:45:40 +00003084 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00003085 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003086
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003087 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003088 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003089
John McCall183700f2009-09-21 23:43:11 +00003090 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003091 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003092 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00003093 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003094
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003095 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003096 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003097 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003098 Context->getSizeType(),
3099 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003100 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3101 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3102 // For X86 it is more complicated and some kind of target specific routine
3103 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003104 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003105 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003106 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3107 llvm::APInt(IntSize, 8),
3108 Context->IntTy,
3109 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003110 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
John McCall2de56d12010-08-25 11:45:40 +00003111 BO_LE,
Mike Stump1eb44332009-09-09 15:08:12 +00003112 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003113 SourceLocation());
3114 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003115 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003116 new (Context) ConditionalOperator(lessThanExpr,
3117 SourceLocation(), CE,
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003118 SourceLocation(), STCE, (Expr*)0,
3119 returnType);
3120 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3121 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003122 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003123 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003124 return ReplacingStmt;
3125}
3126
Steve Naroffb29b4272008-04-14 22:03:09 +00003127Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003128 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3129 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003130
Steve Naroff934f2762007-10-24 22:48:43 +00003131 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003132 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003133
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003134 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003135 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003136}
3137
Steve Naroff621edce2009-04-29 16:37:50 +00003138// typedef struct objc_object Protocol;
3139QualType RewriteObjC::getProtocolType() {
3140 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003141 TypeSourceInfo *TInfo
3142 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003143 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003144 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003145 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003146 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003147 }
3148 return Context->getTypeDeclType(ProtocolTypeDecl);
3149}
3150
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003151/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003152/// a synthesized/forward data reference (to the protocol's metadata).
3153/// The forward references (and metadata) are generated in
3154/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003155Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003156 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3157 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003158 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003159 ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003160 SC_Extern, SC_None);
Steve Naroff621edce2009-04-29 16:37:50 +00003161 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003162 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003163 Context->getPointerType(DRE->getType()),
3164 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003165 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCall2de56d12010-08-25 11:45:40 +00003166 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00003167 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003168 ReplaceStmt(Exp, castExpr);
3169 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003170 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003171 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003172
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003173}
3174
Mike Stump1eb44332009-09-09 15:08:12 +00003175bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003176 const char *endBuf) {
3177 while (startBuf < endBuf) {
3178 if (*startBuf == '#') {
3179 // Skip whitespace.
3180 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3181 ;
3182 if (!strncmp(startBuf, "if", strlen("if")) ||
3183 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3184 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3185 !strncmp(startBuf, "define", strlen("define")) ||
3186 !strncmp(startBuf, "undef", strlen("undef")) ||
3187 !strncmp(startBuf, "else", strlen("else")) ||
3188 !strncmp(startBuf, "elif", strlen("elif")) ||
3189 !strncmp(startBuf, "endif", strlen("endif")) ||
3190 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3191 !strncmp(startBuf, "include", strlen("include")) ||
3192 !strncmp(startBuf, "import", strlen("import")) ||
3193 !strncmp(startBuf, "include_next", strlen("include_next")))
3194 return true;
3195 }
3196 startBuf++;
3197 }
3198 return false;
3199}
3200
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003201/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003202/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003203void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003204 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003205 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003206 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003207 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003208 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003209 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003210 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003211 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003212 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003213 SourceLocation LocStart = CDecl->getLocStart();
3214 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003215
Steve Narofffea763e82007-11-14 19:25:57 +00003216 const char *startBuf = SM->getCharacterData(LocStart);
3217 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003218
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003219 // If no ivars and no root or if its root, directly or indirectly,
3220 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003221 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3222 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003223 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003224 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003225 return;
3226 }
Mike Stump1eb44332009-09-09 15:08:12 +00003227
3228 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003229 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003230 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003231 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003232 if (LangOpts.Microsoft)
3233 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003234
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003235 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003236 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003237 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003238 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003239 // If the buffer contains preprocessor directives, we do more fine-grained
3240 // rewrites. This is intended to fix code that looks like (which occurs in
3241 // NSURL.h, for example):
3242 //
3243 // #ifdef XYZ
3244 // @interface Foo : NSObject
3245 // #else
3246 // @interface FooBar : NSObject
3247 // #endif
3248 // {
3249 // int i;
3250 // }
3251 // @end
3252 //
3253 // This clause is segregated to avoid breaking the common case.
3254 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003255 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003256 CDecl->getClassLoc();
3257 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003258 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003259
Chris Lattnercafeb352009-02-20 18:18:36 +00003260 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003261 // advance to the end of the referenced protocols.
3262 while (endHeader < cursor && *endHeader != '>') endHeader++;
3263 endHeader++;
3264 }
3265 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003266 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003267 } else {
3268 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003269 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003270 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003271 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003272 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003273 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003274 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003275 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003276 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003277
Steve Narofffea763e82007-11-14 19:25:57 +00003278 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003279 SourceLocation OnePastCurly =
3280 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003281 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003282 }
3283 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003284
Steve Narofffea763e82007-11-14 19:25:57 +00003285 // Now comment out any visibility specifiers.
3286 while (cursor < endBuf) {
3287 if (*cursor == '@') {
3288 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003289 // Skip whitespace.
3290 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3291 /*scan*/;
3292
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003293 // FIXME: presence of @public, etc. inside comment results in
3294 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003295 if (!strncmp(cursor, "public", strlen("public")) ||
3296 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003297 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003298 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003299 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003300 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003301 // FIXME: If there are cases where '<' is used in ivar declaration part
3302 // of user code, then scan the ivar list and use needToScanForQualifiers
3303 // for type checking.
3304 else if (*cursor == '<') {
3305 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003306 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003307 cursor = strchr(cursor, '>');
3308 cursor++;
3309 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003310 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003311 } else if (*cursor == '^') { // rewrite block specifier.
3312 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003313 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003314 }
Steve Narofffea763e82007-11-14 19:25:57 +00003315 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003316 }
Steve Narofffea763e82007-11-14 19:25:57 +00003317 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003318 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003319 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003320 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003321 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003322 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003323 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003324 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003325 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003326 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003327 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003328 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003329 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003330 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003331}
3332
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003333// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003334/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003335template<typename MethodIterator>
3336void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3337 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003338 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003339 llvm::StringRef prefix,
3340 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003341 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003342 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003343
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003344 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003345 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003346 SEL _cmd;
3347 char *method_types;
3348 void *_imp;
3349 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003350 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003351 Result += "\nstruct _objc_method {\n";
3352 Result += "\tSEL _cmd;\n";
3353 Result += "\tchar *method_types;\n";
3354 Result += "\tvoid *_imp;\n";
3355 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003357 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003358 }
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003360 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003361
Steve Naroff946a6932008-03-11 00:12:29 +00003362 /* struct {
3363 struct _objc_method_list *next_method;
3364 int method_count;
3365 struct _objc_method method_list[];
3366 }
3367 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003368 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003369 Result += "\nstatic struct {\n";
3370 Result += "\tstruct _objc_method_list *next_method;\n";
3371 Result += "\tint method_count;\n";
3372 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003373 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003374 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003375 Result += prefix;
3376 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3377 Result += "_METHODS_";
3378 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003379 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003380 Result += IsInstanceMethod ? "inst" : "cls";
3381 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003382 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003383
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003384 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003385 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003386 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003387 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003388 Result += "\", \"";
3389 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003390 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003391 Result += MethodInternalNames[*MethodBegin];
3392 Result += "}\n";
3393 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3394 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003395 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003396 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003397 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003398 Result += "\", \"";
3399 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003400 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003401 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003402 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003403 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003404 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003405}
3406
Steve Naroff621edce2009-04-29 16:37:50 +00003407/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003408void RewriteObjC::
Daniel Dunbar4087f272010-08-17 22:39:59 +00003409RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3410 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003411 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003412
3413 // Output struct protocol_methods holder of method selector and type.
3414 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3415 /* struct protocol_methods {
3416 SEL _cmd;
3417 char *method_types;
3418 }
3419 */
3420 Result += "\nstruct _protocol_methods {\n";
3421 Result += "\tstruct objc_selector *_cmd;\n";
3422 Result += "\tchar *method_types;\n";
3423 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Steve Naroff621edce2009-04-29 16:37:50 +00003425 objc_protocol_methods = true;
3426 }
3427 // Do not synthesize the protocol more than once.
3428 if (ObjCSynthesizedProtocols.count(PDecl))
3429 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003430
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003431 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3432 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3433 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003434 /* struct _objc_protocol_method_list {
3435 int protocol_method_count;
3436 struct protocol_methods protocols[];
3437 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003438 */
Steve Naroff621edce2009-04-29 16:37:50 +00003439 Result += "\nstatic struct {\n";
3440 Result += "\tint protocol_method_count;\n";
3441 Result += "\tstruct _protocol_methods protocol_methods[";
3442 Result += utostr(NumMethods);
3443 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3444 Result += PDecl->getNameAsString();
3445 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3446 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003447
Steve Naroff621edce2009-04-29 16:37:50 +00003448 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003449 for (ObjCProtocolDecl::instmeth_iterator
3450 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003451 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003452 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003453 Result += "\t ,{{(struct objc_selector *)\"";
3454 else
3455 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003456 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003457 std::string MethodTypeString;
3458 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3459 Result += "\", \"";
3460 Result += MethodTypeString;
3461 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003462 }
Steve Naroff621edce2009-04-29 16:37:50 +00003463 Result += "\t }\n};\n";
3464 }
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Steve Naroff621edce2009-04-29 16:37:50 +00003466 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003467 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3468 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003469 if (NumMethods > 0) {
3470 /* struct _objc_protocol_method_list {
3471 int protocol_method_count;
3472 struct protocol_methods protocols[];
3473 }
3474 */
3475 Result += "\nstatic struct {\n";
3476 Result += "\tint protocol_method_count;\n";
3477 Result += "\tstruct _protocol_methods protocol_methods[";
3478 Result += utostr(NumMethods);
3479 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3480 Result += PDecl->getNameAsString();
3481 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3482 "{\n\t";
3483 Result += utostr(NumMethods);
3484 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003485
Steve Naroff621edce2009-04-29 16:37:50 +00003486 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003487 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003488 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003489 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003490 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003491 Result += "\t ,{{(struct objc_selector *)\"";
3492 else
3493 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003494 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003495 std::string MethodTypeString;
3496 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3497 Result += "\", \"";
3498 Result += MethodTypeString;
3499 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003500 }
Steve Naroff621edce2009-04-29 16:37:50 +00003501 Result += "\t }\n};\n";
3502 }
3503
3504 // Output:
3505 /* struct _objc_protocol {
3506 // Objective-C 1.0 extensions
3507 struct _objc_protocol_extension *isa;
3508 char *protocol_name;
3509 struct _objc_protocol **protocol_list;
3510 struct _objc_protocol_method_list *instance_methods;
3511 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003512 };
Steve Naroff621edce2009-04-29 16:37:50 +00003513 */
3514 static bool objc_protocol = false;
3515 if (!objc_protocol) {
3516 Result += "\nstruct _objc_protocol {\n";
3517 Result += "\tstruct _objc_protocol_extension *isa;\n";
3518 Result += "\tchar *protocol_name;\n";
3519 Result += "\tstruct _objc_protocol **protocol_list;\n";
3520 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3521 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003522 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003523
Steve Naroff621edce2009-04-29 16:37:50 +00003524 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003525 }
Mike Stump1eb44332009-09-09 15:08:12 +00003526
Steve Naroff621edce2009-04-29 16:37:50 +00003527 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3528 Result += PDecl->getNameAsString();
3529 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3530 "{\n\t0, \"";
3531 Result += PDecl->getNameAsString();
3532 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003533 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003534 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3535 Result += PDecl->getNameAsString();
3536 Result += ", ";
3537 }
3538 else
3539 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003540 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003541 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3542 Result += PDecl->getNameAsString();
3543 Result += "\n";
3544 }
3545 else
3546 Result += "0\n";
3547 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Steve Naroff621edce2009-04-29 16:37:50 +00003549 // Mark this protocol as having been generated.
3550 if (!ObjCSynthesizedProtocols.insert(PDecl))
3551 assert(false && "protocol already synthesized");
3552
3553}
3554
3555void RewriteObjC::
3556RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003557 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003558 std::string &Result) {
3559 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Steve Naroff621edce2009-04-29 16:37:50 +00003561 for (unsigned i = 0; i != Protocols.size(); i++)
3562 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3563
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003564 // Output the top lovel protocol meta-data for the class.
3565 /* struct _objc_protocol_list {
3566 struct _objc_protocol_list *next;
3567 int protocol_count;
3568 struct _objc_protocol *class_protocols[];
3569 }
3570 */
3571 Result += "\nstatic struct {\n";
3572 Result += "\tstruct _objc_protocol_list *next;\n";
3573 Result += "\tint protocol_count;\n";
3574 Result += "\tstruct _objc_protocol *class_protocols[";
3575 Result += utostr(Protocols.size());
3576 Result += "];\n} _OBJC_";
3577 Result += prefix;
3578 Result += "_PROTOCOLS_";
3579 Result += ClassName;
3580 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3581 "{\n\t0, ";
3582 Result += utostr(Protocols.size());
3583 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003584
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003585 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003586 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003587 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003588
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003589 for (unsigned i = 1; i != Protocols.size(); i++) {
3590 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003591 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003592 Result += "\n";
3593 }
3594 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003595}
3596
Steve Naroff621edce2009-04-29 16:37:50 +00003597
Mike Stump1eb44332009-09-09 15:08:12 +00003598/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003599/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003600void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003601 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003602 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003603 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003604 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003605 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003606 CDecl = CDecl->getNextClassCategory())
3607 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3608 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003609
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003610 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003611 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003612 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003613
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003614 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003615 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003616 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003617
3618 // If any of our property implementations have associated getters or
3619 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003620 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3621 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003622 Prop != PropEnd; ++Prop) {
3623 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3624 continue;
3625 if (!(*Prop)->getPropertyIvarDecl())
3626 continue;
3627 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3628 if (!PD)
3629 continue;
3630 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3631 InstanceMethods.push_back(Getter);
3632 if (PD->isReadOnly())
3633 continue;
3634 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3635 InstanceMethods.push_back(Setter);
3636 }
3637 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003638 true, "CATEGORY_", FullCategoryName.c_str(),
3639 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003640
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003641 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003642 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003643 false, "CATEGORY_", FullCategoryName.c_str(),
3644 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003645
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003646 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003647 // Null CDecl is case of a category implementation with no category interface
3648 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003649 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003650 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003651 /* struct _objc_category {
3652 char *category_name;
3653 char *class_name;
3654 struct _objc_method_list *instance_methods;
3655 struct _objc_method_list *class_methods;
3656 struct _objc_protocol_list *protocols;
3657 // Objective-C 1.0 extensions
3658 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003659 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003660 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003661 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003662 */
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003664 static bool objc_category = false;
3665 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003666 Result += "\nstruct _objc_category {\n";
3667 Result += "\tchar *category_name;\n";
3668 Result += "\tchar *class_name;\n";
3669 Result += "\tstruct _objc_method_list *instance_methods;\n";
3670 Result += "\tstruct _objc_method_list *class_methods;\n";
3671 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003672 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003673 Result += "\tstruct _objc_property_list *instance_properties;\n";
3674 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003675 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003676 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003677 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3678 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003679 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003680 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003681 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003682 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003683 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003685 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003686 Result += "\t, (struct _objc_method_list *)"
3687 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3688 Result += FullCategoryName;
3689 Result += "\n";
3690 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003691 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003692 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003693 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003694 Result += "\t, (struct _objc_method_list *)"
3695 "&_OBJC_CATEGORY_CLASS_METHODS_";
3696 Result += FullCategoryName;
3697 Result += "\n";
3698 }
3699 else
3700 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003701
Chris Lattnercafeb352009-02-20 18:18:36 +00003702 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003703 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003704 Result += FullCategoryName;
3705 Result += "\n";
3706 }
3707 else
3708 Result += "\t, 0\n";
3709 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003710}
3711
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003712/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3713/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003714void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003715 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003716 if (ivar->isBitField()) {
3717 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3718 // place all bitfields at offset 0.
3719 Result += "0";
3720 } else {
3721 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003722 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003723 if (LangOpts.Microsoft)
3724 Result += "_IMPL";
3725 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003726 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003727 Result += ")";
3728 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003729}
3730
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003731//===----------------------------------------------------------------------===//
3732// Meta Data Emission
3733//===----------------------------------------------------------------------===//
3734
Steve Naroffb29b4272008-04-14 22:03:09 +00003735void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003736 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003737 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003738
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003739 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003740 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003741 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003742 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003743 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003744 }
Mike Stump1eb44332009-09-09 15:08:12 +00003745
Chris Lattnerbe6df082007-12-12 07:56:42 +00003746 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003747 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003748 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003749 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003750 if (NumIvars > 0) {
3751 static bool objc_ivar = false;
3752 if (!objc_ivar) {
3753 /* struct _objc_ivar {
3754 char *ivar_name;
3755 char *ivar_type;
3756 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003757 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003758 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003759 Result += "\nstruct _objc_ivar {\n";
3760 Result += "\tchar *ivar_name;\n";
3761 Result += "\tchar *ivar_type;\n";
3762 Result += "\tint ivar_offset;\n";
3763 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003764
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003765 objc_ivar = true;
3766 }
3767
Steve Naroff946a6932008-03-11 00:12:29 +00003768 /* struct {
3769 int ivar_count;
3770 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003771 };
Steve Naroff946a6932008-03-11 00:12:29 +00003772 */
Mike Stump1eb44332009-09-09 15:08:12 +00003773 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003774 Result += "\tint ivar_count;\n";
3775 Result += "\tstruct _objc_ivar ivar_list[";
3776 Result += utostr(NumIvars);
3777 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003778 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003779 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003780 "{\n\t";
3781 Result += utostr(NumIvars);
3782 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003783
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003784 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003785 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003786 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003787 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003788 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003789 IV != IVEnd; ++IV)
3790 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003791 IVI = IDecl->ivar_begin();
3792 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003793 } else {
3794 IVI = CDecl->ivar_begin();
3795 IVE = CDecl->ivar_end();
3796 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003797 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003798 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003799 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003800 std::string TmpString, StrEncoding;
3801 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3802 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003803 Result += StrEncoding;
3804 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003805 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003806 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003807 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003808 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003809 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003810 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003811 std::string TmpString, StrEncoding;
3812 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3813 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003814 Result += StrEncoding;
3815 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003816 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003817 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003818 }
Mike Stump1eb44332009-09-09 15:08:12 +00003819
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003820 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003821 }
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003823 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003824 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003825 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003826
3827 // If any of our property implementations have associated getters or
3828 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003829 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3830 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003831 Prop != PropEnd; ++Prop) {
3832 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3833 continue;
3834 if (!(*Prop)->getPropertyIvarDecl())
3835 continue;
3836 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3837 if (!PD)
3838 continue;
3839 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003840 if (!Getter->isDefined())
3841 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003842 if (PD->isReadOnly())
3843 continue;
3844 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003845 if (!Setter->isDefined())
3846 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003847 }
3848 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003849 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003851 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003852 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003853 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003854
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003855 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003856 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003857 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003859 // Declaration of class/meta-class metadata
3860 /* struct _objc_class {
3861 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003862 const char *super_class_name;
3863 char *name;
3864 long version;
3865 long info;
3866 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003867 struct _objc_ivar_list *ivars;
3868 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003869 struct objc_cache *cache;
3870 struct objc_protocol_list *protocols;
3871 const char *ivar_layout;
3872 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003873 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003874 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003875 static bool objc_class = false;
3876 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003877 Result += "\nstruct _objc_class {\n";
3878 Result += "\tstruct _objc_class *isa;\n";
3879 Result += "\tconst char *super_class_name;\n";
3880 Result += "\tchar *name;\n";
3881 Result += "\tlong version;\n";
3882 Result += "\tlong info;\n";
3883 Result += "\tlong instance_size;\n";
3884 Result += "\tstruct _objc_ivar_list *ivars;\n";
3885 Result += "\tstruct _objc_method_list *methods;\n";
3886 Result += "\tstruct objc_cache *cache;\n";
3887 Result += "\tstruct _objc_protocol_list *protocols;\n";
3888 Result += "\tconst char *ivar_layout;\n";
3889 Result += "\tstruct _objc_class_ext *ext;\n";
3890 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003891 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003892 }
Mike Stump1eb44332009-09-09 15:08:12 +00003893
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003894 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003895 ObjCInterfaceDecl *RootClass = 0;
3896 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003897 while (SuperClass) {
3898 RootClass = SuperClass;
3899 SuperClass = SuperClass->getSuperClass();
3900 }
3901 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003902
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003903 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003904 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003905 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003906 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003907 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003908 Result += "\"";
3909
3910 if (SuperClass) {
3911 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003912 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003913 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003914 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003915 Result += "\"";
3916 }
3917 else {
3918 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003919 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003920 Result += "\"";
3921 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003922 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003923 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003924 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003925 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003926 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003927 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003928 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003929 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003930 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003931 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003932 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003933 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003934 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003935 Result += ",0,0\n";
3936 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003937 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003938 Result += "\t,0,0,0,0\n";
3939 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003940
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003941 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003942 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003943 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003944 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003945 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003946 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003947 if (SuperClass) {
3948 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003949 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003950 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003951 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003952 Result += "\"";
3953 }
3954 else {
3955 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003956 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003957 Result += "\"";
3958 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003959 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003960 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003961 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003962 Result += ",0";
3963 else {
3964 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003965 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003966 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003967 if (LangOpts.Microsoft)
3968 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003969 Result += ")";
3970 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003971 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003972 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003973 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003974 Result += "\n\t";
3975 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003976 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003977 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003978 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003979 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003980 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003981 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003982 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003983 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003984 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003985 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003986 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003987 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003988 Result += ", 0,0\n";
3989 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003990 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003991 Result += ",0,0,0\n";
3992 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003993}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003994
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003995/// RewriteImplementations - This routine rewrites all method implementations
3996/// and emits meta-data.
3997
Steve Narofface66252008-11-13 20:07:04 +00003998void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003999 int ClsDefCount = ClassImplementation.size();
4000 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004001
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004002 // Rewrite implemented methods
4003 for (int i = 0; i < ClsDefCount; i++)
4004 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004005
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004006 for (int i = 0; i < CatDefCount; i++)
4007 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004008}
Mike Stump1eb44332009-09-09 15:08:12 +00004009
Steve Narofface66252008-11-13 20:07:04 +00004010void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4011 int ClsDefCount = ClassImplementation.size();
4012 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004013
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004014 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004015 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004016 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004018 // For each implemented category, write out all its meta data.
4019 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004020 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004021
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004022 // Write objc_symtab metadata
4023 /*
4024 struct _objc_symtab
4025 {
4026 long sel_ref_cnt;
4027 SEL *refs;
4028 short cls_def_cnt;
4029 short cat_def_cnt;
4030 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004031 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004032 */
Mike Stump1eb44332009-09-09 15:08:12 +00004033
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004034 Result += "\nstruct _objc_symtab {\n";
4035 Result += "\tlong sel_ref_cnt;\n";
4036 Result += "\tSEL *refs;\n";
4037 Result += "\tshort cls_def_cnt;\n";
4038 Result += "\tshort cat_def_cnt;\n";
4039 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4040 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004042 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004043 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004044 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004045 + ", " + utostr(CatDefCount) + "\n";
4046 for (int i = 0; i < ClsDefCount; i++) {
4047 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004048 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004049 Result += "\n";
4050 }
Mike Stump1eb44332009-09-09 15:08:12 +00004051
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004052 for (int i = 0; i < CatDefCount; i++) {
4053 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004054 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004055 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004056 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004057 Result += "\n";
4058 }
Mike Stump1eb44332009-09-09 15:08:12 +00004059
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004060 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004061
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004062 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004063
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004064 /*
4065 struct _objc_module {
4066 long version;
4067 long size;
4068 const char *name;
4069 struct _objc_symtab *symtab;
4070 }
4071 */
Mike Stump1eb44332009-09-09 15:08:12 +00004072
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004073 Result += "\nstruct _objc_module {\n";
4074 Result += "\tlong version;\n";
4075 Result += "\tlong size;\n";
4076 Result += "\tconst char *name;\n";
4077 Result += "\tstruct _objc_symtab *symtab;\n";
4078 Result += "};\n\n";
4079 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004080 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004081 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004082 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004083 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004084
4085 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004086 if (ProtocolExprDecls.size()) {
4087 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4088 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004089 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004090 E = ProtocolExprDecls.end(); I != E; ++I) {
4091 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4092 Result += (*I)->getNameAsString();
4093 Result += " = &_OBJC_PROTOCOL_";
4094 Result += (*I)->getNameAsString();
4095 Result += ";\n";
4096 }
4097 Result += "#pragma data_seg(pop)\n\n";
4098 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004099 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004100 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004101 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4102 Result += "&_OBJC_MODULES;\n";
4103 Result += "#pragma data_seg(pop)\n\n";
4104 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004105}
Chris Lattner311ff022007-10-16 22:36:42 +00004106
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004107void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4108 const std::string &Name,
4109 ValueDecl *VD) {
4110 assert(BlockByRefDeclNo.count(VD) &&
4111 "RewriteByRefString: ByRef decl missing");
4112 ResultStr += "struct __Block_byref_" + Name +
4113 "_" + utostr(BlockByRefDeclNo[VD]) ;
4114}
4115
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004116static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4117 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4118 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4119 return false;
4120}
4121
Steve Naroff54055232008-10-27 17:20:55 +00004122std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004123 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004124 std::string Tag) {
4125 const FunctionType *AFT = CE->getFunctionType();
4126 QualType RT = AFT->getResultType();
4127 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004128 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004129 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004130
Steve Naroff54055232008-10-27 17:20:55 +00004131 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004132
Douglas Gregor72564e72009-02-26 23:50:07 +00004133 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004134 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004135 // block (to reference imported block decl refs).
4136 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004137 } else if (BD->param_empty()) {
4138 S += "(" + StructRef + " *__cself)";
4139 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004140 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004141 assert(FT && "SynthesizeBlockFunc: No function proto");
4142 S += '(';
4143 // first add the implicit argument.
4144 S += StructRef + " *__cself, ";
4145 std::string ParamStr;
4146 for (BlockDecl::param_iterator AI = BD->param_begin(),
4147 E = BD->param_end(); AI != E; ++AI) {
4148 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004149 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004150 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004151 if (convertBlockPointerToFunctionPointer(QT))
4152 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004153 else
4154 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004155 S += ParamStr;
4156 }
4157 if (FT->isVariadic()) {
4158 if (!BD->param_empty()) S += ", ";
4159 S += "...";
4160 }
4161 S += ')';
4162 }
4163 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004164
Steve Naroff54055232008-10-27 17:20:55 +00004165 // Create local declarations to avoid rewriting all closure decl ref exprs.
4166 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004167 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004168 E = BlockByRefDecls.end(); I != E; ++I) {
4169 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004170 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004171 std::string TypeString;
4172 RewriteByRefString(TypeString, Name, (*I));
4173 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004174 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004175 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004176 }
Steve Naroff54055232008-10-27 17:20:55 +00004177 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004178 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004179 E = BlockByCopyDecls.end(); I != E; ++I) {
4180 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004181 // Handle nested closure invocation. For example:
4182 //
4183 // void (^myImportedClosure)(void);
4184 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004185 //
Steve Naroff54055232008-10-27 17:20:55 +00004186 // void (^anotherClosure)(void);
4187 // anotherClosure = ^(void) {
4188 // myImportedClosure(); // import and invoke the closure
4189 // };
4190 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004191 if (isTopLevelBlockPointerType((*I)->getType())) {
4192 RewriteBlockPointerTypeVariable(S, (*I));
4193 S += " = (";
4194 RewriteBlockPointerType(S, (*I)->getType());
4195 S += ")";
4196 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4197 }
4198 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004199 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004200 QualType QT = (*I)->getType();
4201 if (HasLocalVariableExternalStorage(*I))
4202 QT = Context->getPointerType(QT);
4203 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004204 S += Name + " = __cself->" +
4205 (*I)->getNameAsString() + "; // bound by copy\n";
4206 }
Steve Naroff54055232008-10-27 17:20:55 +00004207 }
4208 std::string RewrittenStr = RewrittenBlockExprs[CE];
4209 const char *cstr = RewrittenStr.c_str();
4210 while (*cstr++ != '{') ;
4211 S += cstr;
4212 S += "\n";
4213 return S;
4214}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004215
Steve Naroff54055232008-10-27 17:20:55 +00004216std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004217 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004218 std::string Tag) {
4219 std::string StructRef = "struct " + Tag;
4220 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004221
Steve Naroff54055232008-10-27 17:20:55 +00004222 S += funcName;
4223 S += "_block_copy_" + utostr(i);
4224 S += "(" + StructRef;
4225 S += "*dst, " + StructRef;
4226 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004227 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004228 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004229 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004230 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004231 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004232 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004233 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004234 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004235 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004236 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004237 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004238 S += "}\n";
4239
Steve Naroff54055232008-10-27 17:20:55 +00004240 S += "\nstatic void __";
4241 S += funcName;
4242 S += "_block_dispose_" + utostr(i);
4243 S += "(" + StructRef;
4244 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004245 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004246 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004247 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004248 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004249 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004250 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004251 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004252 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004253 }
Mike Stump1eb44332009-09-09 15:08:12 +00004254 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004255 return S;
4256}
4257
Steve Naroff01aec112009-12-06 21:14:13 +00004258std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4259 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004260 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004261 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004262
Steve Naroff54055232008-10-27 17:20:55 +00004263 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004264 S += " struct " + Desc;
4265 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004266
Steve Naroff01aec112009-12-06 21:14:13 +00004267 Constructor += "(void *fp, "; // Invoke function pointer.
4268 Constructor += "struct " + Desc; // Descriptor pointer.
4269 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004270
Steve Naroff54055232008-10-27 17:20:55 +00004271 if (BlockDeclRefs.size()) {
4272 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004273 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004274 E = BlockByCopyDecls.end(); I != E; ++I) {
4275 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004276 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004277 std::string ArgName = "_" + FieldName;
4278 // Handle nested closure invocation. For example:
4279 //
4280 // void (^myImportedBlock)(void);
4281 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004282 //
Steve Naroff54055232008-10-27 17:20:55 +00004283 // void (^anotherBlock)(void);
4284 // anotherBlock = ^(void) {
4285 // myImportedBlock(); // import and invoke the closure
4286 // };
4287 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004288 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004289 S += "struct __block_impl *";
4290 Constructor += ", void *" + ArgName;
4291 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004292 QualType QT = (*I)->getType();
4293 if (HasLocalVariableExternalStorage(*I))
4294 QT = Context->getPointerType(QT);
4295 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4296 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004297 Constructor += ", " + ArgName;
4298 }
4299 S += FieldName + ";\n";
4300 }
4301 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004302 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004303 E = BlockByRefDecls.end(); I != E; ++I) {
4304 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004305 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004306 std::string ArgName = "_" + FieldName;
4307 // Handle nested closure invocation. For example:
4308 //
4309 // void (^myImportedBlock)(void);
4310 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004311 //
Steve Naroff54055232008-10-27 17:20:55 +00004312 // void (^anotherBlock)(void);
4313 // anotherBlock = ^(void) {
4314 // myImportedBlock(); // import and invoke the closure
4315 // };
4316 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004317 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004318 S += "struct __block_impl *";
4319 Constructor += ", void *" + ArgName;
4320 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004321 std::string TypeString;
4322 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004323 TypeString += " *";
4324 FieldName = TypeString + FieldName;
4325 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004326 Constructor += ", " + ArgName;
4327 }
4328 S += FieldName + "; // by ref\n";
4329 }
4330 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004331 Constructor += ", int flags=0)";
4332 // Initialize all "by copy" arguments.
4333 bool firsTime = true;
4334 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4335 E = BlockByCopyDecls.end(); I != E; ++I) {
4336 std::string Name = (*I)->getNameAsString();
4337 if (firsTime) {
4338 Constructor += " : ";
4339 firsTime = false;
4340 }
4341 else
4342 Constructor += ", ";
4343 if (isTopLevelBlockPointerType((*I)->getType()))
4344 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4345 else
4346 Constructor += Name + "(_" + Name + ")";
4347 }
4348 // Initialize all "by ref" arguments.
4349 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4350 E = BlockByRefDecls.end(); I != E; ++I) {
4351 std::string Name = (*I)->getNameAsString();
4352 if (firsTime) {
4353 Constructor += " : ";
4354 firsTime = false;
4355 }
4356 else
4357 Constructor += ", ";
4358 if (isTopLevelBlockPointerType((*I)->getType()))
4359 Constructor += Name + "((struct __block_impl *)_"
4360 + Name + "->__forwarding)";
4361 else
4362 Constructor += Name + "(_" + Name + "->__forwarding)";
4363 }
4364
4365 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004366 if (GlobalVarDecl)
4367 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4368 else
4369 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004370 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004371
Steve Naroff01aec112009-12-06 21:14:13 +00004372 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004373 } else {
4374 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004375 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004376 if (GlobalVarDecl)
4377 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4378 else
4379 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004380 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4381 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004382 }
4383 Constructor += " ";
4384 Constructor += "}\n";
4385 S += Constructor;
4386 S += "};\n";
4387 return S;
4388}
4389
Steve Naroff01aec112009-12-06 21:14:13 +00004390std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4391 std::string ImplTag, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004392 llvm::StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004393 unsigned hasCopy) {
4394 std::string S = "\nstatic struct " + DescTag;
4395
4396 S += " {\n unsigned long reserved;\n";
4397 S += " unsigned long Block_size;\n";
4398 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004399 S += " void (*copy)(struct ";
4400 S += ImplTag; S += "*, struct ";
4401 S += ImplTag; S += "*);\n";
4402
4403 S += " void (*dispose)(struct ";
4404 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004405 }
4406 S += "} ";
4407
4408 S += DescTag + "_DATA = { 0, sizeof(struct ";
4409 S += ImplTag + ")";
4410 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004411 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4412 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004413 }
4414 S += "};\n";
4415 return S;
4416}
4417
Steve Naroff54055232008-10-27 17:20:55 +00004418void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004419 llvm::StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004420 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004421 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004422 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004423 bool RewriteSC = (GlobalVarDecl &&
4424 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004425 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004426 GlobalVarDecl->getType().getCVRQualifiers());
4427 if (RewriteSC) {
4428 std::string SC(" void __");
4429 SC += GlobalVarDecl->getNameAsString();
4430 SC += "() {}";
4431 InsertText(FunLocStart, SC);
4432 }
4433
Steve Naroff54055232008-10-27 17:20:55 +00004434 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004435 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4436 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004437 // Need to copy-in the inner copied-in variables not actually used in this
4438 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004439 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4440 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4441 ValueDecl *VD = Exp->getDecl();
4442 BlockDeclRefs.push_back(Exp);
4443 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4444 BlockByCopyDeclsPtrSet.insert(VD);
4445 BlockByCopyDecls.push_back(VD);
4446 }
4447 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4448 BlockByRefDeclsPtrSet.insert(VD);
4449 BlockByRefDecls.push_back(VD);
4450 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004451 // imported objects in the inner blocks not used in the outer
4452 // blocks must be copied/disposed in the outer block as well.
4453 if (Exp->isByRef() ||
4454 VD->getType()->isObjCObjectPointerType() ||
4455 VD->getType()->isBlockPointerType())
4456 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004457 }
Steve Naroff54055232008-10-27 17:20:55 +00004458
Daniel Dunbar4087f272010-08-17 22:39:59 +00004459 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4460 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004461
Steve Naroff01aec112009-12-06 21:14:13 +00004462 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004463
Benjamin Kramerd999b372010-02-14 14:14:16 +00004464 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004465
Steve Naroff01aec112009-12-06 21:14:13 +00004466 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004467
Benjamin Kramerd999b372010-02-14 14:14:16 +00004468 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004469
4470 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004471 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004472 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004473 }
Steve Naroff01aec112009-12-06 21:14:13 +00004474 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4475 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004476 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004477
Steve Naroff54055232008-10-27 17:20:55 +00004478 BlockDeclRefs.clear();
4479 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004480 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004481 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004482 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004483 ImportedBlockDecls.clear();
4484 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004485 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004486 // Must insert any 'const/volatile/static here. Since it has been
4487 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004488 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004489 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004490 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004491 if (GlobalVarDecl->getType().isConstQualified())
4492 SC += "const ";
4493 if (GlobalVarDecl->getType().isVolatileQualified())
4494 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004495 if (GlobalVarDecl->getType().isRestrictQualified())
4496 SC += "restrict ";
4497 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004498 }
4499
Steve Naroff54055232008-10-27 17:20:55 +00004500 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004501 InnerDeclRefsCount.clear();
4502 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004503 RewrittenBlockExprs.clear();
4504}
4505
4506void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4507 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004508 llvm::StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004509
Steve Naroff54055232008-10-27 17:20:55 +00004510 SynthesizeBlockLiterals(FunLocStart, FuncName);
4511}
4512
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004513static void BuildUniqueMethodName(std::string &Name,
4514 ObjCMethodDecl *MD) {
4515 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004516 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004517 Name += "__" + MD->getSelector().getAsString();
4518 // Convert colons to underscores.
4519 std::string::size_type loc = 0;
4520 while ((loc = Name.find(":", loc)) != std::string::npos)
4521 Name.replace(loc, 1, "_");
4522}
4523
Steve Naroff54055232008-10-27 17:20:55 +00004524void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004525 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4526 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004527 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004528 std::string FuncName;
4529 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004530 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004531}
4532
4533void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4534 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4535 CI != E; ++CI)
4536 if (*CI) {
4537 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4538 GetBlockDeclRefExprs(CBE->getBody());
4539 else
4540 GetBlockDeclRefExprs(*CI);
4541 }
4542 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004543 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004544 // FIXME: Handle enums.
4545 if (!isa<FunctionDecl>(CDRE->getDecl()))
4546 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004547 }
4548 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4549 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4550 BlockDeclRefExpr *BDRE =
4551 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4552 DRE->getLocation(), false);
4553 BlockDeclRefs.push_back(BDRE);
4554 }
4555
Steve Naroff54055232008-10-27 17:20:55 +00004556 return;
4557}
4558
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004559void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4560 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004561 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004562 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4563 CI != E; ++CI)
4564 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004565 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4566 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004567 GetInnerBlockDeclRefExprs(CBE->getBody(),
4568 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004569 InnerContexts);
4570 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004571 else
4572 GetInnerBlockDeclRefExprs(*CI,
4573 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004574 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004575
4576 }
4577 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004578 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004579 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004580 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004581 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004582 }
4583 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4584 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4585 if (Var->isFunctionOrMethodVarDecl())
4586 ImportedLocalExternalDecls.insert(Var);
4587 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004588
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004589 return;
4590}
4591
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004592/// convertFunctionTypeOfBlocks - This routine converts a function type
4593/// whose result type may be a block pointer or whose argument type(s)
4594/// might be block pointers to an equivalent funtion type replacing
4595/// all block pointers to function pointers.
4596QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4597 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4598 // FTP will be null for closures that don't take arguments.
4599 // Generate a funky cast.
4600 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004601 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004602 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004603
4604 if (FTP) {
4605 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4606 E = FTP->arg_type_end(); I && (I != E); ++I) {
4607 QualType t = *I;
4608 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004609 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004610 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004611 ArgTypes.push_back(t);
4612 }
4613 }
4614 QualType FuncType;
4615 // FIXME. Does this work if block takes no argument but has a return type
4616 // which is of block type?
4617 if (HasBlockType)
4618 FuncType = Context->getFunctionType(Res,
4619 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4620 false, false, 0, 0, FunctionType::ExtInfo());
4621 else FuncType = QualType(FT, 0);
4622 return FuncType;
4623}
4624
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004625Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004626 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004627 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004628
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004629 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004630 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004631 } else if (const BlockDeclRefExpr *CDRE =
4632 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004633 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004634 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004635 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004636 }
4637 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4638 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4639 }
4640 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4641 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4642 else if (const ConditionalOperator *CEXPR =
4643 dyn_cast<ConditionalOperator>(BlockExp)) {
4644 Expr *LHSExp = CEXPR->getLHS();
4645 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4646 Expr *RHSExp = CEXPR->getRHS();
4647 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4648 Expr *CONDExp = CEXPR->getCond();
4649 ConditionalOperator *CondExpr =
4650 new (Context) ConditionalOperator(CONDExp,
4651 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004652 SourceLocation(), cast<Expr>(RHSStmt),
4653 (Expr*)0,
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004654 Exp->getType());
4655 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004656 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4657 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004658 } else {
4659 assert(1 && "RewriteBlockClass: Bad type");
4660 }
4661 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004662 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004663 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004664 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004665 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004666
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004667 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004668 SourceLocation(),
4669 &Context->Idents.get("__block_impl"));
4670 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004671
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004672 // Generate a funky cast.
4673 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004674
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004675 // Push the block argument type.
4676 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004677 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004678 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004679 E = FTP->arg_type_end(); I && (I != E); ++I) {
4680 QualType t = *I;
4681 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004682 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004683 ArgTypes.push_back(t);
4684 }
Steve Naroff54055232008-10-27 17:20:55 +00004685 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004686 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004687 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004688 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4689 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00004690 FunctionType::ExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00004691
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004692 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004693
John McCall9d125032010-01-15 18:39:57 +00004694 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCall2de56d12010-08-25 11:45:40 +00004695 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00004696 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004697 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004698 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4699 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004700 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004701
Douglas Gregor44b43212008-12-11 16:49:14 +00004702 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004703 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004704 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004705 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4706 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004707
John McCall9d125032010-01-15 18:39:57 +00004708 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCall2de56d12010-08-25 11:45:40 +00004709 CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004710 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004711
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004712 llvm::SmallVector<Expr*, 8> BlkExprs;
4713 // Add the implicit argument.
4714 BlkExprs.push_back(BlkCast);
4715 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004716 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004717 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004718 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004719 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004720 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4721 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004722 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004723 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004724}
4725
Steve Naroff621edce2009-04-29 16:37:50 +00004726// We need to return the rewritten expression to handle cases where the
4727// BlockDeclRefExpr is embedded in another expression being rewritten.
4728// For example:
4729//
4730// int main() {
4731// __block Foo *f;
4732// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004733//
Steve Naroff621edce2009-04-29 16:37:50 +00004734// void (^myblock)() = ^() {
4735// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4736// i = 77;
4737// };
4738//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004739Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004740 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004741 // for each DeclRefExp where BYREFVAR is name of the variable.
4742 ValueDecl *VD;
4743 bool isArrow = true;
4744 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4745 VD = BDRE->getDecl();
4746 else {
4747 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4748 isArrow = false;
4749 }
4750
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004751 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4752 &Context->Idents.get("__forwarding"),
4753 Context->VoidPtrTy, 0,
4754 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004755 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4756 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004757 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004758
Daniel Dunbar4087f272010-08-17 22:39:59 +00004759 llvm::StringRef Name = VD->getName();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004760 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4761 &Context->Idents.get(Name),
4762 Context->VoidPtrTy, 0,
4763 /*BitWidth=*/0, /*Mutable=*/true);
4764 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004765 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004766
4767
4768
Steve Naroffdf8570d2009-02-02 17:19:26 +00004769 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004770 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4771 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004772 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004773 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004774}
4775
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004776// Rewrites the imported local variable V with external storage
4777// (static, extern, etc.) as *V
4778//
4779Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4780 ValueDecl *VD = DRE->getDecl();
4781 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4782 if (!ImportedLocalExternalDecls.count(Var))
4783 return DRE;
John McCall2de56d12010-08-25 11:45:40 +00004784 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref,
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004785 DRE->getType(), DRE->getLocation());
4786 // Need parens to enforce precedence.
4787 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4788 Exp);
4789 ReplaceStmt(DRE, PE);
4790 return PE;
4791}
4792
Steve Naroffb2f9e512008-11-03 23:29:32 +00004793void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4794 SourceLocation LocStart = CE->getLParenLoc();
4795 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004796
4797 // Need to avoid trying to rewrite synthesized casts.
4798 if (LocStart.isInvalid())
4799 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004800 // Need to avoid trying to rewrite casts contained in macros.
4801 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4802 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004803
Steve Naroff54055232008-10-27 17:20:55 +00004804 const char *startBuf = SM->getCharacterData(LocStart);
4805 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004806 QualType QT = CE->getType();
4807 const Type* TypePtr = QT->getAs<Type>();
4808 if (isa<TypeOfExprType>(TypePtr)) {
4809 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4810 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4811 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004812 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004813 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004814 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004815 return;
4816 }
Steve Naroff54055232008-10-27 17:20:55 +00004817 // advance the location to startArgList.
4818 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004819
Steve Naroff54055232008-10-27 17:20:55 +00004820 while (*argPtr++ && (argPtr < endBuf)) {
4821 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004822 case '^':
4823 // Replace the '^' with '*'.
4824 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004825 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004826 break;
Steve Naroff54055232008-10-27 17:20:55 +00004827 }
4828 }
4829 return;
4830}
4831
4832void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4833 SourceLocation DeclLoc = FD->getLocation();
4834 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004835
Steve Naroff54055232008-10-27 17:20:55 +00004836 // We have 1 or more arguments that have closure pointers.
4837 const char *startBuf = SM->getCharacterData(DeclLoc);
4838 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004839
Steve Naroff54055232008-10-27 17:20:55 +00004840 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004841
Steve Naroff54055232008-10-27 17:20:55 +00004842 parenCount++;
4843 // advance the location to startArgList.
4844 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4845 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Steve Naroff54055232008-10-27 17:20:55 +00004847 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004848
Steve Naroff54055232008-10-27 17:20:55 +00004849 while (*argPtr++ && parenCount) {
4850 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004851 case '^':
4852 // Replace the '^' with '*'.
4853 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004854 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004855 break;
4856 case '(':
4857 parenCount++;
4858 break;
4859 case ')':
4860 parenCount--;
4861 break;
Steve Naroff54055232008-10-27 17:20:55 +00004862 }
4863 }
4864 return;
4865}
4866
4867bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004868 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004869 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004870 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004871 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004872 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004873 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004874 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004875 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004876 }
4877 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004878 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004879 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004880 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004881 return true;
4882 }
4883 return false;
4884}
4885
Ted Kremenek8189cde2009-02-07 01:47:29 +00004886void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4887 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004888 const char *argPtr = strchr(Name, '(');
4889 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004890
Steve Naroff54055232008-10-27 17:20:55 +00004891 LParen = argPtr; // output the start.
4892 argPtr++; // skip past the left paren.
4893 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004894
Steve Naroff54055232008-10-27 17:20:55 +00004895 while (*argPtr && parenCount) {
4896 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004897 case '(': parenCount++; break;
4898 case ')': parenCount--; break;
4899 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004900 }
4901 if (parenCount) argPtr++;
4902 }
4903 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4904 RParen = argPtr; // output the end
4905}
4906
4907void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4908 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4909 RewriteBlockPointerFunctionArgs(FD);
4910 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004911 }
Steve Naroff54055232008-10-27 17:20:55 +00004912 // Handle Variables and Typedefs.
4913 SourceLocation DeclLoc = ND->getLocation();
4914 QualType DeclT;
4915 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4916 DeclT = VD->getType();
4917 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4918 DeclT = TDD->getUnderlyingType();
4919 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4920 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004921 else
Steve Naroff54055232008-10-27 17:20:55 +00004922 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004923
Steve Naroff54055232008-10-27 17:20:55 +00004924 const char *startBuf = SM->getCharacterData(DeclLoc);
4925 const char *endBuf = startBuf;
4926 // scan backward (from the decl location) for the end of the previous decl.
4927 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4928 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004929
Steve Naroff54055232008-10-27 17:20:55 +00004930 // *startBuf != '^' if we are dealing with a pointer to function that
4931 // may take block argument types (which will be handled below).
4932 if (*startBuf == '^') {
4933 // Replace the '^' with '*', computing a negative offset.
4934 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004935 ReplaceText(DeclLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004936 }
4937 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4938 // Replace the '^' with '*' for arguments.
4939 DeclLoc = ND->getLocation();
4940 startBuf = SM->getCharacterData(DeclLoc);
4941 const char *argListBegin, *argListEnd;
4942 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4943 while (argListBegin < argListEnd) {
4944 if (*argListBegin == '^') {
4945 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004946 ReplaceText(CaretLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004947 }
4948 argListBegin++;
4949 }
4950 }
4951 return;
4952}
4953
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004954
4955/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4956/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4957/// struct Block_byref_id_object *src) {
4958/// _Block_object_assign (&_dest->object, _src->object,
4959/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4960/// [|BLOCK_FIELD_IS_WEAK]) // object
4961/// _Block_object_assign(&_dest->object, _src->object,
4962/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4963/// [|BLOCK_FIELD_IS_WEAK]) // block
4964/// }
4965/// And:
4966/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4967/// _Block_object_dispose(_src->object,
4968/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4969/// [|BLOCK_FIELD_IS_WEAK]) // object
4970/// _Block_object_dispose(_src->object,
4971/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4972/// [|BLOCK_FIELD_IS_WEAK]) // block
4973/// }
4974
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004975std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4976 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004977 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004978 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004979 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004980 CopyDestroyCache.insert(flag);
4981 S = "static void __Block_byref_id_object_copy_";
4982 S += utostr(flag);
4983 S += "(void *dst, void *src) {\n";
4984
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004985 // offset into the object pointer is computed as:
4986 // void * + void* + int + int + void* + void *
4987 unsigned IntSize =
4988 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4989 unsigned VoidPtrSize =
4990 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4991
4992 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4993 S += " _Block_object_assign((char*)dst + ";
4994 S += utostr(offset);
4995 S += ", *(void * *) ((char*)src + ";
4996 S += utostr(offset);
4997 S += "), ";
4998 S += utostr(flag);
4999 S += ");\n}\n";
5000
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005001 S += "static void __Block_byref_id_object_dispose_";
5002 S += utostr(flag);
5003 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005004 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5005 S += utostr(offset);
5006 S += "), ";
5007 S += utostr(flag);
5008 S += ");\n}\n";
5009 return S;
5010}
5011
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005012/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5013/// the declaration into:
5014/// struct __Block_byref_ND {
5015/// void *__isa; // NULL for everything except __weak pointers
5016/// struct __Block_byref_ND *__forwarding;
5017/// int32_t __flags;
5018/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005019/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5020/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005021/// typex ND;
5022/// };
5023///
5024/// It then replaces declaration of ND variable with:
5025/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5026/// __size=sizeof(struct __Block_byref_ND),
5027/// ND=initializer-if-any};
5028///
5029///
5030void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005031 // Insert declaration for the function in which block literal is
5032 // used.
5033 if (CurFunctionDeclToDeclareForBlock)
5034 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005035 int flag = 0;
5036 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005037 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005038 if (DeclLoc.isInvalid())
5039 // If type location is missing, it is because of missing type (a warning).
5040 // Use variable's location which is good for this case.
5041 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005042 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005043 SourceLocation X = ND->getLocEnd();
5044 X = SM->getInstantiationLoc(X);
5045 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005046 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005047 std::string ByrefType;
5048 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005049 ByrefType += " {\n";
5050 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005051 RewriteByRefString(ByrefType, Name, ND);
5052 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005053 ByrefType += " int __flags;\n";
5054 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005055 // Add void *__Block_byref_id_object_copy;
5056 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005057 QualType Ty = ND->getType();
5058 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5059 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005060 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5061 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005062 }
5063
5064 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005065 ByrefType += " " + Name + ";\n";
5066 ByrefType += "};\n";
5067 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005068 SourceLocation FunLocStart;
5069 if (CurFunctionDef)
5070 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5071 else {
5072 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5073 FunLocStart = CurMethodDef->getLocStart();
5074 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005075 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005076 if (Ty.isObjCGCWeak()) {
5077 flag |= BLOCK_FIELD_IS_WEAK;
5078 isa = 1;
5079 }
5080
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005081 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005082 flag = BLOCK_BYREF_CALLER;
5083 QualType Ty = ND->getType();
5084 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5085 if (Ty->isBlockPointerType())
5086 flag |= BLOCK_FIELD_IS_BLOCK;
5087 else
5088 flag |= BLOCK_FIELD_IS_OBJECT;
5089 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005090 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005091 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005092 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005093
5094 // struct __Block_byref_ND ND =
5095 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5096 // initializer-if-any};
5097 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005098 unsigned flags = 0;
5099 if (HasCopyAndDispose)
5100 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005101 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005102 ByrefType.clear();
5103 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005104 std::string ForwardingCastType("(");
5105 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005106 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005107 ByrefType += " " + Name + " = {(void*)";
5108 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005109 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005110 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005111 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005112 ByrefType += "sizeof(";
5113 RewriteByRefString(ByrefType, Name, ND);
5114 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005115 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005116 ByrefType += ", __Block_byref_id_object_copy_";
5117 ByrefType += utostr(flag);
5118 ByrefType += ", __Block_byref_id_object_dispose_";
5119 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005120 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005121 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005122 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005123 }
5124 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005125 SourceLocation startLoc;
5126 Expr *E = ND->getInit();
5127 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5128 startLoc = ECE->getLParenLoc();
5129 else
5130 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005131 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005132 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005133 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005134 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005135 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005136 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005137 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005138 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005139 ByrefType += "sizeof(";
5140 RewriteByRefString(ByrefType, Name, ND);
5141 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005142 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005143 ByrefType += "__Block_byref_id_object_copy_";
5144 ByrefType += utostr(flag);
5145 ByrefType += ", __Block_byref_id_object_dispose_";
5146 ByrefType += utostr(flag);
5147 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005148 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005149 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005150
5151 // Complete the newly synthesized compound expression by inserting a right
5152 // curly brace before the end of the declaration.
5153 // FIXME: This approach avoids rewriting the initializer expression. It
5154 // also assumes there is only one declarator. For example, the following
5155 // isn't currently supported by this routine (in general):
5156 //
5157 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5158 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005159 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5160 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005161 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5162 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005163 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005164
Benjamin Kramerd999b372010-02-14 14:14:16 +00005165 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005166 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005167 return;
5168}
5169
Mike Stump1eb44332009-09-09 15:08:12 +00005170void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005171 // Add initializers for any closure decl refs.
5172 GetBlockDeclRefExprs(Exp->getBody());
5173 if (BlockDeclRefs.size()) {
5174 // Unique all "by copy" declarations.
5175 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005176 if (!BlockDeclRefs[i]->isByRef()) {
5177 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5178 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5179 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5180 }
5181 }
Steve Naroff54055232008-10-27 17:20:55 +00005182 // Unique all "by ref" declarations.
5183 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5184 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005185 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5186 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5187 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5188 }
Steve Naroff54055232008-10-27 17:20:55 +00005189 }
5190 // Find any imported blocks...they will need special attention.
5191 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005192 if (BlockDeclRefs[i]->isByRef() ||
5193 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005194 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005195 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005196 }
5197}
5198
Daniel Dunbar4087f272010-08-17 22:39:59 +00005199FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005200 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005201 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005202 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCalld931b082010-08-26 03:08:43 +00005203 ID, FType, 0, SC_Extern,
5204 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005205}
5206
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005207Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5208 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005209 Blocks.push_back(Exp);
5210
5211 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005212
5213 // Add inner imported variables now used in current block.
5214 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005215 if (!InnerBlockDeclRefs.empty()) {
5216 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5217 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5218 ValueDecl *VD = Exp->getDecl();
5219 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005220 // We need to save the copied-in variables in nested
5221 // blocks because it is needed at the end for some of the API generations.
5222 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005223 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5224 BlockDeclRefs.push_back(Exp);
5225 BlockByCopyDeclsPtrSet.insert(VD);
5226 BlockByCopyDecls.push_back(VD);
5227 }
5228 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5229 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5230 BlockDeclRefs.push_back(Exp);
5231 BlockByRefDeclsPtrSet.insert(VD);
5232 BlockByRefDecls.push_back(VD);
5233 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005234 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005235 // Find any imported blocks...they will need special attention.
5236 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5237 if (InnerBlockDeclRefs[i]->isByRef() ||
5238 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5239 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5240 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005241 }
5242 InnerDeclRefsCount.push_back(countOfInnerDecls);
5243
Steve Narofffa15fd92008-10-28 20:29:00 +00005244 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005245
Steve Narofffa15fd92008-10-28 20:29:00 +00005246 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005247 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005248 else if (CurMethodDef)
5249 BuildUniqueMethodName(FuncName, CurMethodDef);
5250 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005251 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005252
Steve Narofffa15fd92008-10-28 20:29:00 +00005253 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005254
Steve Narofffa15fd92008-10-28 20:29:00 +00005255 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5256 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005257
Steve Narofffa15fd92008-10-28 20:29:00 +00005258 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005259 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5260 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005261
5262 FunctionDecl *FD;
5263 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005264
Steve Narofffa15fd92008-10-28 20:29:00 +00005265 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005266 FD = SynthBlockInitFunctionDecl(Tag);
Ted Kremenek8189cde2009-02-07 01:47:29 +00005267 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005268
Steve Narofffa15fd92008-10-28 20:29:00 +00005269 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005270
Steve Narofffdc03722008-10-29 21:23:59 +00005271 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005272 FD = SynthBlockInitFunctionDecl(Func);
Ted Kremenek8189cde2009-02-07 01:47:29 +00005273 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5274 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005275 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCall2de56d12010-08-25 11:45:40 +00005276 CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005277 InitExprs.push_back(castExpr);
5278
Steve Naroff01aec112009-12-06 21:14:13 +00005279 // Initialize the block descriptor.
5280 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005281
Steve Naroff01aec112009-12-06 21:14:13 +00005282 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5283 &Context->Idents.get(DescData.c_str()),
5284 Context->VoidPtrTy, 0,
John McCalld931b082010-08-26 03:08:43 +00005285 SC_Static, SC_None);
Steve Naroff01aec112009-12-06 21:14:13 +00005286 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5287 new (Context) DeclRefExpr(NewVD,
5288 Context->VoidPtrTy, SourceLocation()),
John McCall2de56d12010-08-25 11:45:40 +00005289 UO_AddrOf,
Steve Naroff01aec112009-12-06 21:14:13 +00005290 Context->getPointerType(Context->VoidPtrTy),
5291 SourceLocation());
5292 InitExprs.push_back(DescRefExpr);
5293
Steve Narofffa15fd92008-10-28 20:29:00 +00005294 // Add initializers for any closure decl refs.
5295 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005296 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005297 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005298 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005299 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005300 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005301 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005302 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005303 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005304 if (HasLocalVariableExternalStorage(*I)) {
5305 QualType QT = (*I)->getType();
5306 QT = Context->getPointerType(QT);
John McCall2de56d12010-08-25 11:45:40 +00005307 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005308 SourceLocation());
5309 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005310 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005311 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005312 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005313 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCall2de56d12010-08-25 11:45:40 +00005314 CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005315 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005316 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005317 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005318 if (HasLocalVariableExternalStorage(*I)) {
5319 QualType QT = (*I)->getType();
5320 QT = Context->getPointerType(QT);
John McCall2de56d12010-08-25 11:45:40 +00005321 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005322 SourceLocation());
5323 }
5324
Steve Narofffa15fd92008-10-28 20:29:00 +00005325 }
Mike Stump1eb44332009-09-09 15:08:12 +00005326 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005327 }
5328 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005329 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005330 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005331 ValueDecl *ND = (*I);
5332 std::string Name(ND->getNameAsString());
5333 std::string RecName;
5334 RewriteByRefString(RecName, Name, ND);
5335 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5336 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005337 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005338 SourceLocation(), II);
5339 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5340 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5341
Daniel Dunbar4087f272010-08-17 22:39:59 +00005342 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005343 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005344 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005345 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00005346 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005347 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005348 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005349 }
5350 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005351 if (ImportedBlockDecls.size()) {
5352 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5353 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005354 unsigned IntSize =
5355 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005356 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5357 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005358 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005359 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005360 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5361 FType, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005362 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005363 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00005364 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005365 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00005366 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005367 BlockDeclRefs.clear();
5368 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005369 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005370 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005371 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005372 ImportedBlockDecls.clear();
5373 return NewRep;
5374}
5375
5376//===----------------------------------------------------------------------===//
5377// Function Body / Expression rewriting
5378//===----------------------------------------------------------------------===//
5379
Steve Naroffc77a6362008-12-04 16:24:46 +00005380// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5381// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5382// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5383// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5384// Since the rewriter isn't capable of rewriting rewritten code, it's important
5385// we get this right.
5386void RewriteObjC::CollectPropertySetters(Stmt *S) {
5387 // Perform a bottom up traversal of all children.
5388 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5389 CI != E; ++CI)
5390 if (*CI)
5391 CollectPropertySetters(*CI);
5392
5393 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5394 if (BinOp->isAssignmentOp()) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005395 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()) ||
5396 isa<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS()))
5397 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005398 }
5399 }
5400}
5401
Steve Narofffa15fd92008-10-28 20:29:00 +00005402Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005403 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005404 isa<DoStmt>(S) || isa<ForStmt>(S))
5405 Stmts.push_back(S);
5406 else if (isa<ObjCForCollectionStmt>(S)) {
5407 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005408 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005409 }
Mike Stump1eb44332009-09-09 15:08:12 +00005410
Steve Narofffa15fd92008-10-28 20:29:00 +00005411 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005412
Steve Narofffa15fd92008-10-28 20:29:00 +00005413 // Perform a bottom up rewrite of all children.
5414 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5415 CI != E; ++CI)
5416 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005417 Stmt *newStmt;
5418 Stmt *S = (*CI);
5419 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5420 Expr *OldBase = IvarRefExpr->getBase();
5421 bool replaced = false;
5422 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5423 if (replaced) {
5424 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5425 ReplaceStmt(OldBase, IRE->getBase());
5426 else
5427 ReplaceStmt(S, newStmt);
5428 }
5429 }
5430 else
5431 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005432 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005433 *CI = newStmt;
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005434 // If dealing with an assignment with LHS being a property reference
5435 // expression, the entire assignment tree is rewritten into a property
5436 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5437 // RHS again.
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005438 if (Expr *Exp = dyn_cast<Expr>(S))
5439 if (isa<ObjCPropertyRefExpr>(Exp) ||
5440 isa<ObjCImplicitSetterGetterRefExpr>(Exp)) {
5441 if (PropSetters[Exp]) {
5442 ++CI;
5443 continue;
5444 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005445 }
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005446 }
Mike Stump1eb44332009-09-09 15:08:12 +00005447
Steve Narofffa15fd92008-10-28 20:29:00 +00005448 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005449 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005450 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5451 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005452 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005453 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005454 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005455 // Rewrite the block body in place.
5456 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005457 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005458 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005459 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005460 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005461
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005462 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5463
Steve Narofffa15fd92008-10-28 20:29:00 +00005464 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005465 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005466 return blockTranscribed;
5467 }
5468 // Handle specific things.
5469 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5470 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005471
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005472 if (isa<ObjCPropertyRefExpr>(S) || isa<ObjCImplicitSetterGetterRefExpr>(S)) {
5473 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5474 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5475
5476 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005477 if (BinOp) {
5478 // Because the rewriter doesn't allow us to rewrite rewritten code,
5479 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005480 DisableReplaceStmt = true;
5481 // Save the source range. Even if we disable the replacement, the
5482 // rewritten node will have been inserted into the tree. If the synthesized
5483 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005484 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005485 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5486 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005487 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005488 // Need to rewrite the ivar access expression if need be.
5489 if (isa<ObjCIvarRefExpr>(newStmt)) {
5490 bool replaced = false;
5491 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5492 }
5493
Steve Naroffb619d952008-12-09 12:56:34 +00005494 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005495 //
5496 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5497 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5498 // to see the original expression). Consider this example:
5499 //
5500 // Foo *obj1, *obj2;
5501 //
5502 // obj1.i = [obj2 rrrr];
5503 //
5504 // 'BinOp' for the previous expression looks like:
5505 //
5506 // (BinaryOperator 0x231ccf0 'int' '='
5507 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5508 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5509 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5510 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5511 //
5512 // 'newStmt' represents the rewritten message expression. For example:
5513 //
5514 // (CallExpr 0x231d300 'id':'struct objc_object *'
5515 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5516 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5517 // (CStyleCastExpr 0x231d220 'void *'
5518 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5519 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005520 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005521 // can be used as the setter argument. ReplaceStmt() will still 'see'
5522 // the original RHS (since we haven't altered BinOp).
5523 //
Mike Stump1eb44332009-09-09 15:08:12 +00005524 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005525 // node. As a result, we now leak the original AST nodes.
5526 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005527 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005528 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005529 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005530 }
5531 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005532
Steve Narofffa15fd92008-10-28 20:29:00 +00005533 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5534 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005535
Steve Narofffa15fd92008-10-28 20:29:00 +00005536 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5537 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005538
Steve Narofffa15fd92008-10-28 20:29:00 +00005539 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005540#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005541 // Before we rewrite it, put the original message expression in a comment.
5542 SourceLocation startLoc = MessExpr->getLocStart();
5543 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005544
Steve Narofffa15fd92008-10-28 20:29:00 +00005545 const char *startBuf = SM->getCharacterData(startLoc);
5546 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005547
Steve Narofffa15fd92008-10-28 20:29:00 +00005548 std::string messString;
5549 messString += "// ";
5550 messString.append(startBuf, endBuf-startBuf+1);
5551 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005552
5553 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005554 // InsertText(clang::SourceLocation, char const*, unsigned int).
5555 // InsertText(startLoc, messString.c_str(), messString.size());
5556 // Tried this, but it didn't work either...
5557 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005558#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005559 return RewriteMessageExpr(MessExpr);
5560 }
Mike Stump1eb44332009-09-09 15:08:12 +00005561
Steve Narofffa15fd92008-10-28 20:29:00 +00005562 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5563 return RewriteObjCTryStmt(StmtTry);
5564
5565 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5566 return RewriteObjCSynchronizedStmt(StmtTry);
5567
5568 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5569 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005570
Steve Narofffa15fd92008-10-28 20:29:00 +00005571 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5572 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005573
5574 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005575 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005576 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005577 OrigStmtRange.getEnd());
5578 if (BreakStmt *StmtBreakStmt =
5579 dyn_cast<BreakStmt>(S))
5580 return RewriteBreakStmt(StmtBreakStmt);
5581 if (ContinueStmt *StmtContinueStmt =
5582 dyn_cast<ContinueStmt>(S))
5583 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005584
5585 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005586 // and cast exprs.
5587 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5588 // FIXME: What we're doing here is modifying the type-specifier that
5589 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005590 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005591 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5592 // the context of an ObjCForCollectionStmt. For example:
5593 // NSArray *someArray;
5594 // for (id <FooProtocol> index in someArray) ;
5595 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5596 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005597 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005598 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005599
Steve Narofffa15fd92008-10-28 20:29:00 +00005600 // Blocks rewrite rules.
5601 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5602 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005603 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005604 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005605 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005606 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005607 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005608 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005609 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005610 if (VD->hasAttr<BlocksAttr>()) {
5611 static unsigned uniqueByrefDeclCount = 0;
5612 assert(!BlockByRefDeclNo.count(ND) &&
5613 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5614 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005615 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005616 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005617 else
5618 RewriteTypeOfDecl(VD);
5619 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005620 }
5621 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005622 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005623 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005624 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005625 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5626 }
5627 }
5628 }
Mike Stump1eb44332009-09-09 15:08:12 +00005629
Steve Narofffa15fd92008-10-28 20:29:00 +00005630 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5631 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005632
5633 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005634 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5635 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005636 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5637 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005638 && "Statement stack mismatch");
5639 Stmts.pop_back();
5640 }
5641 // Handle blocks rewriting.
5642 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5643 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005644 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005645 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005646 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5647 ValueDecl *VD = DRE->getDecl();
5648 if (VD->hasAttr<BlocksAttr>())
5649 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005650 if (HasLocalVariableExternalStorage(VD))
5651 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005652 }
5653
Steve Narofffa15fd92008-10-28 20:29:00 +00005654 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005655 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005656 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005657 ReplaceStmt(S, BlockCall);
5658 return BlockCall;
5659 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005660 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005661 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005662 RewriteCastExpr(CE);
5663 }
5664#if 0
5665 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005666 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5667 ICE->getSubExpr(),
5668 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005669 // Get the new text.
5670 std::string SStr;
5671 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005672 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005673 const std::string &Str = Buf.str();
5674
5675 printf("CAST = %s\n", &Str[0]);
5676 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5677 delete S;
5678 return Replacement;
5679 }
5680#endif
5681 // Return this stmt unmodified.
5682 return S;
5683}
5684
Steve Naroff3d7e7862009-12-05 15:55:59 +00005685void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5686 for (RecordDecl::field_iterator i = RD->field_begin(),
5687 e = RD->field_end(); i != e; ++i) {
5688 FieldDecl *FD = *i;
5689 if (isTopLevelBlockPointerType(FD->getType()))
5690 RewriteBlockPointerDecl(FD);
5691 if (FD->getType()->isObjCQualifiedIdType() ||
5692 FD->getType()->isObjCQualifiedInterfaceType())
5693 RewriteObjCQualifiedInterfaceTypes(FD);
5694 }
5695}
5696
Steve Narofffa15fd92008-10-28 20:29:00 +00005697/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5698/// main file of the input.
5699void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5700 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005701 if (FD->isOverloadedOperator())
5702 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005703
Steve Narofffa15fd92008-10-28 20:29:00 +00005704 // Since function prototypes don't have ParmDecl's, we check the function
5705 // prototype. This enables us to rewrite function declarations and
5706 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005707 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005708
Sebastian Redld3a413d2009-04-26 20:35:05 +00005709 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005710 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005711 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005712 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005713 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005714 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005715 Body =
5716 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5717 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005718 CurrentBody = 0;
5719 if (PropParentMap) {
5720 delete PropParentMap;
5721 PropParentMap = 0;
5722 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005723 // This synthesizes and inserts the block "impl" struct, invoke function,
5724 // and any copy/dispose helper functions.
5725 InsertBlockLiteralsWithinFunction(FD);
5726 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005727 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005728 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005729 return;
5730 }
5731 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005732 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005733 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005734 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005735 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005736 Body =
5737 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5738 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005739 CurrentBody = 0;
5740 if (PropParentMap) {
5741 delete PropParentMap;
5742 PropParentMap = 0;
5743 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005744 InsertBlockLiteralsWithinMethod(MD);
5745 CurMethodDef = 0;
5746 }
5747 }
5748 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5749 ClassImplementation.push_back(CI);
5750 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5751 CategoryImplementation.push_back(CI);
5752 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5753 RewriteForwardClassDecl(CD);
5754 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5755 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005756 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005757 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005758 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005759 CheckFunctionPointerDecl(VD->getType(), VD);
5760 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005761 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005762 RewriteCastExpr(CE);
5763 }
5764 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005765 } else if (VD->getType()->isRecordType()) {
5766 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5767 if (RD->isDefinition())
5768 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005769 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005770 if (VD->getInit()) {
5771 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005772 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005773 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005774 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005775 CurrentBody = 0;
5776 if (PropParentMap) {
5777 delete PropParentMap;
5778 PropParentMap = 0;
5779 }
Mike Stump1eb44332009-09-09 15:08:12 +00005780 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005781 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005782 GlobalVarDecl = 0;
5783
5784 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005785 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005786 RewriteCastExpr(CE);
5787 }
5788 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005789 return;
5790 }
5791 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005792 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005793 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005794 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005795 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5796 return;
5797 }
5798 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005799 if (RD->isDefinition())
5800 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005801 return;
5802 }
5803 // Nothing yet.
5804}
5805
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005806void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005807 if (Diags.hasErrorOccurred())
5808 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005809
Steve Narofffa15fd92008-10-28 20:29:00 +00005810 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005811
Steve Naroff621edce2009-04-29 16:37:50 +00005812 // Here's a great place to add any extra declarations that may be needed.
5813 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005814 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005815 E = ProtocolExprDecls.end(); I != E; ++I)
5816 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5817
Benjamin Kramerd999b372010-02-14 14:14:16 +00005818 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005819 if (ClassImplementation.size() || CategoryImplementation.size())
5820 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005821
Steve Narofffa15fd92008-10-28 20:29:00 +00005822 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5823 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005824 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005825 Rewrite.getRewriteBufferFor(MainFileID)) {
5826 //printf("Changed:\n");
5827 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5828 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005829 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005830 }
Steve Narofface66252008-11-13 20:07:04 +00005831
Steve Naroff621edce2009-04-29 16:37:50 +00005832 if (ClassImplementation.size() || CategoryImplementation.size() ||
5833 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005834 // Rewrite Objective-c meta data*
5835 std::string ResultStr;
5836 SynthesizeMetaDataIntoBuffer(ResultStr);
5837 // Emit metadata.
5838 *OutFile << ResultStr;
5839 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005840 OutFile->flush();
5841}