blob: 23719cb345743adf8d957e0a7a47408e9d8b1950 [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
Ted Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner07506182007-11-30 22:53:43 +000019#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000020#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/SourceManager.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000024#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/OwningPtr.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000028#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000030
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Chris Lattner77cd2a02007-10-11 00:43:27 +000034namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000035 class RewriteObjC : public ASTConsumer {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000036 protected:
37
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000038 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000039 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000040 block, ... */
41 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
42 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
43 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000044 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000045 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000046 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000047 support routines */
48 BLOCK_BYREF_CURRENT_MAX = 256
49 };
50
51 enum {
52 BLOCK_NEEDS_FREE = (1 << 24),
53 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
54 BLOCK_HAS_CXX_OBJ = (1 << 26),
55 BLOCK_IS_GC = (1 << 27),
56 BLOCK_IS_GLOBAL = (1 << 28),
57 BLOCK_HAS_DESCRIPTOR = (1 << 29)
58 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000059 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000060
Chris Lattner2c64b7b2007-10-16 21:07:07 +000061 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000062 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000063 const LangOptions &LangOpts;
Chris Lattner01c57482007-10-17 22:35:30 +000064 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000065 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000066 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000067 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000068 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian58457172011-12-05 18:43:13 +000069 Stmt *CurrentBody;
70 ParentMap *PropParentMap; // created lazily.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000071 std::string InFileName;
72 raw_ostream* OutFile;
73 std::string Preamble;
74
75 TypeDecl *ProtocolTypeDecl;
76 VarDecl *GlobalVarDecl;
77 unsigned RewriteFailedDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000078 // ObjC string constant support.
79 unsigned NumObjCStringLiterals;
80 VarDecl *ConstantStringClassReference;
81 RecordDecl *NSStringRecord;
Fariborz Jahanian58457172011-12-05 18:43:13 +000082
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000083 // ObjC foreach break/continue generation support.
84 int BcLabelCount;
85
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000086 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000087 // Needed for super.
88 ObjCMethodDecl *CurMethodDef;
89 RecordDecl *SuperStructDecl;
90 RecordDecl *ConstantStringDecl;
91
92 FunctionDecl *MsgSendFunctionDecl;
93 FunctionDecl *MsgSendSuperFunctionDecl;
94 FunctionDecl *MsgSendStretFunctionDecl;
95 FunctionDecl *MsgSendSuperStretFunctionDecl;
96 FunctionDecl *MsgSendFpretFunctionDecl;
97 FunctionDecl *GetClassFunctionDecl;
98 FunctionDecl *GetMetaClassFunctionDecl;
99 FunctionDecl *GetSuperClassFunctionDecl;
100 FunctionDecl *SelGetUidFunctionDecl;
101 FunctionDecl *CFStringFunctionDecl;
102 FunctionDecl *SuperContructorFunctionDecl;
103 FunctionDecl *CurFunctionDef;
104 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000106 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner5f9e2722011-07-23 10:55:15 +0000107 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
108 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000109 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +0000110 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
112 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000113 SmallVector<Stmt *, 32> Stmts;
114 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +0000115 // Remember all the @protocol(<expr>) expressions.
116 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000117
118 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff54055232008-10-27 17:20:55 +0000119
120 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000121 SmallVector<BlockExpr *, 32> Blocks;
122 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000123 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000124
John McCallf4b88a42012-03-10 09:33:50 +0000125 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000126
Steve Naroff54055232008-10-27 17:20:55 +0000127 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000129 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000130 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000131 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000132 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000133 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000134 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
135
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
137
Steve Naroff4c3580e2008-12-04 23:50:32 +0000138 // This maps an original source AST to it's rewritten form. This allows
139 // us to avoid rewriting the same node twice (which is very uncommon).
140 // This is needed to support some of the exotic property rewriting.
141 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000142
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000143 // Needed for header files being rewritten
144 bool IsHeader;
145 bool SilenceRewriteMacroWarning;
146 bool objc_impl_method;
147
Steve Naroffb619d952008-12-09 12:56:34 +0000148 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000149 class DisableReplaceStmtScope {
150 RewriteObjC &R;
151 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000152
John McCall4b9c2d22011-11-06 09:01:30 +0000153 public:
154 DisableReplaceStmtScope(RewriteObjC &R)
155 : R(R), SavedValue(R.DisableReplaceStmt) {
156 R.DisableReplaceStmt = true;
157 }
158 ~DisableReplaceStmtScope() {
159 R.DisableReplaceStmt = SavedValue;
160 }
161 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000162 void InitializeCommon(ASTContext &context);
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Chris Lattner77cd2a02007-10-11 00:43:27 +0000164 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000165
Chris Lattnerf04da132007-10-24 17:06:59 +0000166 // Top Level Driver code.
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000167 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000168 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000169 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
170 if (!Class->isThisDeclarationADefinition()) {
171 RewriteForwardClassDecl(D);
172 break;
173 }
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000174 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000175
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000176 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
177 if (!Proto->isThisDeclarationADefinition()) {
178 RewriteForwardProtocolDecl(D);
179 break;
180 }
181 }
182
Chris Lattner682bf922009-03-29 16:50:03 +0000183 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000184 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000185 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000186 }
187 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000188 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000189 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000190 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000191 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000192
193 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000195 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000197 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000198 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Steve Naroff4c3580e2008-12-04 23:50:32 +0000200 if (ReplacingStmt)
201 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000202
Steve Naroffb619d952008-12-09 12:56:34 +0000203 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000204 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000205
Steve Naroff4c3580e2008-12-04 23:50:32 +0000206 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000207 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000208 ReplacedNodes[Old] = New;
209 return;
210 }
211 if (SilenceRewriteMacroWarning)
212 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000213 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
214 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000215 }
Steve Naroffb619d952008-12-09 12:56:34 +0000216
217 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000218 if (DisableReplaceStmt)
219 return;
220
Nick Lewycky7e749242010-10-31 21:07:24 +0000221 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000222 int Size = Rewrite.getRangeSize(SrcRange);
223 if (Size == -1) {
224 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
225 << Old->getSourceRange();
226 return;
227 }
228 // Get the new text.
229 std::string SStr;
230 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000231 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000232 const std::string &Str = S.str();
233
234 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000235 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000236 ReplacedNodes[Old] = New;
237 return;
238 }
239 if (SilenceRewriteMacroWarning)
240 return;
241 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
242 << Old->getSourceRange();
243 }
244
Chris Lattner5f9e2722011-07-23 10:55:15 +0000245 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000246 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000247 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000248 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000249 SilenceRewriteMacroWarning)
250 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000252 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
253 }
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattneraadaf782008-01-31 19:51:04 +0000255 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000256 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000257 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000258 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000259 SilenceRewriteMacroWarning)
260 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Chris Lattneraadaf782008-01-31 19:51:04 +0000262 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
263 }
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Chris Lattnerf04da132007-10-24 17:06:59 +0000265 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000266 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000267 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000268 void RewriteForwardClassDecl(DeclGroupRef D);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000269 void RewriteForwardClassDecl(const SmallVector<Decl *, 8> &DG);
Douglas Gregor375bb142011-12-27 22:43:10 +0000270 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000271 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000272 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000273 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
274 ObjCImplementationDecl *IMD,
275 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000276 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000277 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000278 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
279 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000280 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
281 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000282 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000283 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000284 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
285 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000286 void RewriteForwardProtocolDecl(DeclGroupRef D);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000287 void RewriteForwardProtocolDecl(const SmallVector<Decl *, 8> &DG);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000288 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000289 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000290 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000291 void RewriteBlockPointerType(std::string& Str, QualType Type);
292 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000293 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000294 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000295 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000296 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000297
Chris Lattnerf04da132007-10-24 17:06:59 +0000298 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000299 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000300 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000301 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
302 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000303 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000304 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000305 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000306 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000307 void RewriteTryReturnStmts(Stmt *S);
308 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000309 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000310 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000311 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000312 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
313 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000314 Stmt *RewriteBreakStmt(BreakStmt *S);
315 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000316 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000317
Steve Naroff54055232008-10-27 17:20:55 +0000318 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000319 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000320
Mike Stump1eb44332009-09-09 15:08:12 +0000321 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000322 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000323 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000324 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000325 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000326 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000327
328 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
329 std::string &Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000330
331 virtual void Initialize(ASTContext &context) = 0;
332
333 // Metadata Rewriting.
334 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
335 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
336 StringRef prefix,
337 StringRef ClassName,
338 std::string &Result) = 0;
339 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
340 std::string &Result) = 0;
341 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
342 StringRef prefix,
343 StringRef ClassName,
344 std::string &Result) = 0;
345 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
346 std::string &Result) = 0;
347
348 // Rewriting ivar access
349 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
350 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
351 std::string &Result) = 0;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000352
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000353 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian58457172011-12-05 18:43:13 +0000354 // rewriting routines on the new ASTs.
355 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
356 Expr **args, unsigned nargs,
357 SourceLocation StartLoc=SourceLocation(),
358 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +0000359 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
360 QualType msgSendType,
361 QualType returnType,
362 SmallVectorImpl<QualType> &ArgTypes,
363 SmallVectorImpl<Expr*> &MsgExprs,
364 ObjCMethodDecl *Method);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000365 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
366 SourceLocation StartLoc=SourceLocation(),
367 SourceLocation EndLoc=SourceLocation());
368
369 void SynthCountByEnumWithState(std::string &buf);
370 void SynthMsgSendFunctionDecl();
371 void SynthMsgSendSuperFunctionDecl();
372 void SynthMsgSendStretFunctionDecl();
373 void SynthMsgSendFpretFunctionDecl();
374 void SynthMsgSendSuperStretFunctionDecl();
375 void SynthGetClassFunctionDecl();
376 void SynthGetMetaClassFunctionDecl();
377 void SynthGetSuperClassFunctionDecl();
378 void SynthSelGetUidFunctionDecl();
379 void SynthSuperContructorFunctionDecl();
380
381 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000382 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000383 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000384 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000385 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000386 std::string SynthesizeBlockImpl(BlockExpr *CE,
387 std::string Tag, std::string Desc);
388 std::string SynthesizeBlockDescriptor(std::string DescTag,
389 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000390 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000391 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000392 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000393 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000394 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000395 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
396 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000397 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Fariborz Jahanian58457172011-12-05 18:43:13 +0000399 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000400 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000401 void WarnAboutReturnGotoStmts(Stmt *S);
402 void HasReturnStmts(Stmt *S, bool &hasReturns);
403 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
404 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
405 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
406
407 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000408 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000409 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000410 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000411 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000412 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Steve Naroff54055232008-10-27 17:20:55 +0000414 // We avoid calling Type::isBlockPointerType(), since it operates on the
415 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000416 bool isTopLevelBlockPointerType(QualType T) {
417 return isa<BlockPointerType>(T);
418 }
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000420 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
421 /// to a function pointer type and upon success, returns true; false
422 /// otherwise.
423 bool convertBlockPointerToFunctionPointer(QualType &T) {
424 if (isTopLevelBlockPointerType(T)) {
425 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
426 T = Context->getPointerType(BPT->getPointeeType());
427 return true;
428 }
429 return false;
430 }
431
Fariborz Jahanian58457172011-12-05 18:43:13 +0000432 bool needToScanForQualifiers(QualType T);
433 QualType getSuperStructType();
434 QualType getConstantStringStructType();
435 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
436 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
437
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000438 void convertToUnqualifiedObjCType(QualType &T) {
439 if (T->isObjCQualifiedIdType())
440 T = Context->getObjCIdType();
441 else if (T->isObjCQualifiedClassType())
442 T = Context->getObjCClassType();
443 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000444 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
445 if (const ObjCObjectPointerType * OBJPT =
446 T->getAsObjCInterfacePointerType()) {
447 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
448 T = QualType(IFaceT, 0);
449 T = Context->getPointerType(T);
450 }
451 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000452 }
453
Steve Naroff54055232008-10-27 17:20:55 +0000454 // FIXME: This predicate seems like it would be useful to add to ASTContext.
455 bool isObjCType(QualType T) {
456 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
457 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Steve Naroff54055232008-10-27 17:20:55 +0000459 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Steve Naroff54055232008-10-27 17:20:55 +0000461 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
462 OCT == Context->getCanonicalType(Context->getObjCClassType()))
463 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Ted Kremenek6217b802009-07-29 21:53:49 +0000465 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000466 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000467 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000468 return true;
469 }
470 return false;
471 }
472 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000473 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000474 void GetExtentOfArgList(const char *Name, const char *&LParen,
475 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000476
Steve Naroff621edce2009-04-29 16:37:50 +0000477 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000478 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000479 if (From[i] == '"')
480 To += "\\\"";
481 else
482 To += From[i];
483 }
484 }
John McCalle23cf432010-12-14 08:05:40 +0000485
486 QualType getSimpleFunctionType(QualType result,
487 const QualType *args,
488 unsigned numArgs,
489 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000490 if (result == Context->getObjCInstanceType())
491 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000492 FunctionProtoType::ExtProtoInfo fpi;
493 fpi.Variadic = variadic;
494 return Context->getFunctionType(result, args, numArgs, fpi);
495 }
John McCall9d125032010-01-15 18:39:57 +0000496
Fariborz Jahanian58457172011-12-05 18:43:13 +0000497 // Helper function: create a CStyleCastExpr with trivial type source info.
498 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
499 CastKind Kind, Expr *E) {
500 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
501 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
502 SourceLocation(), SourceLocation());
503 }
504 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000505
506 class RewriteObjCFragileABI : public RewriteObjC {
507 public:
508
509 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
510 DiagnosticsEngine &D, const LangOptions &LOpts,
511 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
512 D, LOpts,
513 silenceMacroWarn) {}
514
515 ~RewriteObjCFragileABI() {}
516 virtual void Initialize(ASTContext &context);
517
518 // Rewriting metadata
519 template<typename MethodIterator>
520 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521 MethodIterator MethodEnd,
522 bool IsInstanceMethod,
523 StringRef prefix,
524 StringRef ClassName,
525 std::string &Result);
526 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
527 StringRef prefix,
528 StringRef ClassName,
529 std::string &Result);
530 virtual void RewriteObjCProtocolListMetaData(
531 const ObjCList<ObjCProtocolDecl> &Prots,
532 StringRef prefix, StringRef ClassName, std::string &Result);
533 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
534 std::string &Result);
535 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
536 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
537 std::string &Result);
538
539 // Rewriting ivar
540 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
541 std::string &Result);
542 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
543 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000544}
545
Mike Stump1eb44332009-09-09 15:08:12 +0000546void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
547 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000548 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000549 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000550 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000551 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000552 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000553 // All the args are checked/rewritten. Don't call twice!
554 RewriteBlockPointerDecl(D);
555 break;
556 }
557 }
558}
559
560void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000561 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000562 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000563 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000564}
565
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000566static bool IsHeaderFile(const std::string &Filename) {
567 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000569 if (DotPos == std::string::npos) {
570 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000571 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000572 }
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000574 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
575 // C header: .h
576 // C++ header: .hh or .H;
577 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000578}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000579
Chris Lattner5f9e2722011-07-23 10:55:15 +0000580RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000581 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000582 bool silenceMacroWarn)
583 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
584 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000585 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000586 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000587 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000588 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
589 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000590 "rewriter doesn't support user-specified control flow semantics "
591 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000592}
593
Eli Friedmanbce831b2009-05-18 22:29:17 +0000594ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000595 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000596 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000597 const LangOptions &LOpts,
598 bool SilenceRewriteMacroWarning) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000599 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000600}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000601
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000602void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000603 Context = &context;
604 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000605 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000606 MsgSendFunctionDecl = 0;
607 MsgSendSuperFunctionDecl = 0;
608 MsgSendStretFunctionDecl = 0;
609 MsgSendSuperStretFunctionDecl = 0;
610 MsgSendFpretFunctionDecl = 0;
611 GetClassFunctionDecl = 0;
612 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000613 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000614 SelGetUidFunctionDecl = 0;
615 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000616 ConstantStringClassReference = 0;
617 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000618 CurMethodDef = 0;
619 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000620 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000621 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000622 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000623 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000624 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000625 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000626 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000627 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000628 PropParentMap = 0;
629 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000630 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000631 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000633 // Get the ID and start/end of the main file.
634 MainFileID = SM->getMainFileID();
635 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
636 MainFileStart = MainBuf->getBufferStart();
637 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000638
David Blaikie4e4d0842012-03-11 07:00:24 +0000639 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000640}
641
Chris Lattnerf04da132007-10-24 17:06:59 +0000642//===----------------------------------------------------------------------===//
643// Top Level Driver Code
644//===----------------------------------------------------------------------===//
645
Chris Lattner682bf922009-03-29 16:50:03 +0000646void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000647 if (Diags.hasErrorOccurred())
648 return;
649
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000650 // Two cases: either the decl could be in the main file, or it could be in a
651 // #included file. If the former, rewrite it now. If the later, check to see
652 // if we rewrote the #include/#import.
653 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000654 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000655
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000656 // If this is for a builtin, ignore it.
657 if (Loc.isInvalid()) return;
658
Steve Naroffebf2b562007-10-23 23:50:29 +0000659 // Look for built-in declarations that we need to refer during the rewrite.
660 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000661 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000662 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000663 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000664 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000665 ConstantStringClassReference = FVD;
666 return;
667 }
Douglas Gregor7723fec2011-12-15 20:29:51 +0000668 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
669 if (ID->isThisDeclarationADefinition())
670 RewriteInterfaceDecl(ID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000671 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000672 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000673 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000674 if (PD->isThisDeclarationADefinition())
675 RewriteProtocolDecl(PD);
Douglas Gregord0434102009-01-09 00:49:46 +0000676 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
677 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000678 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
679 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000680 DI != DIEnd; ) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000681 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
682 if (!IFace->isThisDeclarationADefinition()) {
683 SmallVector<Decl *, 8> DG;
684 SourceLocation StartLoc = IFace->getLocStart();
685 do {
686 if (isa<ObjCInterfaceDecl>(*DI) &&
687 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
688 StartLoc == (*DI)->getLocStart())
689 DG.push_back(*DI);
690 else
691 break;
692
Douglas Gregor7723fec2011-12-15 20:29:51 +0000693 ++DI;
Douglas Gregor375bb142011-12-27 22:43:10 +0000694 } while (DI != DIEnd);
695 RewriteForwardClassDecl(DG);
696 continue;
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000697 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000698 }
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000699
700 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
701 if (!Proto->isThisDeclarationADefinition()) {
702 SmallVector<Decl *, 8> DG;
703 SourceLocation StartLoc = Proto->getLocStart();
704 do {
705 if (isa<ObjCProtocolDecl>(*DI) &&
706 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
707 StartLoc == (*DI)->getLocStart())
708 DG.push_back(*DI);
709 else
710 break;
711
712 ++DI;
713 } while (DI != DIEnd);
714 RewriteForwardProtocolDecl(DG);
715 continue;
716 }
717 }
718
Chris Lattner682bf922009-03-29 16:50:03 +0000719 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000720 ++DI;
721 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000722 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000723 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000724 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000725 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000726}
727
Chris Lattnerf04da132007-10-24 17:06:59 +0000728//===----------------------------------------------------------------------===//
729// Syntactic (non-AST) Rewriting Code
730//===----------------------------------------------------------------------===//
731
Steve Naroffb29b4272008-04-14 22:03:09 +0000732void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000733 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000734 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000735 const char *MainBufStart = MainBuf.begin();
736 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000737 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000739 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000740 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
741 if (*BufPtr == '#') {
742 if (++BufPtr == MainBufEnd)
743 return;
744 while (*BufPtr == ' ' || *BufPtr == '\t')
745 if (++BufPtr == MainBufEnd)
746 return;
747 if (!strncmp(BufPtr, "import", ImportLen)) {
748 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000749 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000750 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000751 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000752 BufPtr += ImportLen;
753 }
754 }
755 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000756}
757
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000758static std::string getIvarAccessString(ObjCIvarDecl *OID) {
759 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000760 std::string S;
761 S = "((struct ";
762 S += ClassDecl->getIdentifier()->getName();
763 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000764 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765 return S;
766}
767
Steve Naroffa0876e82008-12-02 17:36:43 +0000768void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
769 ObjCImplementationDecl *IMD,
770 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000771 static bool objcGetPropertyDefined = false;
772 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000773 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000774 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000775 const char *startBuf = SM->getCharacterData(startLoc);
776 assert((*startBuf == '@') && "bogus @synthesize location");
777 const char *semiBuf = strchr(startBuf, ';');
778 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000779 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000780 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000781
782 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
783 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Steve Naroffeb0646c2008-12-02 15:48:25 +0000785 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000786 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000787 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000789 if (!OID)
790 return;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000791 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000792 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000793 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
794 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000795 ObjCPropertyDecl::OBJC_PR_copy));
796 std::string Getr;
797 if (GenGetProperty && !objcGetPropertyDefined) {
798 objcGetPropertyDefined = true;
799 // FIXME. Is this attribute correct in all cases?
800 Getr = "\nextern \"C\" __declspec(dllimport) "
801 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000802 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000803 RewriteObjCMethodDecl(OID->getContainingInterface(),
804 PD->getGetterMethodDecl(), Getr);
805 Getr += "{ ";
806 // Synthesize an explicit cast to gain access to the ivar.
807 // See objc-act.c:objc_synthesize_new_getter() for details.
808 if (GenGetProperty) {
809 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
810 Getr += "typedef ";
811 const FunctionType *FPRetType = 0;
812 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
813 FPRetType);
814 Getr += " _TYPE";
815 if (FPRetType) {
816 Getr += ")"; // close the precedence "scope" for "*".
817
818 // Now, emit the argument types (if any).
819 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
820 Getr += "(";
821 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
822 if (i) Getr += ", ";
823 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000824 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000825 Getr += ParamStr;
826 }
827 if (FT->isVariadic()) {
828 if (FT->getNumArgs()) Getr += ", ";
829 Getr += "...";
830 }
831 Getr += ")";
832 } else
833 Getr += "()";
834 }
835 Getr += ";\n";
836 Getr += "return (_TYPE)";
837 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000838 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000839 Getr += ", 1)";
840 }
841 else
842 Getr += "return " + getIvarAccessString(OID);
843 Getr += "; }";
844 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000845 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000846
847 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000848 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Steve Naroffeb0646c2008-12-02 15:48:25 +0000850 // Generate the 'setter' function.
851 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000852 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000853 ObjCPropertyDecl::OBJC_PR_copy);
854 if (GenSetProperty && !objcSetPropertyDefined) {
855 objcSetPropertyDefined = true;
856 // FIXME. Is this attribute correct in all cases?
857 Setr = "\nextern \"C\" __declspec(dllimport) "
858 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
859 }
860
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000861 RewriteObjCMethodDecl(OID->getContainingInterface(),
862 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000863 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000864 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000865 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000866 if (GenSetProperty) {
867 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000868 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000869 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000870 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000871 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +0000872 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000873 Setr += "0, ";
874 else
875 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +0000876 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000877 Setr += "1)";
878 else
879 Setr += "0)";
880 }
881 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000882 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000883 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000884 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000885 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000886 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000887}
Chris Lattner8a12c272007-10-11 18:38:32 +0000888
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000889static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
890 std::string &typedefString) {
891 typedefString += "#ifndef _REWRITER_typedef_";
892 typedefString += ForwardDecl->getNameAsString();
893 typedefString += "\n";
894 typedefString += "#define _REWRITER_typedef_";
895 typedefString += ForwardDecl->getNameAsString();
896 typedefString += "\n";
897 typedefString += "typedef struct objc_object ";
898 typedefString += ForwardDecl->getNameAsString();
899 typedefString += ";\n#endif\n";
900}
901
Douglas Gregor375bb142011-12-27 22:43:10 +0000902void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000903 const std::string &typedefString) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000904 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000905 const char *startBuf = SM->getCharacterData(startLoc);
906 const char *semiPtr = strchr(startBuf, ';');
907 // Replace the @class with typedefs corresponding to the classes.
908 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
909}
910
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000911void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000912 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000913 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000914 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000915 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000916 // Translate to typedef's that forward reference structs with the same name
917 // as the class. As a convenience, we include the original declaration
918 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000919 typedefString += "// @class ";
920 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000921 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000922 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000923 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000924 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000925 DeclGroupRef::iterator I = D.begin();
Douglas Gregor375bb142011-12-27 22:43:10 +0000926 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000927}
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000929void RewriteObjC::RewriteForwardClassDecl(const SmallVector<Decl *, 8> &D) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000930 std::string typedefString;
931 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000932 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000933 if (i == 0) {
934 typedefString += "// @class ";
935 typedefString += ForwardDecl->getNameAsString();
936 typedefString += ";\n";
937 }
938 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
939 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000940 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000941}
942
Steve Naroffb29b4272008-04-14 22:03:09 +0000943void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000944 // When method is a synthesized one, such as a getter/setter there is
945 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000946 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000947 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000948 SourceLocation LocStart = Method->getLocStart();
949 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chandler Carruth64211622011-07-25 21:09:52 +0000951 if (SM->getExpansionLineNumber(LocEnd) >
952 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000953 InsertText(LocStart, "#if 0\n");
954 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000955 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000956 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000957 }
958}
959
Mike Stump1eb44332009-09-09 15:08:12 +0000960void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000961 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Benjamin Kramerd999b372010-02-14 14:14:16 +0000963 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000964 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000965}
966
Steve Naroffb29b4272008-04-14 22:03:09 +0000967void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000968 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Steve Naroff423cb562007-10-30 13:30:57 +0000970 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000971 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000973 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
974 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000975 RewriteProperty(*I);
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000976
Mike Stump1eb44332009-09-09 15:08:12 +0000977 for (ObjCCategoryDecl::instmeth_iterator
978 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000979 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000980 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000981 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000982 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000983 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000984 RewriteMethodDeclaration(*I);
985
Steve Naroff423cb562007-10-30 13:30:57 +0000986 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000987 ReplaceText(CatDecl->getAtEndRange().getBegin(),
988 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000989}
990
Steve Naroffb29b4272008-04-14 22:03:09 +0000991void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000992 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregor61cc2962012-01-02 02:00:30 +0000993 assert(PDecl->isThisDeclarationADefinition());
994
Steve Naroff752d6ef2007-10-30 16:42:30 +0000995 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000996 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000997
998 for (ObjCProtocolDecl::instmeth_iterator
999 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001000 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001001 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001002 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001003 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001004 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001005 RewriteMethodDeclaration(*I);
1006
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001007 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1008 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001009 RewriteProperty(*I);
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001010
Steve Naroff752d6ef2007-10-30 16:42:30 +00001011 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001012 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001013 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001014
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001015 // Must comment out @optional/@required
1016 const char *startBuf = SM->getCharacterData(LocStart);
1017 const char *endBuf = SM->getCharacterData(LocEnd);
1018 for (const char *p = startBuf; p < endBuf; p++) {
1019 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001020 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001021 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001023 }
1024 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001025 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001026 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001028 }
1029 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001030}
1031
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001032void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1033 SourceLocation LocStart = (*D.begin())->getLocStart();
1034 if (LocStart.isInvalid())
1035 llvm_unreachable("Invalid SourceLocation");
1036 // FIXME: handle forward protocol that are declared across multiple lines.
1037 ReplaceText(LocStart, 0, "// ");
1038}
1039
1040void
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001041RewriteObjC::RewriteForwardProtocolDecl(const SmallVector<Decl *, 8> &DG) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001042 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001043 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001044 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001045 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001046 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001047}
1048
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001049void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1050 const FunctionType *&FPRetType) {
1051 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001052 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001053 else if (T->isFunctionPointerType() ||
1054 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001055 // needs special handling, since pointer-to-functions have special
1056 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001057 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001058 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001059 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001060 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001061 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001062 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001063 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001064 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001065 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001066 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001067 }
1068 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001069 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001070}
1071
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001072void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1073 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001074 std::string &ResultStr) {
1075 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1076 const FunctionType *FPRetType = 0;
1077 ResultStr += "\nstatic ";
1078 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001079 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001081 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001082 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001084 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001085 NameStr += "_I_";
1086 else
1087 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001089 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001090 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001091
1092 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001093 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001094 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001095 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001096 }
Mike Stump1eb44332009-09-09 15:08:12 +00001097 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001098 {
1099 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100 int len = selString.size();
1101 for (int i = 0; i < len; i++)
1102 if (selString[i] == ':')
1103 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001104 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001105 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001106 // Remember this name for metadata emission
1107 MethodInternalNames[OMD] = NameStr;
1108 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001110 // Rewrite arguments
1111 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001113 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001114 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001115 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001116 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001117 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001118 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001119 ResultStr += "struct ";
1120 }
1121 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001122 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001123 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001124 }
1125 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001126 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001127 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001129 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001130 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001131 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001133 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001134 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1135 E = OMD->param_end(); PI != E; ++PI) {
1136 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001137 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001138 if (PDecl->getType()->isObjCQualifiedIdType()) {
1139 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001140 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001141 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001142 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001143 QualType QT = PDecl->getType();
1144 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001145 (void)convertBlockPointerToFunctionPointer(QT);
1146 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001147 ResultStr += Name;
1148 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001149 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001150 if (OMD->isVariadic())
1151 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001152 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Steve Naroff76e429d2008-07-16 14:40:40 +00001154 if (FPRetType) {
1155 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Steve Naroff76e429d2008-07-16 14:40:40 +00001157 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001158 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001159 ResultStr += "(";
1160 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1161 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001162 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001163 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001164 ResultStr += ParamStr;
1165 }
1166 if (FT->isVariadic()) {
1167 if (FT->getNumArgs()) ResultStr += ", ";
1168 ResultStr += "...";
1169 }
1170 ResultStr += ")";
1171 } else {
1172 ResultStr += "()";
1173 }
1174 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001175}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001176void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001177 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1178 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001180 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001182 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001183 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1184 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001185 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001186 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001187 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001188 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001189 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001190 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001191
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001192 const char *startBuf = SM->getCharacterData(LocStart);
1193 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001194 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001195 }
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001197 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001198 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1199 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001200 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001201 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001202 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001203 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001204 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001205 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001207 const char *startBuf = SM->getCharacterData(LocStart);
1208 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001209 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001210 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001211 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001212 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001213 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001214 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001215 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001216 }
1217
Benjamin Kramerd999b372010-02-14 14:14:16 +00001218 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001219}
1220
Steve Naroffb29b4272008-04-14 22:03:09 +00001221void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001222 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001223 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001224 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001225 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001226 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001227 ResultStr += "\n";
1228 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001229 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001230 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001231 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001232 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001233 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001234 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001235 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001236 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001237 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001238
1239 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001240 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001241 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001242 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001243 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001244 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001245 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001246 for (ObjCInterfaceDecl::classmeth_iterator
1247 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001248 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001249 RewriteMethodDeclaration(*I);
1250
Steve Naroff2feac5e2007-10-30 03:43:13 +00001251 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001252 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1253 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001254}
1255
John McCall4b9c2d22011-11-06 09:01:30 +00001256Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1257 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001258
John McCall4b9c2d22011-11-06 09:01:30 +00001259 // We just magically know some things about the structure of this
1260 // expression.
1261 ObjCMessageExpr *OldMsg =
1262 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1263 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001264
John McCall4b9c2d22011-11-06 09:01:30 +00001265 // Because the rewriter doesn't allow us to rewrite rewritten code,
1266 // we need to suppress rewriting the sub-statements.
1267 Expr *Base, *RHS;
1268 {
1269 DisableReplaceStmtScope S(*this);
1270
1271 // Rebuild the base expression if we have one.
1272 Base = 0;
1273 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1274 Base = OldMsg->getInstanceReceiver();
1275 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1276 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1277 }
1278
1279 // Rebuild the RHS.
1280 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1281 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1282 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1283 }
1284
1285 // TODO: avoid this copy.
1286 SmallVector<SourceLocation, 1> SelLocs;
1287 OldMsg->getSelectorLocs(SelLocs);
1288
Chad Rosier0774ba72012-01-06 20:05:14 +00001289 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001290 switch (OldMsg->getReceiverKind()) {
1291 case ObjCMessageExpr::Class:
1292 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1293 OldMsg->getValueKind(),
1294 OldMsg->getLeftLoc(),
1295 OldMsg->getClassReceiverTypeInfo(),
1296 OldMsg->getSelector(),
1297 SelLocs,
1298 OldMsg->getMethodDecl(),
1299 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001300 OldMsg->getRightLoc(),
1301 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001302 break;
1303
1304 case ObjCMessageExpr::Instance:
1305 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1306 OldMsg->getValueKind(),
1307 OldMsg->getLeftLoc(),
1308 Base,
1309 OldMsg->getSelector(),
1310 SelLocs,
1311 OldMsg->getMethodDecl(),
1312 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001313 OldMsg->getRightLoc(),
1314 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001315 break;
1316
1317 case ObjCMessageExpr::SuperClass:
1318 case ObjCMessageExpr::SuperInstance:
1319 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1320 OldMsg->getValueKind(),
1321 OldMsg->getLeftLoc(),
1322 OldMsg->getSuperLoc(),
1323 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1324 OldMsg->getSuperType(),
1325 OldMsg->getSelector(),
1326 SelLocs,
1327 OldMsg->getMethodDecl(),
1328 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001329 OldMsg->getRightLoc(),
1330 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001331 break;
1332 }
1333
1334 Stmt *Replacement = SynthMessageExpr(NewMsg);
1335 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1336 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001337}
1338
John McCall4b9c2d22011-11-06 09:01:30 +00001339Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1340 SourceRange OldRange = PseudoOp->getSourceRange();
1341
1342 // We just magically know some things about the structure of this
1343 // expression.
1344 ObjCMessageExpr *OldMsg =
1345 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1346
1347 // Because the rewriter doesn't allow us to rewrite rewritten code,
1348 // we need to suppress rewriting the sub-statements.
1349 Expr *Base = 0;
1350 {
1351 DisableReplaceStmtScope S(*this);
1352
1353 // Rebuild the base expression if we have one.
1354 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1355 Base = OldMsg->getInstanceReceiver();
1356 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1357 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001358 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001359 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001360
John McCall4b9c2d22011-11-06 09:01:30 +00001361 // Intentionally empty.
1362 SmallVector<SourceLocation, 1> SelLocs;
1363 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001364
Chad Rosier0774ba72012-01-06 20:05:14 +00001365 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001366 switch (OldMsg->getReceiverKind()) {
1367 case ObjCMessageExpr::Class:
1368 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1369 OldMsg->getValueKind(),
1370 OldMsg->getLeftLoc(),
1371 OldMsg->getClassReceiverTypeInfo(),
1372 OldMsg->getSelector(),
1373 SelLocs,
1374 OldMsg->getMethodDecl(),
1375 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001376 OldMsg->getRightLoc(),
1377 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001378 break;
1379
1380 case ObjCMessageExpr::Instance:
1381 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1382 OldMsg->getValueKind(),
1383 OldMsg->getLeftLoc(),
1384 Base,
1385 OldMsg->getSelector(),
1386 SelLocs,
1387 OldMsg->getMethodDecl(),
1388 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001389 OldMsg->getRightLoc(),
1390 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001391 break;
1392
1393 case ObjCMessageExpr::SuperClass:
1394 case ObjCMessageExpr::SuperInstance:
1395 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1396 OldMsg->getValueKind(),
1397 OldMsg->getLeftLoc(),
1398 OldMsg->getSuperLoc(),
1399 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1400 OldMsg->getSuperType(),
1401 OldMsg->getSelector(),
1402 SelLocs,
1403 OldMsg->getMethodDecl(),
1404 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001405 OldMsg->getRightLoc(),
1406 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001407 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001408 }
John McCall4b9c2d22011-11-06 09:01:30 +00001409
1410 Stmt *Replacement = SynthMessageExpr(NewMsg);
1411 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1412 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001413}
1414
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001415/// SynthCountByEnumWithState - To print:
1416/// ((unsigned int (*)
1417/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001418/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001419/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001420/// "countByEnumeratingWithState:objects:count:"),
1421/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001422/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001423///
Steve Naroffb29b4272008-04-14 22:03:09 +00001424void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001425 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1426 "id *, unsigned int))(void *)objc_msgSend)";
1427 buf += "\n\t\t";
1428 buf += "((id)l_collection,\n\t\t";
1429 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1430 buf += "\n\t\t";
1431 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001432 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001433}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001434
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001435/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1436/// statement to exit to its outer synthesized loop.
1437///
Steve Naroffb29b4272008-04-14 22:03:09 +00001438Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001439 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1440 return S;
1441 // replace break with goto __break_label
1442 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001444 SourceLocation startLoc = S->getLocStart();
1445 buf = "goto __break_label_";
1446 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001447 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001448
1449 return 0;
1450}
1451
1452/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1453/// statement to continue with its inner synthesized loop.
1454///
Steve Naroffb29b4272008-04-14 22:03:09 +00001455Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001456 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1457 return S;
1458 // replace continue with goto __continue_label
1459 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001461 SourceLocation startLoc = S->getLocStart();
1462 buf = "goto __continue_label_";
1463 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001464 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001466 return 0;
1467}
1468
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001469/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001470/// It rewrites:
1471/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001473/// Into:
1474/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001475/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001476/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001477/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001478/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001479/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001480/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001481/// if (limit) {
1482/// unsigned long startMutations = *enumState.mutationsPtr;
1483/// do {
1484/// unsigned long counter = 0;
1485/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001486/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001487/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001488/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001489/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001490/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001491/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001492/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001493/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001494/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001495/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001496/// }
1497/// else
1498/// elem = nil;
1499/// }
1500///
Steve Naroffb29b4272008-04-14 22:03:09 +00001501Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001502 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001503 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001504 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001505 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001506 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001507 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001509 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001510 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001511 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001512 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001513 std::string buf;
1514 buf = "\n{\n\t";
1515 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1516 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001517 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001518 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001519 if (ElementType->isObjCQualifiedIdType() ||
1520 ElementType->isObjCQualifiedInterfaceType())
1521 // Simply use 'id' for all qualified types.
1522 elementTypeAsString = "id";
1523 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001524 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001525 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001526 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001527 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001528 buf += elementName;
1529 buf += ";\n\t";
1530 }
Chris Lattner06767512008-04-08 05:52:18 +00001531 else {
1532 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001533 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001534 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1535 if (VD->getType()->isObjCQualifiedIdType() ||
1536 VD->getType()->isObjCQualifiedInterfaceType())
1537 // Simply use 'id' for all qualified types.
1538 elementTypeAsString = "id";
1539 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001540 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001541 }
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001543 // struct __objcFastEnumerationState enumState = { 0 };
1544 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001545 // id __rw_items[16];
1546 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001547 // id l_collection = (id)
1548 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001549 // Find start location of 'collection' the hard way!
1550 const char *startCollectionBuf = startBuf;
1551 startCollectionBuf += 3; // skip 'for'
1552 startCollectionBuf = strchr(startCollectionBuf, '(');
1553 startCollectionBuf++; // skip '('
1554 // find 'in' and skip it.
1555 while (*startCollectionBuf != ' ' ||
1556 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1557 (*(startCollectionBuf+3) != ' ' &&
1558 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1559 startCollectionBuf++;
1560 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001561
1562 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001563 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001564 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001565 SourceLocation rightParenLoc = S->getRParenLoc();
1566 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001567 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001568 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001570 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001571 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001572 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001573 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001574 // ((unsigned int (*)
1575 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001576 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001577 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001578 // "countByEnumeratingWithState:objects:count:"),
1579 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001580 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001581 buf += "unsigned long limit =\n\t\t";
1582 SynthCountByEnumWithState(buf);
1583 buf += ";\n\t";
1584 /// if (limit) {
1585 /// unsigned long startMutations = *enumState.mutationsPtr;
1586 /// do {
1587 /// unsigned long counter = 0;
1588 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001589 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001590 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001591 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001592 buf += "if (limit) {\n\t";
1593 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1594 buf += "do {\n\t\t";
1595 buf += "unsigned long counter = 0;\n\t\t";
1596 buf += "do {\n\t\t\t";
1597 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1598 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1599 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001600 buf += " = (";
1601 buf += elementTypeAsString;
1602 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001603 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001604 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001606 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001607 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001608 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001609 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001610 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001611 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001612 /// }
1613 /// else
1614 /// elem = nil;
1615 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001616 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001617 buf = ";\n\t";
1618 buf += "__continue_label_";
1619 buf += utostr(ObjCBcLabelNo.back());
1620 buf += ": ;";
1621 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001622 buf += "} while (counter < limit);\n\t";
1623 buf += "} while (limit = ";
1624 SynthCountByEnumWithState(buf);
1625 buf += ");\n\t";
1626 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001627 buf += " = ((";
1628 buf += elementTypeAsString;
1629 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001630 buf += "__break_label_";
1631 buf += utostr(ObjCBcLabelNo.back());
1632 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001633 buf += "}\n\t";
1634 buf += "else\n\t\t";
1635 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001636 buf += " = ((";
1637 buf += elementTypeAsString;
1638 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001639 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001641 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001642 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001643 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001644 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001645 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001646 } else {
1647 /* Need to treat single statements specially. For example:
1648 *
1649 * for (A *a in b) if (stuff()) break;
1650 * for (A *a in b) xxxyy;
1651 *
1652 * The following code simply scans ahead to the semi to find the actual end.
1653 */
1654 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1655 const char *semiBuf = strchr(stmtBuf, ';');
1656 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001657 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001658 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001659 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001660 Stmts.pop_back();
1661 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001662 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001663}
1664
Mike Stump1eb44332009-09-09 15:08:12 +00001665/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001666/// This routine rewrites @synchronized(expr) stmt;
1667/// into:
1668/// objc_sync_enter(expr);
1669/// @try stmt @finally { objc_sync_exit(expr); }
1670///
Steve Naroffb29b4272008-04-14 22:03:09 +00001671Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001672 // Get the start location and compute the semi location.
1673 SourceLocation startLoc = S->getLocStart();
1674 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001675
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001676 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001677
1678 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001679 buf = "objc_sync_enter((id)";
1680 const char *lparenBuf = startBuf;
1681 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001682 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001683 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1684 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001685 // been rewritten! (which implies the SourceLocation's are invalid).
1686 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001687 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001688 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001689 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001690 buf = ");\n";
1691 // declare a new scope with two variables, _stack and _rethrow.
1692 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1693 buf += "int buf[18/*32-bit i386*/];\n";
1694 buf += "char *pointers[4];} _stack;\n";
1695 buf += "id volatile _rethrow = 0;\n";
1696 buf += "objc_exception_try_enter(&_stack);\n";
1697 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001698 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001699 startLoc = S->getSynchBody()->getLocEnd();
1700 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Steve Naroffc7089f12008-08-19 13:04:19 +00001702 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001703 SourceLocation lastCurlyLoc = startLoc;
1704 buf = "}\nelse {\n";
1705 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001706 buf += "}\n";
1707 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001708 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001709
1710 std::string syncBuf;
1711 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001712
1713 Expr *syncExpr = S->getSynchExpr();
1714 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1715 ? CK_BitCast :
1716 syncExpr->getType()->isBlockPointerType()
1717 ? CK_BlockPointerToObjCPointerCast
1718 : CK_CPointerToObjCPointerCast;
1719 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1720 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001721 std::string syncExprBufS;
1722 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00001723 syncExpr->printPretty(syncExprBuf, 0, PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001724 syncBuf += syncExprBuf.str();
1725 syncBuf += ");";
1726
1727 buf += syncBuf;
1728 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001729 buf += "}\n";
1730 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Benjamin Kramerd999b372010-02-14 14:14:16 +00001732 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001733
1734 bool hasReturns = false;
1735 HasReturnStmts(S->getSynchBody(), hasReturns);
1736 if (hasReturns)
1737 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1738
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001739 return 0;
1740}
1741
Steve Naroffb85e77a2009-12-05 21:43:12 +00001742void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1743{
Steve Naroff8c565152008-12-05 17:03:39 +00001744 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001745 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001746 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001747 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001748
Steve Naroffb85e77a2009-12-05 21:43:12 +00001749 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001750 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001751 TryFinallyContainsReturnDiag);
1752 }
1753 return;
1754}
1755
Steve Naroffb85e77a2009-12-05 21:43:12 +00001756void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1757{
1758 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001759 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001760 if (*CI)
1761 HasReturnStmts(*CI, hasReturns);
1762
1763 if (isa<ReturnStmt>(S))
1764 hasReturns = true;
1765 return;
1766}
1767
1768void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1769 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001770 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001771 if (*CI) {
1772 RewriteTryReturnStmts(*CI);
1773 }
1774 if (isa<ReturnStmt>(S)) {
1775 SourceLocation startLoc = S->getLocStart();
1776 const char *startBuf = SM->getCharacterData(startLoc);
1777
1778 const char *semiBuf = strchr(startBuf, ';');
1779 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001780 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001781
1782 std::string buf;
1783 buf = "{ objc_exception_try_exit(&_stack); return";
1784
Benjamin Kramerd999b372010-02-14 14:14:16 +00001785 ReplaceText(startLoc, 6, buf);
1786 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001787 }
1788 return;
1789}
1790
1791void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1792 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001793 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001794 if (*CI) {
1795 RewriteSyncReturnStmts(*CI, syncExitBuf);
1796 }
1797 if (isa<ReturnStmt>(S)) {
1798 SourceLocation startLoc = S->getLocStart();
1799 const char *startBuf = SM->getCharacterData(startLoc);
1800
1801 const char *semiBuf = strchr(startBuf, ';');
1802 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001803 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001804
1805 std::string buf;
1806 buf = "{ objc_exception_try_exit(&_stack);";
1807 buf += syncExitBuf;
1808 buf += " return";
1809
Benjamin Kramerd999b372010-02-14 14:14:16 +00001810 ReplaceText(startLoc, 6, buf);
1811 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001812 }
1813 return;
1814}
1815
Steve Naroffb29b4272008-04-14 22:03:09 +00001816Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001817 // Get the start location and compute the semi location.
1818 SourceLocation startLoc = S->getLocStart();
1819 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Steve Naroff75730982007-11-07 04:08:17 +00001821 assert((*startBuf == '@') && "bogus @try location");
1822
1823 std::string buf;
1824 // declare a new scope with two variables, _stack and _rethrow.
1825 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1826 buf += "int buf[18/*32-bit i386*/];\n";
1827 buf += "char *pointers[4];} _stack;\n";
1828 buf += "id volatile _rethrow = 0;\n";
1829 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001830 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001831
Benjamin Kramerd999b372010-02-14 14:14:16 +00001832 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Steve Naroff75730982007-11-07 04:08:17 +00001834 startLoc = S->getTryBody()->getLocEnd();
1835 startBuf = SM->getCharacterData(startLoc);
1836
1837 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Steve Naroff75730982007-11-07 04:08:17 +00001839 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001840 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001841 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001842 buf = " /* @catch begin */ else {\n";
1843 buf += " id _caught = objc_exception_extract(&_stack);\n";
1844 buf += " objc_exception_try_enter (&_stack);\n";
1845 buf += " if (_setjmp(_stack.buf))\n";
1846 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1847 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Benjamin Kramerd999b372010-02-14 14:14:16 +00001849 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001850 } else { /* no catch list */
1851 buf = "}\nelse {\n";
1852 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1853 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001854 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001855 }
Steve Naroff75730982007-11-07 04:08:17 +00001856 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001857 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1858 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001859 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001860
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001861 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001862 buf = "if ("; // we are generating code for the first catch clause
1863 else
1864 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001865 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001866 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Steve Naroff75730982007-11-07 04:08:17 +00001868 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Steve Naroff75730982007-11-07 04:08:17 +00001870 const char *lParenLoc = strchr(startBuf, '(');
1871
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001872 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001873 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001874 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001875 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1876 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001877 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001878 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001879 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Steve Naroffe12e6922008-02-01 20:02:07 +00001881 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001882 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001883 } else if (catchDecl) {
1884 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001885 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001886 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001887 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001888 } else if (const ObjCObjectPointerType *Ptr =
1889 t->getAs<ObjCObjectPointerType>()) {
1890 // Should be a pointer to a class.
1891 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1892 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001893 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001894 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001895 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001896 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001897 }
1898 }
1899 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001900 lastCatchBody = Catch->getCatchBody();
1901 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001902 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1903 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1904 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1905 assert((*rParenBuf == ')') && "bogus @catch paren location");
1906 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Mike Stump1eb44332009-09-09 15:08:12 +00001908 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001909 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001910 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001911 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001912 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001913 }
Steve Naroff75730982007-11-07 04:08:17 +00001914 }
1915 // Complete the catch list...
1916 if (lastCatchBody) {
1917 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001918 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1919 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Steve Naroff378f47a2008-09-11 15:29:03 +00001921 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001922 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001923 buf = "} /* last catch end */\n";
1924 buf += "else {\n";
1925 buf += " _rethrow = _caught;\n";
1926 buf += " objc_exception_try_exit(&_stack);\n";
1927 buf += "} } /* @catch end */\n";
1928 if (!S->getFinallyStmt())
1929 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001930 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Steve Naroff75730982007-11-07 04:08:17 +00001932 // Set lastCurlyLoc
1933 lastCurlyLoc = lastCatchBody->getLocEnd();
1934 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001935 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001936 startLoc = finalStmt->getLocStart();
1937 startBuf = SM->getCharacterData(startLoc);
1938 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Benjamin Kramerd999b372010-02-14 14:14:16 +00001940 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Steve Naroff75730982007-11-07 04:08:17 +00001942 Stmt *body = finalStmt->getFinallyBody();
1943 SourceLocation startLoc = body->getLocStart();
1944 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001945 assert(*SM->getCharacterData(startLoc) == '{' &&
1946 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001947 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001948 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001950 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001951 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001952 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001953 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Steve Naroff75730982007-11-07 04:08:17 +00001955 // Set lastCurlyLoc
1956 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Steve Naroff8c565152008-12-05 17:03:39 +00001958 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001959 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001960 } else { /* no finally clause - make sure we synthesize an implicit one */
1961 buf = "{ /* implicit finally clause */\n";
1962 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1963 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1964 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001965 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001966
1967 // Now check for any return/continue/go statements within the @try.
1968 // The implicit finally clause won't called if the @try contains any
1969 // jump statements.
1970 bool hasReturns = false;
1971 HasReturnStmts(S->getTryBody(), hasReturns);
1972 if (hasReturns)
1973 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001974 }
1975 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001976 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001977 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001978 return 0;
1979}
1980
Mike Stump1eb44332009-09-09 15:08:12 +00001981// This can't be done with ReplaceStmt(S, ThrowExpr), since
1982// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001983// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001984Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001985 // Get the start location and compute the semi location.
1986 SourceLocation startLoc = S->getLocStart();
1987 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Steve Naroff2bd03922007-11-07 15:32:26 +00001989 assert((*startBuf == '@') && "bogus @throw location");
1990
1991 std::string buf;
1992 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001993 if (S->getThrowExpr())
1994 buf = "objc_exception_throw(";
1995 else // add an implicit argument
1996 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001998 // handle "@ throw" correctly.
1999 const char *wBuf = strchr(startBuf, 'w');
2000 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002001 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Steve Naroff2bd03922007-11-07 15:32:26 +00002003 const char *semiBuf = strchr(startBuf, ';');
2004 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002005 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002006 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002007 return 0;
2008}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002009
Steve Naroffb29b4272008-04-14 22:03:09 +00002010Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002011 // Create a new string expression.
2012 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002013 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002014 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002015 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002016 StringLiteral::Ascii, false,
2017 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002018 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Chris Lattner07506182007-11-30 22:53:43 +00002020 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002021 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002022 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002023}
2024
Steve Naroffb29b4272008-04-14 22:03:09 +00002025Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002026 if (!SelGetUidFunctionDecl)
2027 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002028 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2029 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002030 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002031 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002032 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002033 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002034 StringLiteral::Ascii, false,
2035 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002036 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2037 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002038 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002039 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002040 return SelExp;
2041}
2042
Steve Naroffb29b4272008-04-14 22:03:09 +00002043CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002044 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2045 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002046 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002047 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Steve Naroffebf2b562007-10-23 23:50:29 +00002049 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002050 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2051 VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Steve Naroffebf2b562007-10-23 23:50:29 +00002053 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002054 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002055 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002056 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002057 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002058
John McCall183700f2009-09-21 23:43:11 +00002059 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002061 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002062 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
John McCallf89e55a2010-11-18 06:31:45 +00002063 FT->getCallResultType(*Context),
2064 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002065 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002066}
2067
Steve Naroffd5255f52007-11-01 13:24:47 +00002068static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2069 const char *&startRef, const char *&endRef) {
2070 while (startBuf < endBuf) {
2071 if (*startBuf == '<')
2072 startRef = startBuf; // mark the start.
2073 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002074 if (startRef && *startRef == '<') {
2075 endRef = startBuf; // mark the end.
2076 return true;
2077 }
2078 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002079 }
2080 startBuf++;
2081 }
2082 return false;
2083}
2084
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002085static void scanToNextArgument(const char *&argRef) {
2086 int angle = 0;
2087 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2088 if (*argRef == '<')
2089 angle++;
2090 else if (*argRef == '>')
2091 angle--;
2092 argRef++;
2093 }
2094 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2095}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002096
Steve Naroffb29b4272008-04-14 22:03:09 +00002097bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002098 if (T->isObjCQualifiedIdType())
2099 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002100 if (const PointerType *PT = T->getAs<PointerType>()) {
2101 if (PT->getPointeeType()->isObjCQualifiedIdType())
2102 return true;
2103 }
2104 if (T->isObjCObjectPointerType()) {
2105 T = T->getPointeeType();
2106 return T->isObjCQualifiedInterfaceType();
2107 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002108 if (T->isArrayType()) {
2109 QualType ElemTy = Context->getBaseElementType(T);
2110 return needToScanForQualifiers(ElemTy);
2111 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002112 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002113}
2114
Steve Naroff4f95b752008-07-29 18:15:38 +00002115void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2116 QualType Type = E->getType();
2117 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002118 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Steve Naroffcda658e2008-11-19 21:15:47 +00002120 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2121 Loc = ECE->getLParenLoc();
2122 EndLoc = ECE->getRParenLoc();
2123 } else {
2124 Loc = E->getLocStart();
2125 EndLoc = E->getLocEnd();
2126 }
2127 // This will defend against trying to rewrite synthesized expressions.
2128 if (Loc.isInvalid() || EndLoc.isInvalid())
2129 return;
2130
Steve Naroff4f95b752008-07-29 18:15:38 +00002131 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002132 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002133 const char *startRef = 0, *endRef = 0;
2134 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2135 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002136 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2137 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002138 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002139 InsertText(LessLoc, "/*");
2140 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002141 }
2142 }
2143}
2144
Steve Naroffb29b4272008-04-14 22:03:09 +00002145void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002146 SourceLocation Loc;
2147 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002148 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002149 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2150 Loc = VD->getLocation();
2151 Type = VD->getType();
2152 }
2153 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2154 Loc = FD->getLocation();
2155 // Check for ObjC 'id' and class types that have been adorned with protocol
2156 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002157 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002158 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002159 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002160 if (!proto)
2161 return;
2162 Type = proto->getResultType();
2163 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002164 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2165 Loc = FD->getLocation();
2166 Type = FD->getType();
2167 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002168 else
2169 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002171 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002172 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002173
Steve Naroffd5255f52007-11-01 13:24:47 +00002174 const char *endBuf = SM->getCharacterData(Loc);
2175 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002176 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002177 startBuf--; // scan backward (from the decl location) for return type.
2178 const char *startRef = 0, *endRef = 0;
2179 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2180 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002181 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2182 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002183 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002184 InsertText(LessLoc, "/*");
2185 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002186 }
2187 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002188 if (!proto)
2189 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002190 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002191 const char *startBuf = SM->getCharacterData(Loc);
2192 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002193 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2194 if (needToScanForQualifiers(proto->getArgType(i))) {
2195 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002196
Steve Naroffd5255f52007-11-01 13:24:47 +00002197 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002198 // scan forward (from the decl location) for argument types.
2199 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002200 const char *startRef = 0, *endRef = 0;
2201 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2202 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002203 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002204 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002205 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002206 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002207 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002208 InsertText(LessLoc, "/*");
2209 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002210 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002211 startBuf = ++endBuf;
2212 }
2213 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002214 // If the function name is derived from a macro expansion, then the
2215 // argument buffer will not follow the name. Need to speak with Chris.
2216 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002217 startBuf++; // scan forward (from the decl location) for argument types.
2218 startBuf++;
2219 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002220 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002221}
2222
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002223void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2224 QualType QT = ND->getType();
2225 const Type* TypePtr = QT->getAs<Type>();
2226 if (!isa<TypeOfExprType>(TypePtr))
2227 return;
2228 while (isa<TypeOfExprType>(TypePtr)) {
2229 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2230 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2231 TypePtr = QT->getAs<Type>();
2232 }
2233 // FIXME. This will not work for multiple declarators; as in:
2234 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002235 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002236 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2237 const char *startBuf = SM->getCharacterData(DeclLoc);
2238 if (ND->getInit()) {
2239 std::string Name(ND->getNameAsString());
2240 TypeAsString += " " + Name + " = ";
2241 Expr *E = ND->getInit();
2242 SourceLocation startLoc;
2243 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2244 startLoc = ECE->getLParenLoc();
2245 else
2246 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002247 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002248 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002249 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002250 }
2251 else {
2252 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002253 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002254 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002255 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002256 }
2257}
2258
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002259// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002260void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002261 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002262 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002263 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002264 QualType getFuncType =
2265 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002266 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002267 SourceLocation(),
2268 SourceLocation(),
2269 SelGetUidIdent, getFuncType, 0,
2270 SC_Extern, SC_None);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002271}
2272
Steve Naroffb29b4272008-04-14 22:03:09 +00002273void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002274 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002275 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002276 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002277 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002278 return;
2279 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002280 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002281}
2282
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002283void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002284 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002285 const char *argPtr = TypeString.c_str();
2286 if (!strchr(argPtr, '^')) {
2287 Str += TypeString;
2288 return;
2289 }
2290 while (*argPtr) {
2291 Str += (*argPtr == '^' ? '*' : *argPtr);
2292 argPtr++;
2293 }
2294}
2295
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002296// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002297void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2298 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002299 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002300 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002301 const char *argPtr = TypeString.c_str();
2302 int paren = 0;
2303 while (*argPtr) {
2304 switch (*argPtr) {
2305 case '(':
2306 Str += *argPtr;
2307 paren++;
2308 break;
2309 case ')':
2310 Str += *argPtr;
2311 paren--;
2312 break;
2313 case '^':
2314 Str += '*';
2315 if (paren == 1)
2316 Str += VD->getNameAsString();
2317 break;
2318 default:
2319 Str += *argPtr;
2320 break;
2321 }
2322 argPtr++;
2323 }
2324}
2325
2326
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002327void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2328 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2329 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2330 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2331 if (!proto)
2332 return;
2333 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002334 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002335 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002336 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002337 FdStr += "(";
2338 unsigned numArgs = proto->getNumArgs();
2339 for (unsigned i = 0; i < numArgs; i++) {
2340 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002341 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002342 if (i+1 < numArgs)
2343 FdStr += ", ";
2344 }
2345 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002346 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002347 CurFunctionDeclToDeclareForBlock = 0;
2348}
2349
Steve Naroffc0a123c2008-03-11 17:37:02 +00002350// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002351void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002352 if (SuperContructorFunctionDecl)
2353 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002354 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002355 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002356 QualType argT = Context->getObjCIdType();
2357 assert(!argT.isNull() && "Can't find 'id' type");
2358 ArgTys.push_back(argT);
2359 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002360 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2361 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002362 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002363 SourceLocation(),
2364 SourceLocation(),
2365 msgSendIdent, msgSendType,
2366 0, SC_Extern, SC_None);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002367}
2368
Steve Naroff09b266e2007-10-30 23:14:51 +00002369// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002370void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002371 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002372 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002373 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002374 assert(!argT.isNull() && "Can't find 'id' type");
2375 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002376 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002377 assert(!argT.isNull() && "Can't find 'SEL' type");
2378 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002379 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2380 &ArgTys[0], ArgTys.size(),
2381 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002382 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002383 SourceLocation(),
2384 SourceLocation(),
2385 msgSendIdent, msgSendType, 0,
2386 SC_Extern, SC_None);
Steve Naroff09b266e2007-10-30 23:14:51 +00002387}
2388
Steve Naroff874e2322007-11-15 10:28:18 +00002389// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002390void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002391 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002392 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002393 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002394 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002395 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002396 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2397 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2398 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002399 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002400 assert(!argT.isNull() && "Can't find 'SEL' type");
2401 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002402 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2403 &ArgTys[0], ArgTys.size(),
2404 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002405 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002406 SourceLocation(),
2407 SourceLocation(),
2408 msgSendIdent, msgSendType, 0,
2409 SC_Extern, SC_None);
Steve Naroff874e2322007-11-15 10:28:18 +00002410}
2411
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002412// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002413void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002414 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002415 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002416 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002417 assert(!argT.isNull() && "Can't find 'id' type");
2418 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002419 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002420 assert(!argT.isNull() && "Can't find 'SEL' type");
2421 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002422 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002423 &ArgTys[0], ArgTys.size(),
2424 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002425 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002426 SourceLocation(),
2427 SourceLocation(),
2428 msgSendIdent, msgSendType, 0,
2429 SC_Extern, SC_None);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002430}
2431
Mike Stump1eb44332009-09-09 15:08:12 +00002432// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002433// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002434void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002435 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002436 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002437 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002438 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002439 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002440 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002441 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2442 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2443 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002444 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002445 assert(!argT.isNull() && "Can't find 'SEL' type");
2446 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002447 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002448 &ArgTys[0], ArgTys.size(),
2449 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002450 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002451 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002452 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002453 msgSendIdent,
2454 msgSendType, 0,
2455 SC_Extern, SC_None);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002456}
2457
Steve Naroff1284db82008-05-08 22:02:18 +00002458// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002459void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002460 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002461 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002462 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002463 assert(!argT.isNull() && "Can't find 'id' type");
2464 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002465 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002466 assert(!argT.isNull() && "Can't find 'SEL' type");
2467 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002468 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2469 &ArgTys[0], ArgTys.size(),
2470 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002471 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002472 SourceLocation(),
2473 SourceLocation(),
2474 msgSendIdent, msgSendType, 0,
2475 SC_Extern, SC_None);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002476}
2477
Steve Naroff09b266e2007-10-30 23:14:51 +00002478// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002479void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002480 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002481 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002482 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002483 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2484 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002485 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002486 SourceLocation(),
2487 SourceLocation(),
2488 getClassIdent, getClassType, 0,
2489 SC_Extern, SC_None);
Steve Naroff09b266e2007-10-30 23:14:51 +00002490}
2491
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002492// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2493void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2494 IdentifierInfo *getSuperClassIdent =
2495 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002496 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002497 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002498 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2499 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002500 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002501 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002502 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002503 getSuperClassIdent,
2504 getClassType, 0,
Chad Rosiere3b29882013-01-04 22:40:33 +00002505 SC_Extern, SC_None);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002506}
2507
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002508// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002509void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002510 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002511 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002512 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002513 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2514 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002515 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002516 SourceLocation(),
2517 SourceLocation(),
2518 getClassIdent, getClassType,
2519 0, SC_Extern, SC_None);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002520}
2521
Steve Naroffb29b4272008-04-14 22:03:09 +00002522Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002523 QualType strType = getConstantStringStructType();
2524
2525 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002526
2527 std::string tmpName = InFileName;
2528 unsigned i;
2529 for (i=0; i < tmpName.length(); i++) {
2530 char c = tmpName.at(i);
2531 // replace any non alphanumeric characters with '_'.
2532 if (!isalpha(c) && (c < '0' || c > '9'))
2533 tmpName[i] = '_';
2534 }
2535 S += tmpName;
2536 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002537 S += utostr(NumObjCStringLiterals++);
2538
Steve Naroffba92b2e2008-03-27 22:29:16 +00002539 Preamble += "static __NSConstantStringImpl " + S;
2540 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2541 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002542 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002543 std::string prettyBufS;
2544 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002545 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002546 Preamble += prettyBuf.str();
2547 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002548 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002549
2550 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002551 SourceLocation(), &Context->Idents.get(S),
2552 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002553 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002554 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002555 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002556 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002557 VK_RValue, OK_Ordinary,
2558 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002559 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002560 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002561 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002562 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002563 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002564 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002565}
2566
Steve Naroff874e2322007-11-15 10:28:18 +00002567// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002568QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002569 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002570 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002571 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002572 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002573 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Steve Naroff874e2322007-11-15 10:28:18 +00002575 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002576 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002577 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002578 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002579
Steve Naroff874e2322007-11-15 10:28:18 +00002580 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002581 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002582 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002583 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002584 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002585 FieldTypes[i], 0,
2586 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002587 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002588 ICIS_NoInit));
Douglas Gregor44b43212008-12-11 16:49:14 +00002589 }
Mike Stump1eb44332009-09-09 15:08:12 +00002590
Douglas Gregor838db382010-02-11 01:19:42 +00002591 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002592 }
2593 return Context->getTagDeclType(SuperStructDecl);
2594}
2595
Steve Naroffb29b4272008-04-14 22:03:09 +00002596QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002597 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002598 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002599 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002600 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002601 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002602
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002603 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002604 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002605 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002606 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002607 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002608 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002609 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002610 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002611
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002612 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002613 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002614 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2615 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002616 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002617 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002618 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002619 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002620 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002621 ICIS_NoInit));
Douglas Gregor44b43212008-12-11 16:49:14 +00002622 }
2623
Douglas Gregor838db382010-02-11 01:19:42 +00002624 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002625 }
2626 return Context->getTagDeclType(ConstantStringDecl);
2627}
2628
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002629CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2630 QualType msgSendType,
2631 QualType returnType,
2632 SmallVectorImpl<QualType> &ArgTypes,
2633 SmallVectorImpl<Expr*> &MsgExprs,
2634 ObjCMethodDecl *Method) {
2635 // Create a reference to the objc_msgSend_stret() declaration.
2636 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2637 false, msgSendType,
2638 VK_LValue, SourceLocation());
2639 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2640 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2641 Context->getPointerType(Context->VoidTy),
2642 CK_BitCast, STDRE);
2643 // Now do the "normal" pointer to function cast.
2644 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2645 Method ? Method->isVariadic() : false);
2646 castType = Context->getPointerType(castType);
2647 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2648 cast);
2649
2650 // Don't forget the parens to enforce the proper binding.
2651 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2652
2653 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002654 CallExpr *STCE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002655 FT->getResultType(), VK_RValue,
2656 SourceLocation());
2657 return STCE;
2658
2659}
2660
2661
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002662Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2663 SourceLocation StartLoc,
2664 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002665 if (!SelGetUidFunctionDecl)
2666 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002667 if (!MsgSendFunctionDecl)
2668 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002669 if (!MsgSendSuperFunctionDecl)
2670 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002671 if (!MsgSendStretFunctionDecl)
2672 SynthMsgSendStretFunctionDecl();
2673 if (!MsgSendSuperStretFunctionDecl)
2674 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002675 if (!MsgSendFpretFunctionDecl)
2676 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002677 if (!GetClassFunctionDecl)
2678 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002679 if (!GetSuperClassFunctionDecl)
2680 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002681 if (!GetMetaClassFunctionDecl)
2682 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Steve Naroff874e2322007-11-15 10:28:18 +00002684 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002685 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2686 // May need to use objc_msgSend_stret() as well.
2687 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002688 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2689 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002690 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002691 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002692 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002693 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002694 }
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Steve Naroff934f2762007-10-24 22:48:43 +00002696 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002697 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002698 switch (Exp->getReceiverKind()) {
2699 case ObjCMessageExpr::SuperClass: {
2700 MsgSendFlavor = MsgSendSuperFunctionDecl;
2701 if (MsgSendStretFlavor)
2702 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2703 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002704
Douglas Gregor04badcf2010-04-21 00:45:42 +00002705 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Chris Lattner5f9e2722011-07-23 10:55:15 +00002707 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002708
Douglas Gregor04badcf2010-04-21 00:45:42 +00002709 // set the receiver to self, the first argument to all methods.
2710 InitExprs.push_back(
2711 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002712 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002713 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002714 false,
John McCallf89e55a2010-11-18 06:31:45 +00002715 Context->getObjCIdType(),
2716 VK_RValue,
2717 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002718 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Douglas Gregor04badcf2010-04-21 00:45:42 +00002720 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002721 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002722 QualType argType = Context->getPointerType(Context->CharTy);
2723 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002724 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002725 StringLiteral::Ascii, false,
2726 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002727 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2728 &ClsExprs[0],
2729 ClsExprs.size(),
2730 StartLoc,
2731 EndLoc);
2732 // (Class)objc_getClass("CurrentClass")
2733 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2734 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002735 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002736 ClsExprs.clear();
2737 ClsExprs.push_back(ArgExpr);
2738 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2739 &ClsExprs[0], ClsExprs.size(),
2740 StartLoc, EndLoc);
2741
2742 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2743 // To turn off a warning, type-cast to 'id'
2744 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2745 NoTypeInfoCStyleCastExpr(Context,
2746 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002747 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002748 // struct objc_super
2749 QualType superType = getSuperStructType();
2750 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002751
Francois Pichet62ec1f22011-09-17 17:15:52 +00002752 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002753 SynthSuperContructorFunctionDecl();
2754 // Simulate a contructor call...
2755 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002756 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002757 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002758 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00002759 superType, VK_LValue,
2760 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002761 // The code for super is a little tricky to prevent collision with
2762 // the structure definition in the header. The rewriter has it's own
2763 // internal definition (__rw_objc_super) that is uses. This is why
2764 // we need the cast below. For example:
2765 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2766 //
John McCall2de56d12010-08-25 11:45:40 +00002767 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002768 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002769 VK_RValue, OK_Ordinary,
2770 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002771 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2772 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002773 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002774 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002775 // (struct objc_super) { <exprs from above> }
2776 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002777 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002778 SourceLocation());
2779 TypeSourceInfo *superTInfo
2780 = Context->getTrivialTypeSourceInfo(superType);
2781 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002782 superType, VK_LValue,
2783 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002784 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002785 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002786 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002787 VK_RValue, OK_Ordinary,
2788 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002789 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002790 MsgExprs.push_back(SuperRep);
2791 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002792 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002793
2794 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002795 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002796 QualType argType = Context->getPointerType(Context->CharTy);
2797 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002798 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002799 IdentifierInfo *clsName = Class->getIdentifier();
2800 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002801 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002802 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002803 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002804 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2805 &ClsExprs[0],
2806 ClsExprs.size(),
2807 StartLoc, EndLoc);
2808 MsgExprs.push_back(Cls);
2809 break;
2810 }
2811
2812 case ObjCMessageExpr::SuperInstance:{
2813 MsgSendFlavor = MsgSendSuperFunctionDecl;
2814 if (MsgSendStretFlavor)
2815 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2816 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2817 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002818 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002819
2820 InitExprs.push_back(
2821 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002822 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002823 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002824 false,
John McCallf89e55a2010-11-18 06:31:45 +00002825 Context->getObjCIdType(),
2826 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002827 ); // set the 'receiver'.
2828
2829 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002830 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002831 QualType argType = Context->getPointerType(Context->CharTy);
2832 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002833 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002834 StringLiteral::Ascii, false, argType,
2835 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002836 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2837 &ClsExprs[0],
2838 ClsExprs.size(),
2839 StartLoc, EndLoc);
2840 // (Class)objc_getClass("CurrentClass")
2841 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2842 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002843 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002844 ClsExprs.clear();
2845 ClsExprs.push_back(ArgExpr);
2846 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2847 &ClsExprs[0], ClsExprs.size(),
2848 StartLoc, EndLoc);
2849
2850 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2851 // To turn off a warning, type-cast to 'id'
2852 InitExprs.push_back(
2853 // set 'super class', using class_getSuperclass().
2854 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002855 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002856 // struct objc_super
2857 QualType superType = getSuperStructType();
2858 Expr *SuperRep;
2859
Francois Pichet62ec1f22011-09-17 17:15:52 +00002860 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002861 SynthSuperContructorFunctionDecl();
2862 // Simulate a contructor call...
2863 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002864 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002865 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002866 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00002867 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002868 // The code for super is a little tricky to prevent collision with
2869 // the structure definition in the header. The rewriter has it's own
2870 // internal definition (__rw_objc_super) that is uses. This is why
2871 // we need the cast below. For example:
2872 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2873 //
John McCall2de56d12010-08-25 11:45:40 +00002874 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002875 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002876 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002877 SourceLocation());
2878 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2879 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002880 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002881 } else {
2882 // (struct objc_super) { <exprs from above> }
2883 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002884 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002885 SourceLocation());
2886 TypeSourceInfo *superTInfo
2887 = Context->getTrivialTypeSourceInfo(superType);
2888 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002889 superType, VK_RValue, ILE,
2890 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002891 }
2892 MsgExprs.push_back(SuperRep);
2893 break;
2894 }
2895
2896 case ObjCMessageExpr::Instance: {
2897 // Remove all type-casts because it may contain objc-style types; e.g.
2898 // Foo<Proto> *.
2899 Expr *recExpr = Exp->getInstanceReceiver();
2900 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2901 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002902 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2903 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2904 ? CK_BlockPointerToObjCPointerCast
2905 : CK_CPointerToObjCPointerCast;
2906
Douglas Gregor04badcf2010-04-21 00:45:42 +00002907 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002908 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002909 MsgExprs.push_back(recExpr);
2910 break;
2911 }
2912 }
2913
Steve Naroffbeaf2992007-11-03 11:27:19 +00002914 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002915 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002916 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002917 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002918 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002919 StringLiteral::Ascii, false,
2920 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002921 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002922 &SelExprs[0], SelExprs.size(),
2923 StartLoc,
2924 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002925 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002926
Steve Naroff934f2762007-10-24 22:48:43 +00002927 // Now push any user supplied arguments.
2928 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002929 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002930 // Make all implicit casts explicit...ICE comes in handy:-)
2931 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2932 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002933 QualType type = ICE->getType();
2934 if (needToScanForQualifiers(type))
2935 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002936 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002937 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002938 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002939 CastKind CK;
2940 if (SubExpr->getType()->isIntegralType(*Context) &&
2941 type->isBooleanType()) {
2942 CK = CK_IntegralToBoolean;
2943 } else if (type->isObjCObjectPointerType()) {
2944 if (SubExpr->getType()->isBlockPointerType()) {
2945 CK = CK_BlockPointerToObjCPointerCast;
2946 } else if (SubExpr->getType()->isPointerType()) {
2947 CK = CK_CPointerToObjCPointerCast;
2948 } else {
2949 CK = CK_BitCast;
2950 }
2951 } else {
2952 CK = CK_BitCast;
2953 }
2954
2955 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002956 }
2957 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002958 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002959 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002960 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002961 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002962 CastKind CK;
2963 if (userExpr->getType()->isIntegralType(*Context)) {
2964 CK = CK_IntegralToPointer;
2965 } else if (userExpr->getType()->isBlockPointerType()) {
2966 CK = CK_BlockPointerToObjCPointerCast;
2967 } else if (userExpr->getType()->isPointerType()) {
2968 CK = CK_CPointerToObjCPointerCast;
2969 } else {
2970 CK = CK_BitCast;
2971 }
John McCall9d125032010-01-15 18:39:57 +00002972 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002973 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002974 }
Mike Stump1eb44332009-09-09 15:08:12 +00002975 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002976 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002977 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2978 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002979 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002980 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002981 }
Steve Naroffab972d32007-11-04 22:37:50 +00002982 // Generate the funky cast.
2983 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002984 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002985 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002986
Steve Naroffab972d32007-11-04 22:37:50 +00002987 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002988 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2989 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2990 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002991 ArgTypes.push_back(Context->getObjCIdType());
2992 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002993 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002994 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002995 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2996 E = OMD->param_end(); PI != E; ++PI) {
2997 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002998 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002999 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003000 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003001 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003002 ArgTypes.push_back(t);
3003 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00003004 returnType = Exp->getType();
3005 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003006 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003007 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003008 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003009 }
3010 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003011 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003012
Steve Naroffab972d32007-11-04 22:37:50 +00003013 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003014 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003015 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003016
Mike Stump1eb44332009-09-09 15:08:12 +00003017 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003018 // If we don't do this cast, we get the following bizarre warning/note:
3019 // xx.m:13: warning: function called through a non-compatible type
3020 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003021 cast = NoTypeInfoCStyleCastExpr(Context,
3022 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003023 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003024
Steve Naroffab972d32007-11-04 22:37:50 +00003025 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003026 QualType castType =
3027 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3028 // If we don't have a method decl, force a variadic cast.
3029 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003030 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003031 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003032 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003033
3034 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003035 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003036
John McCall183700f2009-09-21 23:43:11 +00003037 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003038 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
John McCallf89e55a2010-11-18 06:31:45 +00003039 FT->getResultType(), VK_RValue,
3040 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003041 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003042 if (MsgSendStretFlavor) {
3043 // We have the method which returns a struct/union. Must also generate
3044 // call to objc_msgSend_stret and hang both varieties on a conditional
3045 // expression which dictate which one to envoke depending on size of
3046 // method's return type.
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00003047
3048 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3049 msgSendType, returnType,
3050 ArgTypes, MsgExprs,
3051 Exp->getMethodDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003052
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003053 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003054 UnaryExprOrTypeTraitExpr *sizeofExpr =
3055 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3056 Context->getTrivialTypeSourceInfo(returnType),
3057 Context->getSizeType(), SourceLocation(),
3058 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003059 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3060 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3061 // For X86 it is more complicated and some kind of target specific routine
3062 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003063 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003064 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003065 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3066 llvm::APInt(IntSize, 8),
3067 Context->IntTy,
3068 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003069 BinaryOperator *lessThanExpr =
3070 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003071 VK_RValue, OK_Ordinary, SourceLocation(),
3072 false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003073 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003074 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003075 new (Context) ConditionalOperator(lessThanExpr,
3076 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003077 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003078 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003079 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3080 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003081 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003082 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003083 return ReplacingStmt;
3084}
3085
Steve Naroffb29b4272008-04-14 22:03:09 +00003086Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003087 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3088 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Steve Naroff934f2762007-10-24 22:48:43 +00003090 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003091 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003092
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003093 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003094 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003095}
3096
Steve Naroff621edce2009-04-29 16:37:50 +00003097// typedef struct objc_object Protocol;
3098QualType RewriteObjC::getProtocolType() {
3099 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003100 TypeSourceInfo *TInfo
3101 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003102 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003103 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003104 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003105 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003106 }
3107 return Context->getTypeDeclType(ProtocolTypeDecl);
3108}
3109
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003110/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003111/// a synthesized/forward data reference (to the protocol's metadata).
3112/// The forward references (and metadata) are generated in
3113/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003114Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003115 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3116 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003117 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003118 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003119 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003120 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3121 VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003122 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003123 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003124 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003125 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003126 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003127 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003128 ReplaceStmt(Exp, castExpr);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00003129 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003130 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003131 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003133}
3134
Mike Stump1eb44332009-09-09 15:08:12 +00003135bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003136 const char *endBuf) {
3137 while (startBuf < endBuf) {
3138 if (*startBuf == '#') {
3139 // Skip whitespace.
3140 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3141 ;
3142 if (!strncmp(startBuf, "if", strlen("if")) ||
3143 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3144 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3145 !strncmp(startBuf, "define", strlen("define")) ||
3146 !strncmp(startBuf, "undef", strlen("undef")) ||
3147 !strncmp(startBuf, "else", strlen("else")) ||
3148 !strncmp(startBuf, "elif", strlen("elif")) ||
3149 !strncmp(startBuf, "endif", strlen("endif")) ||
3150 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3151 !strncmp(startBuf, "include", strlen("include")) ||
3152 !strncmp(startBuf, "import", strlen("import")) ||
3153 !strncmp(startBuf, "include_next", strlen("include_next")))
3154 return true;
3155 }
3156 startBuf++;
3157 }
3158 return false;
3159}
3160
Fariborz Jahanian58457172011-12-05 18:43:13 +00003161/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003162/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003163void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003164 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003165 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003166 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003167 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003168 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003169 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003170 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003171 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003172 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003173 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003174 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003175
Steve Narofffea763e82007-11-14 19:25:57 +00003176 const char *startBuf = SM->getCharacterData(LocStart);
3177 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003179 // If no ivars and no root or if its root, directly or indirectly,
3180 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003181 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003182 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003183 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003184 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003185 return;
3186 }
Mike Stump1eb44332009-09-09 15:08:12 +00003187
3188 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003189 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003190 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003191 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003192 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003193 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003194
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003195 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003196 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003197 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003198 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003199 // If the buffer contains preprocessor directives, we do more fine-grained
3200 // rewrites. This is intended to fix code that looks like (which occurs in
3201 // NSURL.h, for example):
3202 //
3203 // #ifdef XYZ
3204 // @interface Foo : NSObject
3205 // #else
3206 // @interface FooBar : NSObject
3207 // #endif
3208 // {
3209 // int i;
3210 // }
3211 // @end
3212 //
3213 // This clause is segregated to avoid breaking the common case.
3214 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003215 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003216 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003217 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003218 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003219
Chris Lattnercafeb352009-02-20 18:18:36 +00003220 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003221 // advance to the end of the referenced protocols.
3222 while (endHeader < cursor && *endHeader != '>') endHeader++;
3223 endHeader++;
3224 }
3225 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003226 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003227 } else {
3228 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003229 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003230 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003231 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003232 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003233 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003234 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003235 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003236 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003237
Steve Narofffea763e82007-11-14 19:25:57 +00003238 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003239 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003240 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003241 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003242 }
3243 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003244
Steve Narofffea763e82007-11-14 19:25:57 +00003245 // Now comment out any visibility specifiers.
3246 while (cursor < endBuf) {
3247 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003248 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003249 // Skip whitespace.
3250 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3251 /*scan*/;
3252
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003253 // FIXME: presence of @public, etc. inside comment results in
3254 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003255 if (!strncmp(cursor, "public", strlen("public")) ||
3256 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003257 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003258 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003259 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003260 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003261 // FIXME: If there are cases where '<' is used in ivar declaration part
3262 // of user code, then scan the ivar list and use needToScanForQualifiers
3263 // for type checking.
3264 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003265 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003266 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003267 cursor = strchr(cursor, '>');
3268 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003269 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003270 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003271 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003272 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003273 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003274 }
Steve Narofffea763e82007-11-14 19:25:57 +00003275 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003276 }
Steve Narofffea763e82007-11-14 19:25:57 +00003277 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003278 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003279 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003280 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003281 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003282 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003283 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003284 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003285 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003286 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003287 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003288 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003289 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003290 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003291}
3292
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003293//===----------------------------------------------------------------------===//
3294// Meta Data Emission
3295//===----------------------------------------------------------------------===//
3296
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003297
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003298/// RewriteImplementations - This routine rewrites all method implementations
3299/// and emits meta-data.
3300
Steve Narofface66252008-11-13 20:07:04 +00003301void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003302 int ClsDefCount = ClassImplementation.size();
3303 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003304
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003305 // Rewrite implemented methods
3306 for (int i = 0; i < ClsDefCount; i++)
3307 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003308
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003309 for (int i = 0; i < CatDefCount; i++)
3310 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003311}
Mike Stump1eb44332009-09-09 15:08:12 +00003312
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003313void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3314 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003315 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003316 assert(BlockByRefDeclNo.count(VD) &&
3317 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003318 if (def)
3319 ResultStr += "struct ";
3320 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003321 "_" + utostr(BlockByRefDeclNo[VD]) ;
3322}
3323
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003324static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3325 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3326 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3327 return false;
3328}
3329
Steve Naroff54055232008-10-27 17:20:55 +00003330std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003331 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003332 std::string Tag) {
3333 const FunctionType *AFT = CE->getFunctionType();
3334 QualType RT = AFT->getResultType();
3335 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003336 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003337 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003338
Steve Naroff54055232008-10-27 17:20:55 +00003339 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003340
Douglas Gregor72564e72009-02-26 23:50:07 +00003341 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003342 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003343 // block (to reference imported block decl refs).
3344 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003345 } else if (BD->param_empty()) {
3346 S += "(" + StructRef + " *__cself)";
3347 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003348 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003349 assert(FT && "SynthesizeBlockFunc: No function proto");
3350 S += '(';
3351 // first add the implicit argument.
3352 S += StructRef + " *__cself, ";
3353 std::string ParamStr;
3354 for (BlockDecl::param_iterator AI = BD->param_begin(),
3355 E = BD->param_end(); AI != E; ++AI) {
3356 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003357 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003358 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003359 (void)convertBlockPointerToFunctionPointer(QT);
3360 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003361 S += ParamStr;
3362 }
3363 if (FT->isVariadic()) {
3364 if (!BD->param_empty()) S += ", ";
3365 S += "...";
3366 }
3367 S += ')';
3368 }
3369 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003370
Steve Naroff54055232008-10-27 17:20:55 +00003371 // Create local declarations to avoid rewriting all closure decl ref exprs.
3372 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003373 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003374 E = BlockByRefDecls.end(); I != E; ++I) {
3375 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003376 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003377 std::string TypeString;
3378 RewriteByRefString(TypeString, Name, (*I));
3379 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003380 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003381 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003382 }
Steve Naroff54055232008-10-27 17:20:55 +00003383 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003384 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003385 E = BlockByCopyDecls.end(); I != E; ++I) {
3386 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003387 // Handle nested closure invocation. For example:
3388 //
3389 // void (^myImportedClosure)(void);
3390 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003391 //
Steve Naroff54055232008-10-27 17:20:55 +00003392 // void (^anotherClosure)(void);
3393 // anotherClosure = ^(void) {
3394 // myImportedClosure(); // import and invoke the closure
3395 // };
3396 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003397 if (isTopLevelBlockPointerType((*I)->getType())) {
3398 RewriteBlockPointerTypeVariable(S, (*I));
3399 S += " = (";
3400 RewriteBlockPointerType(S, (*I)->getType());
3401 S += ")";
3402 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3403 }
3404 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003405 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003406 QualType QT = (*I)->getType();
3407 if (HasLocalVariableExternalStorage(*I))
3408 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003409 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003410 S += Name + " = __cself->" +
3411 (*I)->getNameAsString() + "; // bound by copy\n";
3412 }
Steve Naroff54055232008-10-27 17:20:55 +00003413 }
3414 std::string RewrittenStr = RewrittenBlockExprs[CE];
3415 const char *cstr = RewrittenStr.c_str();
3416 while (*cstr++ != '{') ;
3417 S += cstr;
3418 S += "\n";
3419 return S;
3420}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003421
Steve Naroff54055232008-10-27 17:20:55 +00003422std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003423 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003424 std::string Tag) {
3425 std::string StructRef = "struct " + Tag;
3426 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003427
Steve Naroff54055232008-10-27 17:20:55 +00003428 S += funcName;
3429 S += "_block_copy_" + utostr(i);
3430 S += "(" + StructRef;
3431 S += "*dst, " + StructRef;
3432 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003433 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003434 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003435 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003436 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003437 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003438 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003439 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003440 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003441 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003442 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003443 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003444 else
3445 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003446 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003447 S += "}\n";
3448
Steve Naroff54055232008-10-27 17:20:55 +00003449 S += "\nstatic void __";
3450 S += funcName;
3451 S += "_block_dispose_" + utostr(i);
3452 S += "(" + StructRef;
3453 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003454 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003455 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003456 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003457 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003458 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003459 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003460 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003461 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003462 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003463 else
3464 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003465 }
Mike Stump1eb44332009-09-09 15:08:12 +00003466 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003467 return S;
3468}
3469
Steve Naroff01aec112009-12-06 21:14:13 +00003470std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3471 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003472 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003473 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003474
Steve Naroff54055232008-10-27 17:20:55 +00003475 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003476 S += " struct " + Desc;
3477 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003478
Steve Naroff01aec112009-12-06 21:14:13 +00003479 Constructor += "(void *fp, "; // Invoke function pointer.
3480 Constructor += "struct " + Desc; // Descriptor pointer.
3481 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003482
Steve Naroff54055232008-10-27 17:20:55 +00003483 if (BlockDeclRefs.size()) {
3484 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003485 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003486 E = BlockByCopyDecls.end(); I != E; ++I) {
3487 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003488 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003489 std::string ArgName = "_" + FieldName;
3490 // Handle nested closure invocation. For example:
3491 //
3492 // void (^myImportedBlock)(void);
3493 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003494 //
Steve Naroff54055232008-10-27 17:20:55 +00003495 // void (^anotherBlock)(void);
3496 // anotherBlock = ^(void) {
3497 // myImportedBlock(); // import and invoke the closure
3498 // };
3499 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003500 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003501 S += "struct __block_impl *";
3502 Constructor += ", void *" + ArgName;
3503 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003504 QualType QT = (*I)->getType();
3505 if (HasLocalVariableExternalStorage(*I))
3506 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003507 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3508 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003509 Constructor += ", " + ArgName;
3510 }
3511 S += FieldName + ";\n";
3512 }
3513 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003514 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003515 E = BlockByRefDecls.end(); I != E; ++I) {
3516 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003517 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003518 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003519 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003520 std::string TypeString;
3521 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003522 TypeString += " *";
3523 FieldName = TypeString + FieldName;
3524 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003525 Constructor += ", " + ArgName;
3526 }
3527 S += FieldName + "; // by ref\n";
3528 }
3529 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003530 Constructor += ", int flags=0)";
3531 // Initialize all "by copy" arguments.
3532 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003533 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003534 E = BlockByCopyDecls.end(); I != E; ++I) {
3535 std::string Name = (*I)->getNameAsString();
3536 if (firsTime) {
3537 Constructor += " : ";
3538 firsTime = false;
3539 }
3540 else
3541 Constructor += ", ";
3542 if (isTopLevelBlockPointerType((*I)->getType()))
3543 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3544 else
3545 Constructor += Name + "(_" + Name + ")";
3546 }
3547 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003548 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003549 E = BlockByRefDecls.end(); I != E; ++I) {
3550 std::string Name = (*I)->getNameAsString();
3551 if (firsTime) {
3552 Constructor += " : ";
3553 firsTime = false;
3554 }
3555 else
3556 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003557 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003558 }
3559
3560 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003561 if (GlobalVarDecl)
3562 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3563 else
3564 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003565 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Steve Naroff01aec112009-12-06 21:14:13 +00003567 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003568 } else {
3569 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003570 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003571 if (GlobalVarDecl)
3572 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3573 else
3574 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003575 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3576 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003577 }
3578 Constructor += " ";
3579 Constructor += "}\n";
3580 S += Constructor;
3581 S += "};\n";
3582 return S;
3583}
3584
Steve Naroff01aec112009-12-06 21:14:13 +00003585std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3586 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003587 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003588 unsigned hasCopy) {
3589 std::string S = "\nstatic struct " + DescTag;
3590
3591 S += " {\n unsigned long reserved;\n";
3592 S += " unsigned long Block_size;\n";
3593 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003594 S += " void (*copy)(struct ";
3595 S += ImplTag; S += "*, struct ";
3596 S += ImplTag; S += "*);\n";
3597
3598 S += " void (*dispose)(struct ";
3599 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003600 }
3601 S += "} ";
3602
3603 S += DescTag + "_DATA = { 0, sizeof(struct ";
3604 S += ImplTag + ")";
3605 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003606 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3607 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003608 }
3609 S += "};\n";
3610 return S;
3611}
3612
Steve Naroff54055232008-10-27 17:20:55 +00003613void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003614 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003615 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003616 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003617 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003618 bool RewriteSC = (GlobalVarDecl &&
3619 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003620 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003621 GlobalVarDecl->getType().getCVRQualifiers());
3622 if (RewriteSC) {
3623 std::string SC(" void __");
3624 SC += GlobalVarDecl->getNameAsString();
3625 SC += "() {}";
3626 InsertText(FunLocStart, SC);
3627 }
3628
Steve Naroff54055232008-10-27 17:20:55 +00003629 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003630 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3631 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003632 // Need to copy-in the inner copied-in variables not actually used in this
3633 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003634 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003635 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003636 ValueDecl *VD = Exp->getDecl();
3637 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003638 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003639 BlockByCopyDeclsPtrSet.insert(VD);
3640 BlockByCopyDecls.push_back(VD);
3641 }
John McCallf4b88a42012-03-10 09:33:50 +00003642 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003643 BlockByRefDeclsPtrSet.insert(VD);
3644 BlockByRefDecls.push_back(VD);
3645 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003646 // imported objects in the inner blocks not used in the outer
3647 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003648 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003649 VD->getType()->isObjCObjectPointerType() ||
3650 VD->getType()->isBlockPointerType())
3651 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003652 }
Steve Naroff54055232008-10-27 17:20:55 +00003653
Daniel Dunbar4087f272010-08-17 22:39:59 +00003654 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3655 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003656
Steve Naroff01aec112009-12-06 21:14:13 +00003657 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003658
Benjamin Kramerd999b372010-02-14 14:14:16 +00003659 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003660
Steve Naroff01aec112009-12-06 21:14:13 +00003661 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003662
Benjamin Kramerd999b372010-02-14 14:14:16 +00003663 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003664
3665 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003666 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003667 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003668 }
Steve Naroff01aec112009-12-06 21:14:13 +00003669 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3670 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003671 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Steve Naroff54055232008-10-27 17:20:55 +00003673 BlockDeclRefs.clear();
3674 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003675 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003676 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003677 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003678 ImportedBlockDecls.clear();
3679 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003680 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003681 // Must insert any 'const/volatile/static here. Since it has been
3682 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003683 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003684 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003685 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003686 if (GlobalVarDecl->getType().isConstQualified())
3687 SC += "const ";
3688 if (GlobalVarDecl->getType().isVolatileQualified())
3689 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003690 if (GlobalVarDecl->getType().isRestrictQualified())
3691 SC += "restrict ";
3692 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003693 }
3694
Steve Naroff54055232008-10-27 17:20:55 +00003695 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003696 InnerDeclRefsCount.clear();
3697 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003698 RewrittenBlockExprs.clear();
3699}
3700
3701void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3702 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003703 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003704
Steve Naroff54055232008-10-27 17:20:55 +00003705 SynthesizeBlockLiterals(FunLocStart, FuncName);
3706}
3707
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003708static void BuildUniqueMethodName(std::string &Name,
3709 ObjCMethodDecl *MD) {
3710 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003711 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003712 Name += "__" + MD->getSelector().getAsString();
3713 // Convert colons to underscores.
3714 std::string::size_type loc = 0;
3715 while ((loc = Name.find(":", loc)) != std::string::npos)
3716 Name.replace(loc, 1, "_");
3717}
3718
Steve Naroff54055232008-10-27 17:20:55 +00003719void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003720 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3721 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003722 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003723 std::string FuncName;
3724 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003725 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003726}
3727
3728void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003729 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003730 if (*CI) {
3731 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3732 GetBlockDeclRefExprs(CBE->getBody());
3733 else
3734 GetBlockDeclRefExprs(*CI);
3735 }
3736 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003737 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3738 if (DRE->refersToEnclosingLocal()) {
3739 // FIXME: Handle enums.
3740 if (!isa<FunctionDecl>(DRE->getDecl()))
3741 BlockDeclRefs.push_back(DRE);
3742 if (HasLocalVariableExternalStorage(DRE->getDecl()))
3743 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003744 }
John McCallf4b88a42012-03-10 09:33:50 +00003745 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003746
Steve Naroff54055232008-10-27 17:20:55 +00003747 return;
3748}
3749
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003750void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003751 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003752 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003753 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003754 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003755 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3756 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003757 GetInnerBlockDeclRefExprs(CBE->getBody(),
3758 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003759 InnerContexts);
3760 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003761 else
3762 GetInnerBlockDeclRefExprs(*CI,
3763 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003764 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003765
3766 }
3767 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003768 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3769 if (DRE->refersToEnclosingLocal()) {
3770 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3771 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3772 InnerBlockDeclRefs.push_back(DRE);
3773 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3774 if (Var->isFunctionOrMethodVarDecl())
3775 ImportedLocalExternalDecls.insert(Var);
3776 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003777 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003778
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003779 return;
3780}
3781
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003782/// convertFunctionTypeOfBlocks - This routine converts a function type
3783/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003784/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003785/// all block pointers to function pointers.
3786QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3787 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3788 // FTP will be null for closures that don't take arguments.
3789 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003790 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003791 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003792 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003793
3794 if (FTP) {
3795 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3796 E = FTP->arg_type_end(); I && (I != E); ++I) {
3797 QualType t = *I;
3798 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003799 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003800 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003801 ArgTypes.push_back(t);
3802 }
3803 }
3804 QualType FuncType;
3805 // FIXME. Does this work if block takes no argument but has a return type
3806 // which is of block type?
3807 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00003808 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003809 else FuncType = QualType(FT, 0);
3810 return FuncType;
3811}
3812
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003813Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003814 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00003815 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003817 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003818 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003819 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003820 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003821 }
3822 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3823 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3824 }
3825 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3826 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3827 else if (const ConditionalOperator *CEXPR =
3828 dyn_cast<ConditionalOperator>(BlockExp)) {
3829 Expr *LHSExp = CEXPR->getLHS();
3830 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3831 Expr *RHSExp = CEXPR->getRHS();
3832 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3833 Expr *CONDExp = CEXPR->getCond();
3834 ConditionalOperator *CondExpr =
3835 new (Context) ConditionalOperator(CONDExp,
3836 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003837 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003838 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003839 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003840 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3841 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003842 } else if (const PseudoObjectExpr *POE
3843 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3844 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003845 } else {
3846 assert(1 && "RewriteBlockClass: Bad type");
3847 }
3848 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003849 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003850 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003851 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003852 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003853
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003854 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003855 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003856 &Context->Idents.get("__block_impl"));
3857 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003858
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003859 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003860 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003861
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003862 // Push the block argument type.
3863 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003864 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00003865 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003866 E = FTP->arg_type_end(); I && (I != E); ++I) {
3867 QualType t = *I;
3868 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003869 if (!convertBlockPointerToFunctionPointer(t))
3870 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003871 ArgTypes.push_back(t);
3872 }
Steve Naroff54055232008-10-27 17:20:55 +00003873 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003874 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003875 QualType PtrToFuncCastType
3876 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003877
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003878 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003879
John McCall9d125032010-01-15 18:39:57 +00003880 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003881 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003882 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003883 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003884 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3885 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003886 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003887
Douglas Gregor44b43212008-12-11 16:49:14 +00003888 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003889 SourceLocation(),
3890 &Context->Idents.get("FuncPtr"),
3891 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003892 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003893 ICIS_NoInit);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003894 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003895 FD->getType(), VK_LValue,
3896 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003898
John McCall9d125032010-01-15 18:39:57 +00003899 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003900 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003901 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003902
Chris Lattner5f9e2722011-07-23 10:55:15 +00003903 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003904 // Add the implicit argument.
3905 BlkExprs.push_back(BlkCast);
3906 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003907 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003908 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003909 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003910 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003911 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCallf89e55a2010-11-18 06:31:45 +00003912 Exp->getType(), VK_RValue,
3913 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003914 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003915}
3916
Steve Naroff621edce2009-04-29 16:37:50 +00003917// We need to return the rewritten expression to handle cases where the
3918// BlockDeclRefExpr is embedded in another expression being rewritten.
3919// For example:
3920//
3921// int main() {
3922// __block Foo *f;
3923// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003924//
Steve Naroff621edce2009-04-29 16:37:50 +00003925// void (^myblock)() = ^() {
3926// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3927// i = 77;
3928// };
3929//}
John McCallf4b88a42012-03-10 09:33:50 +00003930Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003931 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003932 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003933 ValueDecl *VD = DeclRefExp->getDecl();
3934 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003935
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003936 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003937 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003938 &Context->Idents.get("__forwarding"),
3939 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003940 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003941 ICIS_NoInit);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003942 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3943 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003944 FD->getType(), VK_LValue,
3945 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003946
Chris Lattner5f9e2722011-07-23 10:55:15 +00003947 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003948 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003949 &Context->Idents.get(Name),
3950 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003951 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003952 ICIS_NoInit);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003953 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003954 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003955
3956
3957
Steve Naroffdf8570d2009-02-02 17:19:26 +00003958 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003959 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3960 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003961 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003962 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003963 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003964}
3965
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003966// Rewrites the imported local variable V with external storage
3967// (static, extern, etc.) as *V
3968//
3969Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3970 ValueDecl *VD = DRE->getDecl();
3971 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3972 if (!ImportedLocalExternalDecls.count(Var))
3973 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003974 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3975 VK_LValue, OK_Ordinary,
3976 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003977 // Need parens to enforce precedence.
3978 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3979 Exp);
3980 ReplaceStmt(DRE, PE);
3981 return PE;
3982}
3983
Steve Naroffb2f9e512008-11-03 23:29:32 +00003984void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3985 SourceLocation LocStart = CE->getLParenLoc();
3986 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003987
3988 // Need to avoid trying to rewrite synthesized casts.
3989 if (LocStart.isInvalid())
3990 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003991 // Need to avoid trying to rewrite casts contained in macros.
3992 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3993 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003994
Steve Naroff54055232008-10-27 17:20:55 +00003995 const char *startBuf = SM->getCharacterData(LocStart);
3996 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003997 QualType QT = CE->getType();
3998 const Type* TypePtr = QT->getAs<Type>();
3999 if (isa<TypeOfExprType>(TypePtr)) {
4000 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4001 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4002 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004003 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004004 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004005 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004006 return;
4007 }
Steve Naroff54055232008-10-27 17:20:55 +00004008 // advance the location to startArgList.
4009 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004010
Steve Naroff54055232008-10-27 17:20:55 +00004011 while (*argPtr++ && (argPtr < endBuf)) {
4012 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004013 case '^':
4014 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004015 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004016 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004017 break;
Steve Naroff54055232008-10-27 17:20:55 +00004018 }
4019 }
4020 return;
4021}
4022
4023void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4024 SourceLocation DeclLoc = FD->getLocation();
4025 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004026
Steve Naroff54055232008-10-27 17:20:55 +00004027 // We have 1 or more arguments that have closure pointers.
4028 const char *startBuf = SM->getCharacterData(DeclLoc);
4029 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004030
Steve Naroff54055232008-10-27 17:20:55 +00004031 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004032
Steve Naroff54055232008-10-27 17:20:55 +00004033 parenCount++;
4034 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004035 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004036 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004037
Steve Naroff54055232008-10-27 17:20:55 +00004038 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Steve Naroff54055232008-10-27 17:20:55 +00004040 while (*argPtr++ && parenCount) {
4041 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004042 case '^':
4043 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004044 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004045 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004046 break;
4047 case '(':
4048 parenCount++;
4049 break;
4050 case ')':
4051 parenCount--;
4052 break;
Steve Naroff54055232008-10-27 17:20:55 +00004053 }
4054 }
4055 return;
4056}
4057
4058bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004059 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004060 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004061 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004062 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004063 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004064 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004065 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004066 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004067 }
4068 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004069 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004070 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004071 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004072 return true;
4073 }
4074 return false;
4075}
4076
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004077bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4078 const FunctionProtoType *FTP;
4079 const PointerType *PT = QT->getAs<PointerType>();
4080 if (PT) {
4081 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4082 } else {
4083 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4084 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4085 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4086 }
4087 if (FTP) {
4088 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004089 E = FTP->arg_type_end(); I != E; ++I) {
4090 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004091 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004092 if ((*I)->isObjCObjectPointerType() &&
4093 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4094 return true;
4095 }
4096
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004097 }
4098 return false;
4099}
4100
Ted Kremenek8189cde2009-02-07 01:47:29 +00004101void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4102 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004103 const char *argPtr = strchr(Name, '(');
4104 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004105
Steve Naroff54055232008-10-27 17:20:55 +00004106 LParen = argPtr; // output the start.
4107 argPtr++; // skip past the left paren.
4108 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004109
Steve Naroff54055232008-10-27 17:20:55 +00004110 while (*argPtr && parenCount) {
4111 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004112 case '(': parenCount++; break;
4113 case ')': parenCount--; break;
4114 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004115 }
4116 if (parenCount) argPtr++;
4117 }
4118 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4119 RParen = argPtr; // output the end
4120}
4121
4122void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4123 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4124 RewriteBlockPointerFunctionArgs(FD);
4125 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004126 }
Steve Naroff54055232008-10-27 17:20:55 +00004127 // Handle Variables and Typedefs.
4128 SourceLocation DeclLoc = ND->getLocation();
4129 QualType DeclT;
4130 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4131 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004132 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004133 DeclT = TDD->getUnderlyingType();
4134 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4135 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004136 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004137 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004138
Steve Naroff54055232008-10-27 17:20:55 +00004139 const char *startBuf = SM->getCharacterData(DeclLoc);
4140 const char *endBuf = startBuf;
4141 // scan backward (from the decl location) for the end of the previous decl.
4142 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4143 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004144 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004145 std::string buf;
4146 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004147 // *startBuf != '^' if we are dealing with a pointer to function that
4148 // may take block argument types (which will be handled below).
4149 if (*startBuf == '^') {
4150 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004151 buf = '*';
4152 startBuf++;
4153 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004154 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004155 while (*startBuf != ')') {
4156 buf += *startBuf;
4157 startBuf++;
4158 OrigLength++;
4159 }
4160 buf += ')';
4161 OrigLength++;
4162
4163 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4164 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004165 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004166 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004167 DeclLoc = ND->getLocation();
4168 startBuf = SM->getCharacterData(DeclLoc);
4169 const char *argListBegin, *argListEnd;
4170 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4171 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004172 if (*argListBegin == '^')
4173 buf += '*';
4174 else if (*argListBegin == '<') {
4175 buf += "/*";
4176 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004177 OrigLength++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004178 while (*argListBegin != '>') {
4179 buf += *argListBegin++;
4180 OrigLength++;
4181 }
4182 buf += *argListBegin;
4183 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004184 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004185 else
4186 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004187 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004188 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004189 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004190 buf += ')';
4191 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004192 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004193 ReplaceText(Start, OrigLength, buf);
4194
Steve Naroff54055232008-10-27 17:20:55 +00004195 return;
4196}
4197
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004198
4199/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4200/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4201/// struct Block_byref_id_object *src) {
4202/// _Block_object_assign (&_dest->object, _src->object,
4203/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4204/// [|BLOCK_FIELD_IS_WEAK]) // object
4205/// _Block_object_assign(&_dest->object, _src->object,
4206/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4207/// [|BLOCK_FIELD_IS_WEAK]) // block
4208/// }
4209/// And:
4210/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4211/// _Block_object_dispose(_src->object,
4212/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4213/// [|BLOCK_FIELD_IS_WEAK]) // object
4214/// _Block_object_dispose(_src->object,
4215/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4216/// [|BLOCK_FIELD_IS_WEAK]) // block
4217/// }
4218
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004219std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4220 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004221 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004222 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004223 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004224 CopyDestroyCache.insert(flag);
4225 S = "static void __Block_byref_id_object_copy_";
4226 S += utostr(flag);
4227 S += "(void *dst, void *src) {\n";
4228
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004229 // offset into the object pointer is computed as:
4230 // void * + void* + int + int + void* + void *
4231 unsigned IntSize =
4232 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4233 unsigned VoidPtrSize =
4234 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4235
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004236 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004237 S += " _Block_object_assign((char*)dst + ";
4238 S += utostr(offset);
4239 S += ", *(void * *) ((char*)src + ";
4240 S += utostr(offset);
4241 S += "), ";
4242 S += utostr(flag);
4243 S += ");\n}\n";
4244
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004245 S += "static void __Block_byref_id_object_dispose_";
4246 S += utostr(flag);
4247 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004248 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4249 S += utostr(offset);
4250 S += "), ";
4251 S += utostr(flag);
4252 S += ");\n}\n";
4253 return S;
4254}
4255
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004256/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4257/// the declaration into:
4258/// struct __Block_byref_ND {
4259/// void *__isa; // NULL for everything except __weak pointers
4260/// struct __Block_byref_ND *__forwarding;
4261/// int32_t __flags;
4262/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004263/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4264/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004265/// typex ND;
4266/// };
4267///
4268/// It then replaces declaration of ND variable with:
4269/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4270/// __size=sizeof(struct __Block_byref_ND),
4271/// ND=initializer-if-any};
4272///
4273///
4274void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004275 // Insert declaration for the function in which block literal is
4276 // used.
4277 if (CurFunctionDeclToDeclareForBlock)
4278 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004279 int flag = 0;
4280 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004281 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004282 if (DeclLoc.isInvalid())
4283 // If type location is missing, it is because of missing type (a warning).
4284 // Use variable's location which is good for this case.
4285 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004286 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004287 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004288 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004289 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004290 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004291 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004292 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004293 ByrefType += " {\n";
4294 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004295 RewriteByRefString(ByrefType, Name, ND);
4296 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004297 ByrefType += " int __flags;\n";
4298 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004299 // Add void *__Block_byref_id_object_copy;
4300 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004301 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004302 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004303 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004304 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4305 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004306 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004307
4308 QualType T = Ty;
4309 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004310 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004311
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004312 ByrefType += " " + Name + ";\n";
4313 ByrefType += "};\n";
4314 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004315 SourceLocation FunLocStart;
4316 if (CurFunctionDef)
4317 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4318 else {
4319 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4320 FunLocStart = CurMethodDef->getLocStart();
4321 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004322 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004323 if (Ty.isObjCGCWeak()) {
4324 flag |= BLOCK_FIELD_IS_WEAK;
4325 isa = 1;
4326 }
4327
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004328 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004329 flag = BLOCK_BYREF_CALLER;
4330 QualType Ty = ND->getType();
4331 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4332 if (Ty->isBlockPointerType())
4333 flag |= BLOCK_FIELD_IS_BLOCK;
4334 else
4335 flag |= BLOCK_FIELD_IS_OBJECT;
4336 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004337 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004338 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004339 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004340
4341 // struct __Block_byref_ND ND =
4342 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4343 // initializer-if-any};
4344 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004345 unsigned flags = 0;
4346 if (HasCopyAndDispose)
4347 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004348 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004349 ByrefType.clear();
4350 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004351 std::string ForwardingCastType("(");
4352 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004353 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004354 ByrefType += " " + Name + " = {(void*)";
4355 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004356 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004357 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004358 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004359 ByrefType += "sizeof(";
4360 RewriteByRefString(ByrefType, Name, ND);
4361 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004362 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004363 ByrefType += ", __Block_byref_id_object_copy_";
4364 ByrefType += utostr(flag);
4365 ByrefType += ", __Block_byref_id_object_dispose_";
4366 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004367 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004368 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004369 unsigned nameSize = Name.size();
4370 // for block or function pointer declaration. Name is aleady
4371 // part of the declaration.
4372 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4373 nameSize = 1;
4374 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004375 }
4376 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004377 SourceLocation startLoc;
4378 Expr *E = ND->getInit();
4379 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4380 startLoc = ECE->getLParenLoc();
4381 else
4382 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004383 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004384 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004385 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004386 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004387 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004388 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004389 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004390 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004391 ByrefType += "sizeof(";
4392 RewriteByRefString(ByrefType, Name, ND);
4393 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004394 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004395 ByrefType += "__Block_byref_id_object_copy_";
4396 ByrefType += utostr(flag);
4397 ByrefType += ", __Block_byref_id_object_dispose_";
4398 ByrefType += utostr(flag);
4399 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004400 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004401 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004402
4403 // Complete the newly synthesized compound expression by inserting a right
4404 // curly brace before the end of the declaration.
4405 // FIXME: This approach avoids rewriting the initializer expression. It
4406 // also assumes there is only one declarator. For example, the following
4407 // isn't currently supported by this routine (in general):
4408 //
4409 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4410 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004411 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4412 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004413 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4414 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004415 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004416
Benjamin Kramerd999b372010-02-14 14:14:16 +00004417 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004418 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004419 return;
4420}
4421
Mike Stump1eb44332009-09-09 15:08:12 +00004422void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004423 // Add initializers for any closure decl refs.
4424 GetBlockDeclRefExprs(Exp->getBody());
4425 if (BlockDeclRefs.size()) {
4426 // Unique all "by copy" declarations.
4427 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004428 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004429 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4430 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4431 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4432 }
4433 }
Steve Naroff54055232008-10-27 17:20:55 +00004434 // Unique all "by ref" declarations.
4435 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004436 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004437 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4438 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4439 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4440 }
Steve Naroff54055232008-10-27 17:20:55 +00004441 }
4442 // Find any imported blocks...they will need special attention.
4443 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004444 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004445 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004446 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004447 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004448 }
4449}
4450
Chris Lattner5f9e2722011-07-23 10:55:15 +00004451FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004452 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004453 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004454 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4455 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00004456 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004457}
4458
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004459Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004460 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004461 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004462 Blocks.push_back(Exp);
4463
4464 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004465
4466 // Add inner imported variables now used in current block.
4467 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004468 if (!InnerBlockDeclRefs.empty()) {
4469 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004470 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004471 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004472 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004473 // We need to save the copied-in variables in nested
4474 // blocks because it is needed at the end for some of the API generations.
4475 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004476 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4477 BlockDeclRefs.push_back(Exp);
4478 BlockByCopyDeclsPtrSet.insert(VD);
4479 BlockByCopyDecls.push_back(VD);
4480 }
John McCallf4b88a42012-03-10 09:33:50 +00004481 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004482 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4483 BlockDeclRefs.push_back(Exp);
4484 BlockByRefDeclsPtrSet.insert(VD);
4485 BlockByRefDecls.push_back(VD);
4486 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004487 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004488 // Find any imported blocks...they will need special attention.
4489 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004490 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004491 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4492 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4493 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004494 }
4495 InnerDeclRefsCount.push_back(countOfInnerDecls);
4496
Steve Narofffa15fd92008-10-28 20:29:00 +00004497 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004498
Steve Narofffa15fd92008-10-28 20:29:00 +00004499 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004500 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004501 else if (CurMethodDef)
4502 BuildUniqueMethodName(FuncName, CurMethodDef);
4503 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004504 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004505
Steve Narofffa15fd92008-10-28 20:29:00 +00004506 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004507
Steve Narofffa15fd92008-10-28 20:29:00 +00004508 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4509 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004510
Steve Narofffa15fd92008-10-28 20:29:00 +00004511 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004512 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4513 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004514
4515 FunctionDecl *FD;
4516 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004517
Steve Narofffa15fd92008-10-28 20:29:00 +00004518 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004519 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004520 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCallf89e55a2010-11-18 06:31:45 +00004521 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004522
Chris Lattner5f9e2722011-07-23 10:55:15 +00004523 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004524
Steve Narofffdc03722008-10-29 21:23:59 +00004525 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004526 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004527 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4528 VK_LValue, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004529 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004530 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004531 InitExprs.push_back(castExpr);
4532
Steve Naroff01aec112009-12-06 21:14:13 +00004533 // Initialize the block descriptor.
4534 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004536 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4537 SourceLocation(), SourceLocation(),
4538 &Context->Idents.get(DescData.c_str()),
4539 Context->VoidPtrTy, 0,
4540 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00004541 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004542 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCallf89e55a2010-11-18 06:31:45 +00004543 Context->VoidPtrTy,
4544 VK_LValue,
4545 SourceLocation()),
4546 UO_AddrOf,
4547 Context->getPointerType(Context->VoidPtrTy),
4548 VK_RValue, OK_Ordinary,
4549 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004550 InitExprs.push_back(DescRefExpr);
4551
Steve Narofffa15fd92008-10-28 20:29:00 +00004552 // Add initializers for any closure decl refs.
4553 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004554 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004555 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004556 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004557 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004558 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004559 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004560 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004561 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004562 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004563 if (HasLocalVariableExternalStorage(*I)) {
4564 QualType QT = (*I)->getType();
4565 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004566 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4567 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004568 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004569 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004570 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004571 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004572 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004573 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004574 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004575 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004576 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004577 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004578 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004579 if (HasLocalVariableExternalStorage(*I)) {
4580 QualType QT = (*I)->getType();
4581 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004582 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4583 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004584 }
4585
Steve Narofffa15fd92008-10-28 20:29:00 +00004586 }
Mike Stump1eb44332009-09-09 15:08:12 +00004587 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004588 }
4589 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004590 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004591 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004592 ValueDecl *ND = (*I);
4593 std::string Name(ND->getNameAsString());
4594 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004595 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004596 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4597 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004598 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004599 SourceLocation(), SourceLocation(),
4600 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004601 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4602 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4603
Daniel Dunbar4087f272010-08-17 22:39:59 +00004604 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004605 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004606 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004607 bool isNestedCapturedVar = false;
4608 if (block)
4609 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4610 ce = block->capture_end(); ci != ce; ++ci) {
4611 const VarDecl *variable = ci->getVariable();
4612 if (variable == ND && ci->isNested()) {
4613 assert (ci->isByRef() &&
4614 "SynthBlockInitExpr - captured block variable is not byref");
4615 isNestedCapturedVar = true;
4616 break;
4617 }
4618 }
4619 // captured nested byref variable has its address passed. Do not take
4620 // its address again.
4621 if (!isNestedCapturedVar)
4622 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004623 Context->getPointerType(Exp->getType()),
4624 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004625 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004626 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004627 }
4628 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004629 if (ImportedBlockDecls.size()) {
4630 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4631 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004632 unsigned IntSize =
4633 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004634 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4635 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004636 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004637 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004638 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00004639 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004640 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004641 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004642 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004643 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004644 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004645 BlockDeclRefs.clear();
4646 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004647 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004648 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004649 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004650 ImportedBlockDecls.clear();
4651 return NewRep;
4652}
4653
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004654bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4655 if (const ObjCForCollectionStmt * CS =
4656 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4657 return CS->getElement() == DS;
4658 return false;
4659}
4660
Steve Narofffa15fd92008-10-28 20:29:00 +00004661//===----------------------------------------------------------------------===//
4662// Function Body / Expression rewriting
4663//===----------------------------------------------------------------------===//
4664
4665Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004666 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004667 isa<DoStmt>(S) || isa<ForStmt>(S))
4668 Stmts.push_back(S);
4669 else if (isa<ObjCForCollectionStmt>(S)) {
4670 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004671 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004672 }
Mike Stump1eb44332009-09-09 15:08:12 +00004673
John McCall4b9c2d22011-11-06 09:01:30 +00004674 // Pseudo-object operations and ivar references need special
4675 // treatment because we're going to recursively rewrite them.
4676 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4677 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4678 return RewritePropertyOrImplicitSetter(PseudoOp);
4679 } else {
4680 return RewritePropertyOrImplicitGetter(PseudoOp);
4681 }
4682 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4683 return RewriteObjCIvarRefExpr(IvarRefExpr);
4684 }
4685
Steve Narofffa15fd92008-10-28 20:29:00 +00004686 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004687
Steve Narofffa15fd92008-10-28 20:29:00 +00004688 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004689 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004690 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004691 Stmt *childStmt = (*CI);
4692 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004693 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004694 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004695 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004696 }
Mike Stump1eb44332009-09-09 15:08:12 +00004697
Steve Narofffa15fd92008-10-28 20:29:00 +00004698 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004699 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004700 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4701 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004702 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004703 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004704 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004705 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004706 Stmt *SaveCurrentBody = CurrentBody;
4707 CurrentBody = BE->getBody();
4708 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004709 // block literal on rhs of a property-dot-sytax assignment
4710 // must be replaced by its synthesize ast so getRewrittenText
4711 // works as expected. In this case, what actually ends up on RHS
4712 // is the blockTranscribed which is the helper function for the
4713 // block literal; as in: self.c = ^() {[ace ARR];};
4714 bool saveDisableReplaceStmt = DisableReplaceStmt;
4715 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004716 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004717 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004718 CurrentBody = SaveCurrentBody;
4719 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004720 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004721 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004722 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004723 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004725 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4726
Steve Narofffa15fd92008-10-28 20:29:00 +00004727 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004728 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004729 return blockTranscribed;
4730 }
4731 // Handle specific things.
4732 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4733 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004734
Steve Narofffa15fd92008-10-28 20:29:00 +00004735 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4736 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004737
Steve Narofffa15fd92008-10-28 20:29:00 +00004738 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4739 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004740
Steve Narofffa15fd92008-10-28 20:29:00 +00004741 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004742#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004743 // Before we rewrite it, put the original message expression in a comment.
4744 SourceLocation startLoc = MessExpr->getLocStart();
4745 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004746
Steve Narofffa15fd92008-10-28 20:29:00 +00004747 const char *startBuf = SM->getCharacterData(startLoc);
4748 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004749
Steve Narofffa15fd92008-10-28 20:29:00 +00004750 std::string messString;
4751 messString += "// ";
4752 messString.append(startBuf, endBuf-startBuf+1);
4753 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004754
4755 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004756 // InsertText(clang::SourceLocation, char const*, unsigned int).
4757 // InsertText(startLoc, messString.c_str(), messString.size());
4758 // Tried this, but it didn't work either...
4759 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004760#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004761 return RewriteMessageExpr(MessExpr);
4762 }
Mike Stump1eb44332009-09-09 15:08:12 +00004763
Steve Narofffa15fd92008-10-28 20:29:00 +00004764 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4765 return RewriteObjCTryStmt(StmtTry);
4766
4767 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4768 return RewriteObjCSynchronizedStmt(StmtTry);
4769
4770 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4771 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004772
Steve Narofffa15fd92008-10-28 20:29:00 +00004773 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4774 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004775
4776 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004777 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004778 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004779 OrigStmtRange.getEnd());
4780 if (BreakStmt *StmtBreakStmt =
4781 dyn_cast<BreakStmt>(S))
4782 return RewriteBreakStmt(StmtBreakStmt);
4783 if (ContinueStmt *StmtContinueStmt =
4784 dyn_cast<ContinueStmt>(S))
4785 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004786
4787 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004788 // and cast exprs.
4789 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4790 // FIXME: What we're doing here is modifying the type-specifier that
4791 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004792 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004793 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4794 // the context of an ObjCForCollectionStmt. For example:
4795 // NSArray *someArray;
4796 // for (id <FooProtocol> index in someArray) ;
4797 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4798 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004799 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004800 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004801
Steve Narofffa15fd92008-10-28 20:29:00 +00004802 // Blocks rewrite rules.
4803 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4804 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004805 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004806 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004807 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004808 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004809 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004810 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004811 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004812 if (VD->hasAttr<BlocksAttr>()) {
4813 static unsigned uniqueByrefDeclCount = 0;
4814 assert(!BlockByRefDeclNo.count(ND) &&
4815 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4816 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004817 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004818 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004819 else
4820 RewriteTypeOfDecl(VD);
4821 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004822 }
Richard Smith162e1c12011-04-15 14:24:37 +00004823 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004824 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004825 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004826 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004827 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4828 }
4829 }
4830 }
Mike Stump1eb44332009-09-09 15:08:12 +00004831
Steve Narofffa15fd92008-10-28 20:29:00 +00004832 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4833 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004834
4835 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004836 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4837 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004838 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4839 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004840 && "Statement stack mismatch");
4841 Stmts.pop_back();
4842 }
4843 // Handle blocks rewriting.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004844 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4845 ValueDecl *VD = DRE->getDecl();
4846 if (VD->hasAttr<BlocksAttr>())
4847 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004848 if (HasLocalVariableExternalStorage(VD))
4849 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004850 }
4851
Steve Narofffa15fd92008-10-28 20:29:00 +00004852 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004853 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004854 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004855 ReplaceStmt(S, BlockCall);
4856 return BlockCall;
4857 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004858 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004859 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004860 RewriteCastExpr(CE);
4861 }
4862#if 0
4863 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004864 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4865 ICE->getSubExpr(),
4866 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004867 // Get the new text.
4868 std::string SStr;
4869 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004870 Replacement->printPretty(Buf);
Steve Narofffa15fd92008-10-28 20:29:00 +00004871 const std::string &Str = Buf.str();
4872
4873 printf("CAST = %s\n", &Str[0]);
4874 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4875 delete S;
4876 return Replacement;
4877 }
4878#endif
4879 // Return this stmt unmodified.
4880 return S;
4881}
4882
Steve Naroff3d7e7862009-12-05 15:55:59 +00004883void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4884 for (RecordDecl::field_iterator i = RD->field_begin(),
4885 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004886 FieldDecl *FD = *i;
Steve Naroff3d7e7862009-12-05 15:55:59 +00004887 if (isTopLevelBlockPointerType(FD->getType()))
4888 RewriteBlockPointerDecl(FD);
4889 if (FD->getType()->isObjCQualifiedIdType() ||
4890 FD->getType()->isObjCQualifiedInterfaceType())
4891 RewriteObjCQualifiedInterfaceTypes(FD);
4892 }
4893}
4894
Steve Narofffa15fd92008-10-28 20:29:00 +00004895/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4896/// main file of the input.
4897void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004898 switch (D->getKind()) {
4899 case Decl::Function: {
4900 FunctionDecl *FD = cast<FunctionDecl>(D);
4901 if (FD->isOverloadedOperator())
4902 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004903
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004904 // Since function prototypes don't have ParmDecl's, we check the function
4905 // prototype. This enables us to rewrite function declarations and
4906 // definitions using the same code.
4907 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004908
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004909 if (!FD->isThisDeclarationADefinition())
4910 break;
4911
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004912 // FIXME: If this should support Obj-C++, support CXXTryStmt
4913 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4914 CurFunctionDef = FD;
4915 CurFunctionDeclToDeclareForBlock = FD;
4916 CurrentBody = Body;
4917 Body =
4918 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4919 FD->setBody(Body);
4920 CurrentBody = 0;
4921 if (PropParentMap) {
4922 delete PropParentMap;
4923 PropParentMap = 0;
4924 }
4925 // This synthesizes and inserts the block "impl" struct, invoke function,
4926 // and any copy/dispose helper functions.
4927 InsertBlockLiteralsWithinFunction(FD);
4928 CurFunctionDef = 0;
4929 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004930 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004931 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004932 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004933 case Decl::ObjCMethod: {
4934 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4935 if (CompoundStmt *Body = MD->getCompoundBody()) {
4936 CurMethodDef = MD;
4937 CurrentBody = Body;
4938 Body =
4939 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4940 MD->setBody(Body);
4941 CurrentBody = 0;
4942 if (PropParentMap) {
4943 delete PropParentMap;
4944 PropParentMap = 0;
4945 }
4946 InsertBlockLiteralsWithinMethod(MD);
4947 CurMethodDef = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004948 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004949 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004950 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004951 case Decl::ObjCImplementation: {
4952 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4953 ClassImplementation.push_back(CI);
4954 break;
4955 }
4956 case Decl::ObjCCategoryImpl: {
4957 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4958 CategoryImplementation.push_back(CI);
4959 break;
4960 }
4961 case Decl::Var: {
4962 VarDecl *VD = cast<VarDecl>(D);
4963 RewriteObjCQualifiedInterfaceTypes(VD);
4964 if (isTopLevelBlockPointerType(VD->getType()))
4965 RewriteBlockPointerDecl(VD);
4966 else if (VD->getType()->isFunctionPointerType()) {
4967 CheckFunctionPointerDecl(VD->getType(), VD);
4968 if (VD->getInit()) {
4969 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4970 RewriteCastExpr(CE);
4971 }
4972 }
4973 } else if (VD->getType()->isRecordType()) {
4974 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4975 if (RD->isCompleteDefinition())
4976 RewriteRecordBody(RD);
4977 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004978 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004979 GlobalVarDecl = VD;
4980 CurrentBody = VD->getInit();
4981 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4982 CurrentBody = 0;
4983 if (PropParentMap) {
4984 delete PropParentMap;
4985 PropParentMap = 0;
4986 }
4987 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4988 GlobalVarDecl = 0;
4989
4990 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004991 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004992 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004993 }
4994 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004995 break;
4996 }
4997 case Decl::TypeAlias:
4998 case Decl::Typedef: {
4999 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5000 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5001 RewriteBlockPointerDecl(TD);
5002 else if (TD->getUnderlyingType()->isFunctionPointerType())
5003 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5004 }
5005 break;
5006 }
5007 case Decl::CXXRecord:
5008 case Decl::Record: {
5009 RecordDecl *RD = cast<RecordDecl>(D);
5010 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005011 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005012 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005013 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005014 default:
5015 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005016 }
5017 // Nothing yet.
5018}
5019
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005020void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005021 if (Diags.hasErrorOccurred())
5022 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005023
Steve Narofffa15fd92008-10-28 20:29:00 +00005024 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005025
Steve Naroff621edce2009-04-29 16:37:50 +00005026 // Here's a great place to add any extra declarations that may be needed.
5027 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005028 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005029 E = ProtocolExprDecls.end(); I != E; ++I)
5030 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5031
Benjamin Kramerd999b372010-02-14 14:14:16 +00005032 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005033 if (ClassImplementation.size() || CategoryImplementation.size())
5034 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005035
Steve Narofffa15fd92008-10-28 20:29:00 +00005036 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5037 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005038 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005039 Rewrite.getRewriteBufferFor(MainFileID)) {
5040 //printf("Changed:\n");
5041 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5042 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005043 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005044 }
Steve Narofface66252008-11-13 20:07:04 +00005045
Steve Naroff621edce2009-04-29 16:37:50 +00005046 if (ClassImplementation.size() || CategoryImplementation.size() ||
5047 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005048 // Rewrite Objective-c meta data*
5049 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005050 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005051 // Emit metadata.
5052 *OutFile << ResultStr;
5053 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005054 OutFile->flush();
5055}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005056
5057void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5058 InitializeCommon(context);
5059
5060 // declaring objc_selector outside the parameter list removes a silly
5061 // scope related warning...
5062 if (IsHeader)
5063 Preamble = "#pragma once\n";
5064 Preamble += "struct objc_selector; struct objc_class;\n";
5065 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5066 Preamble += "struct objc_object *superClass; ";
5067 if (LangOpts.MicrosoftExt) {
5068 // Add a constructor for creating temporary objects.
5069 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5070 ": ";
5071 Preamble += "object(o), superClass(s) {} ";
5072 }
5073 Preamble += "};\n";
5074 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5075 Preamble += "typedef struct objc_object Protocol;\n";
5076 Preamble += "#define _REWRITER_typedef_Protocol\n";
5077 Preamble += "#endif\n";
5078 if (LangOpts.MicrosoftExt) {
5079 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5080 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5081 } else
5082 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5083 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5084 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5085 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5086 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5087 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5088 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5089 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5090 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5091 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5092 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5093 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5094 Preamble += "(const char *);\n";
5095 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5096 Preamble += "(struct objc_class *);\n";
5097 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5098 Preamble += "(const char *);\n";
5099 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5100 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5101 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5102 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5103 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5104 Preamble += "(struct objc_class *, struct objc_object *);\n";
5105 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00005106 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5107 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005108 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5109 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5110 Preamble += "struct __objcFastEnumerationState {\n\t";
5111 Preamble += "unsigned long state;\n\t";
5112 Preamble += "void **itemsPtr;\n\t";
5113 Preamble += "unsigned long *mutationsPtr;\n\t";
5114 Preamble += "unsigned long extra[5];\n};\n";
5115 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5116 Preamble += "#define __FASTENUMERATIONSTATE\n";
5117 Preamble += "#endif\n";
5118 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5119 Preamble += "struct __NSConstantStringImpl {\n";
5120 Preamble += " int *isa;\n";
5121 Preamble += " int flags;\n";
5122 Preamble += " char *str;\n";
5123 Preamble += " long length;\n";
5124 Preamble += "};\n";
5125 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5126 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5127 Preamble += "#else\n";
5128 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5129 Preamble += "#endif\n";
5130 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5131 Preamble += "#endif\n";
5132 // Blocks preamble.
5133 Preamble += "#ifndef BLOCK_IMPL\n";
5134 Preamble += "#define BLOCK_IMPL\n";
5135 Preamble += "struct __block_impl {\n";
5136 Preamble += " void *isa;\n";
5137 Preamble += " int Flags;\n";
5138 Preamble += " int Reserved;\n";
5139 Preamble += " void *FuncPtr;\n";
5140 Preamble += "};\n";
5141 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5142 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5143 Preamble += "extern \"C\" __declspec(dllexport) "
5144 "void _Block_object_assign(void *, const void *, const int);\n";
5145 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5146 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5147 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5148 Preamble += "#else\n";
5149 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5150 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5151 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5152 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5153 Preamble += "#endif\n";
5154 Preamble += "#endif\n";
5155 if (LangOpts.MicrosoftExt) {
5156 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5157 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5158 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5159 Preamble += "#define __attribute__(X)\n";
5160 Preamble += "#endif\n";
5161 Preamble += "#define __weak\n";
5162 }
5163 else {
5164 Preamble += "#define __block\n";
5165 Preamble += "#define __weak\n";
5166 }
5167 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5168 // as this avoids warning in any 64bit/32bit compilation model.
5169 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5170}
5171
5172/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5173/// ivar offset.
5174void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5175 std::string &Result) {
5176 if (ivar->isBitField()) {
5177 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5178 // place all bitfields at offset 0.
5179 Result += "0";
5180 } else {
5181 Result += "__OFFSETOFIVAR__(struct ";
5182 Result += ivar->getContainingInterface()->getNameAsString();
5183 if (LangOpts.MicrosoftExt)
5184 Result += "_IMPL";
5185 Result += ", ";
5186 Result += ivar->getNameAsString();
5187 Result += ")";
5188 }
5189}
5190
5191/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5192void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5193 ObjCProtocolDecl *PDecl, StringRef prefix,
5194 StringRef ClassName, std::string &Result) {
5195 static bool objc_protocol_methods = false;
5196
5197 // Output struct protocol_methods holder of method selector and type.
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005198 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005199 /* struct protocol_methods {
5200 SEL _cmd;
5201 char *method_types;
5202 }
5203 */
5204 Result += "\nstruct _protocol_methods {\n";
5205 Result += "\tstruct objc_selector *_cmd;\n";
5206 Result += "\tchar *method_types;\n";
5207 Result += "};\n";
5208
5209 objc_protocol_methods = true;
5210 }
5211 // Do not synthesize the protocol more than once.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005212 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005213 return;
5214
Douglas Gregor61cc2962012-01-02 02:00:30 +00005215 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5216 PDecl = Def;
5217
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005218 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5219 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5220 PDecl->instmeth_end());
5221 /* struct _objc_protocol_method_list {
5222 int protocol_method_count;
5223 struct protocol_methods protocols[];
5224 }
5225 */
5226 Result += "\nstatic struct {\n";
5227 Result += "\tint protocol_method_count;\n";
5228 Result += "\tstruct _protocol_methods protocol_methods[";
5229 Result += utostr(NumMethods);
5230 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5231 Result += PDecl->getNameAsString();
5232 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5233 "{\n\t" + utostr(NumMethods) + "\n";
5234
5235 // Output instance methods declared in this protocol.
5236 for (ObjCProtocolDecl::instmeth_iterator
5237 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5238 I != E; ++I) {
5239 if (I == PDecl->instmeth_begin())
5240 Result += "\t ,{{(struct objc_selector *)\"";
5241 else
5242 Result += "\t ,{(struct objc_selector *)\"";
5243 Result += (*I)->getSelector().getAsString();
5244 std::string MethodTypeString;
5245 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5246 Result += "\", \"";
5247 Result += MethodTypeString;
5248 Result += "\"}\n";
5249 }
5250 Result += "\t }\n};\n";
5251 }
5252
5253 // Output class methods declared in this protocol.
5254 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5255 PDecl->classmeth_end());
5256 if (NumMethods > 0) {
5257 /* struct _objc_protocol_method_list {
5258 int protocol_method_count;
5259 struct protocol_methods protocols[];
5260 }
5261 */
5262 Result += "\nstatic struct {\n";
5263 Result += "\tint protocol_method_count;\n";
5264 Result += "\tstruct _protocol_methods protocol_methods[";
5265 Result += utostr(NumMethods);
5266 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5267 Result += PDecl->getNameAsString();
5268 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5269 "{\n\t";
5270 Result += utostr(NumMethods);
5271 Result += "\n";
5272
5273 // Output instance methods declared in this protocol.
5274 for (ObjCProtocolDecl::classmeth_iterator
5275 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5276 I != E; ++I) {
5277 if (I == PDecl->classmeth_begin())
5278 Result += "\t ,{{(struct objc_selector *)\"";
5279 else
5280 Result += "\t ,{(struct objc_selector *)\"";
5281 Result += (*I)->getSelector().getAsString();
5282 std::string MethodTypeString;
5283 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5284 Result += "\", \"";
5285 Result += MethodTypeString;
5286 Result += "\"}\n";
5287 }
5288 Result += "\t }\n};\n";
5289 }
5290
5291 // Output:
5292 /* struct _objc_protocol {
5293 // Objective-C 1.0 extensions
5294 struct _objc_protocol_extension *isa;
5295 char *protocol_name;
5296 struct _objc_protocol **protocol_list;
5297 struct _objc_protocol_method_list *instance_methods;
5298 struct _objc_protocol_method_list *class_methods;
5299 };
5300 */
5301 static bool objc_protocol = false;
5302 if (!objc_protocol) {
5303 Result += "\nstruct _objc_protocol {\n";
5304 Result += "\tstruct _objc_protocol_extension *isa;\n";
5305 Result += "\tchar *protocol_name;\n";
5306 Result += "\tstruct _objc_protocol **protocol_list;\n";
5307 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5308 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5309 Result += "};\n";
5310
5311 objc_protocol = true;
5312 }
5313
5314 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5315 Result += PDecl->getNameAsString();
5316 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5317 "{\n\t0, \"";
5318 Result += PDecl->getNameAsString();
5319 Result += "\", 0, ";
5320 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5321 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5322 Result += PDecl->getNameAsString();
5323 Result += ", ";
5324 }
5325 else
5326 Result += "0, ";
5327 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5328 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5329 Result += PDecl->getNameAsString();
5330 Result += "\n";
5331 }
5332 else
5333 Result += "0\n";
5334 Result += "};\n";
5335
5336 // Mark this protocol as having been generated.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005337 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005338 llvm_unreachable("protocol already synthesized");
5339
5340}
5341
5342void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5343 const ObjCList<ObjCProtocolDecl> &Protocols,
5344 StringRef prefix, StringRef ClassName,
5345 std::string &Result) {
5346 if (Protocols.empty()) return;
5347
5348 for (unsigned i = 0; i != Protocols.size(); i++)
5349 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5350
5351 // Output the top lovel protocol meta-data for the class.
5352 /* struct _objc_protocol_list {
5353 struct _objc_protocol_list *next;
5354 int protocol_count;
5355 struct _objc_protocol *class_protocols[];
5356 }
5357 */
5358 Result += "\nstatic struct {\n";
5359 Result += "\tstruct _objc_protocol_list *next;\n";
5360 Result += "\tint protocol_count;\n";
5361 Result += "\tstruct _objc_protocol *class_protocols[";
5362 Result += utostr(Protocols.size());
5363 Result += "];\n} _OBJC_";
5364 Result += prefix;
5365 Result += "_PROTOCOLS_";
5366 Result += ClassName;
5367 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5368 "{\n\t0, ";
5369 Result += utostr(Protocols.size());
5370 Result += "\n";
5371
5372 Result += "\t,{&_OBJC_PROTOCOL_";
5373 Result += Protocols[0]->getNameAsString();
5374 Result += " \n";
5375
5376 for (unsigned i = 1; i != Protocols.size(); i++) {
5377 Result += "\t ,&_OBJC_PROTOCOL_";
5378 Result += Protocols[i]->getNameAsString();
5379 Result += "\n";
5380 }
5381 Result += "\t }\n};\n";
5382}
5383
5384void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5385 std::string &Result) {
5386 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5387
5388 // Explicitly declared @interface's are already synthesized.
5389 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005390 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005391 // produce correct synthesis as yet.
5392 RewriteObjCInternalStruct(CDecl, Result);
5393 }
5394
5395 // Build _objc_ivar_list metadata for classes ivars if needed
5396 unsigned NumIvars = !IDecl->ivar_empty()
5397 ? IDecl->ivar_size()
5398 : (CDecl ? CDecl->ivar_size() : 0);
5399 if (NumIvars > 0) {
5400 static bool objc_ivar = false;
5401 if (!objc_ivar) {
5402 /* struct _objc_ivar {
5403 char *ivar_name;
5404 char *ivar_type;
5405 int ivar_offset;
5406 };
5407 */
5408 Result += "\nstruct _objc_ivar {\n";
5409 Result += "\tchar *ivar_name;\n";
5410 Result += "\tchar *ivar_type;\n";
5411 Result += "\tint ivar_offset;\n";
5412 Result += "};\n";
5413
5414 objc_ivar = true;
5415 }
5416
5417 /* struct {
5418 int ivar_count;
5419 struct _objc_ivar ivar_list[nIvars];
5420 };
5421 */
5422 Result += "\nstatic struct {\n";
5423 Result += "\tint ivar_count;\n";
5424 Result += "\tstruct _objc_ivar ivar_list[";
5425 Result += utostr(NumIvars);
5426 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5427 Result += IDecl->getNameAsString();
5428 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5429 "{\n\t";
5430 Result += utostr(NumIvars);
5431 Result += "\n";
5432
5433 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5434 SmallVector<ObjCIvarDecl *, 8> IVars;
5435 if (!IDecl->ivar_empty()) {
5436 for (ObjCInterfaceDecl::ivar_iterator
5437 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5438 IV != IVEnd; ++IV)
David Blaikie581deb32012-06-06 20:45:41 +00005439 IVars.push_back(*IV);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005440 IVI = IDecl->ivar_begin();
5441 IVE = IDecl->ivar_end();
5442 } else {
5443 IVI = CDecl->ivar_begin();
5444 IVE = CDecl->ivar_end();
5445 }
5446 Result += "\t,{{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005447 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005448 Result += "\", \"";
5449 std::string TmpString, StrEncoding;
David Blaikie581deb32012-06-06 20:45:41 +00005450 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005451 QuoteDoublequotes(TmpString, StrEncoding);
5452 Result += StrEncoding;
5453 Result += "\", ";
David Blaikie581deb32012-06-06 20:45:41 +00005454 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005455 Result += "}\n";
5456 for (++IVI; IVI != IVE; ++IVI) {
5457 Result += "\t ,{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005458 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005459 Result += "\", \"";
5460 std::string TmpString, StrEncoding;
David Blaikie581deb32012-06-06 20:45:41 +00005461 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005462 QuoteDoublequotes(TmpString, StrEncoding);
5463 Result += StrEncoding;
5464 Result += "\", ";
David Blaikie581deb32012-06-06 20:45:41 +00005465 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005466 Result += "}\n";
5467 }
5468
5469 Result += "\t }\n};\n";
5470 }
5471
5472 // Build _objc_method_list for class's instance methods if needed
5473 SmallVector<ObjCMethodDecl *, 32>
5474 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5475
5476 // If any of our property implementations have associated getters or
5477 // setters, produce metadata for them as well.
5478 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5479 PropEnd = IDecl->propimpl_end();
5480 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00005481 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005482 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005483 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005484 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005485 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005486 if (!PD)
5487 continue;
5488 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5489 if (!Getter->isDefined())
5490 InstanceMethods.push_back(Getter);
5491 if (PD->isReadOnly())
5492 continue;
5493 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5494 if (!Setter->isDefined())
5495 InstanceMethods.push_back(Setter);
5496 }
5497 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5498 true, "", IDecl->getName(), Result);
5499
5500 // Build _objc_method_list for class's class methods if needed
5501 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5502 false, "", IDecl->getName(), Result);
5503
5504 // Protocols referenced in class declaration?
5505 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5506 "CLASS", CDecl->getName(), Result);
5507
5508 // Declaration of class/meta-class metadata
5509 /* struct _objc_class {
5510 struct _objc_class *isa; // or const char *root_class_name when metadata
5511 const char *super_class_name;
5512 char *name;
5513 long version;
5514 long info;
5515 long instance_size;
5516 struct _objc_ivar_list *ivars;
5517 struct _objc_method_list *methods;
5518 struct objc_cache *cache;
5519 struct objc_protocol_list *protocols;
5520 const char *ivar_layout;
5521 struct _objc_class_ext *ext;
5522 };
5523 */
5524 static bool objc_class = false;
5525 if (!objc_class) {
5526 Result += "\nstruct _objc_class {\n";
5527 Result += "\tstruct _objc_class *isa;\n";
5528 Result += "\tconst char *super_class_name;\n";
5529 Result += "\tchar *name;\n";
5530 Result += "\tlong version;\n";
5531 Result += "\tlong info;\n";
5532 Result += "\tlong instance_size;\n";
5533 Result += "\tstruct _objc_ivar_list *ivars;\n";
5534 Result += "\tstruct _objc_method_list *methods;\n";
5535 Result += "\tstruct objc_cache *cache;\n";
5536 Result += "\tstruct _objc_protocol_list *protocols;\n";
5537 Result += "\tconst char *ivar_layout;\n";
5538 Result += "\tstruct _objc_class_ext *ext;\n";
5539 Result += "};\n";
5540 objc_class = true;
5541 }
5542
5543 // Meta-class metadata generation.
5544 ObjCInterfaceDecl *RootClass = 0;
5545 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5546 while (SuperClass) {
5547 RootClass = SuperClass;
5548 SuperClass = SuperClass->getSuperClass();
5549 }
5550 SuperClass = CDecl->getSuperClass();
5551
5552 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5553 Result += CDecl->getNameAsString();
5554 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5555 "{\n\t(struct _objc_class *)\"";
5556 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5557 Result += "\"";
5558
5559 if (SuperClass) {
5560 Result += ", \"";
5561 Result += SuperClass->getNameAsString();
5562 Result += "\", \"";
5563 Result += CDecl->getNameAsString();
5564 Result += "\"";
5565 }
5566 else {
5567 Result += ", 0, \"";
5568 Result += CDecl->getNameAsString();
5569 Result += "\"";
5570 }
5571 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5572 // 'info' field is initialized to CLS_META(2) for metaclass
5573 Result += ", 0,2, sizeof(struct _objc_class), 0";
5574 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5575 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5576 Result += IDecl->getNameAsString();
5577 Result += "\n";
5578 }
5579 else
5580 Result += ", 0\n";
5581 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5582 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5583 Result += CDecl->getNameAsString();
5584 Result += ",0,0\n";
5585 }
5586 else
5587 Result += "\t,0,0,0,0\n";
5588 Result += "};\n";
5589
5590 // class metadata generation.
5591 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5592 Result += CDecl->getNameAsString();
5593 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5594 "{\n\t&_OBJC_METACLASS_";
5595 Result += CDecl->getNameAsString();
5596 if (SuperClass) {
5597 Result += ", \"";
5598 Result += SuperClass->getNameAsString();
5599 Result += "\", \"";
5600 Result += CDecl->getNameAsString();
5601 Result += "\"";
5602 }
5603 else {
5604 Result += ", 0, \"";
5605 Result += CDecl->getNameAsString();
5606 Result += "\"";
5607 }
5608 // 'info' field is initialized to CLS_CLASS(1) for class
5609 Result += ", 0,1";
5610 if (!ObjCSynthesizedStructs.count(CDecl))
5611 Result += ",0";
5612 else {
5613 // class has size. Must synthesize its size.
5614 Result += ",sizeof(struct ";
5615 Result += CDecl->getNameAsString();
5616 if (LangOpts.MicrosoftExt)
5617 Result += "_IMPL";
5618 Result += ")";
5619 }
5620 if (NumIvars > 0) {
5621 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5622 Result += CDecl->getNameAsString();
5623 Result += "\n\t";
5624 }
5625 else
5626 Result += ",0";
5627 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5628 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5629 Result += CDecl->getNameAsString();
5630 Result += ", 0\n\t";
5631 }
5632 else
5633 Result += ",0,0";
5634 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5635 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5636 Result += CDecl->getNameAsString();
5637 Result += ", 0,0\n";
5638 }
5639 else
5640 Result += ",0,0,0\n";
5641 Result += "};\n";
5642}
5643
5644void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5645 int ClsDefCount = ClassImplementation.size();
5646 int CatDefCount = CategoryImplementation.size();
5647
5648 // For each implemented class, write out all its meta data.
5649 for (int i = 0; i < ClsDefCount; i++)
5650 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5651
5652 // For each implemented category, write out all its meta data.
5653 for (int i = 0; i < CatDefCount; i++)
5654 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5655
5656 // Write objc_symtab metadata
5657 /*
5658 struct _objc_symtab
5659 {
5660 long sel_ref_cnt;
5661 SEL *refs;
5662 short cls_def_cnt;
5663 short cat_def_cnt;
5664 void *defs[cls_def_cnt + cat_def_cnt];
5665 };
5666 */
5667
5668 Result += "\nstruct _objc_symtab {\n";
5669 Result += "\tlong sel_ref_cnt;\n";
5670 Result += "\tSEL *refs;\n";
5671 Result += "\tshort cls_def_cnt;\n";
5672 Result += "\tshort cat_def_cnt;\n";
5673 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5674 Result += "};\n\n";
5675
5676 Result += "static struct _objc_symtab "
5677 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5678 Result += "\t0, 0, " + utostr(ClsDefCount)
5679 + ", " + utostr(CatDefCount) + "\n";
5680 for (int i = 0; i < ClsDefCount; i++) {
5681 Result += "\t,&_OBJC_CLASS_";
5682 Result += ClassImplementation[i]->getNameAsString();
5683 Result += "\n";
5684 }
5685
5686 for (int i = 0; i < CatDefCount; i++) {
5687 Result += "\t,&_OBJC_CATEGORY_";
5688 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5689 Result += "_";
5690 Result += CategoryImplementation[i]->getNameAsString();
5691 Result += "\n";
5692 }
5693
5694 Result += "};\n\n";
5695
5696 // Write objc_module metadata
5697
5698 /*
5699 struct _objc_module {
5700 long version;
5701 long size;
5702 const char *name;
5703 struct _objc_symtab *symtab;
5704 }
5705 */
5706
5707 Result += "\nstruct _objc_module {\n";
5708 Result += "\tlong version;\n";
5709 Result += "\tlong size;\n";
5710 Result += "\tconst char *name;\n";
5711 Result += "\tstruct _objc_symtab *symtab;\n";
5712 Result += "};\n\n";
5713 Result += "static struct _objc_module "
5714 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5715 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5716 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5717 Result += "};\n\n";
5718
5719 if (LangOpts.MicrosoftExt) {
5720 if (ProtocolExprDecls.size()) {
5721 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5722 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5723 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5724 E = ProtocolExprDecls.end(); I != E; ++I) {
5725 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5726 Result += (*I)->getNameAsString();
5727 Result += " = &_OBJC_PROTOCOL_";
5728 Result += (*I)->getNameAsString();
5729 Result += ";\n";
5730 }
5731 Result += "#pragma data_seg(pop)\n\n";
5732 }
5733 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5734 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5735 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5736 Result += "&_OBJC_MODULES;\n";
5737 Result += "#pragma data_seg(pop)\n\n";
5738 }
5739}
5740
5741/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5742/// implementation.
5743void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5744 std::string &Result) {
5745 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5746 // Find category declaration for this implementation.
5747 ObjCCategoryDecl *CDecl;
5748 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5749 CDecl = CDecl->getNextClassCategory())
5750 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5751 break;
5752
5753 std::string FullCategoryName = ClassDecl->getNameAsString();
5754 FullCategoryName += '_';
5755 FullCategoryName += IDecl->getNameAsString();
5756
5757 // Build _objc_method_list for class's instance methods if needed
5758 SmallVector<ObjCMethodDecl *, 32>
5759 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5760
5761 // If any of our property implementations have associated getters or
5762 // setters, produce metadata for them as well.
5763 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5764 PropEnd = IDecl->propimpl_end();
5765 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00005766 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005767 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005768 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005769 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005770 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005771 if (!PD)
5772 continue;
5773 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5774 InstanceMethods.push_back(Getter);
5775 if (PD->isReadOnly())
5776 continue;
5777 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5778 InstanceMethods.push_back(Setter);
5779 }
5780 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5781 true, "CATEGORY_", FullCategoryName.c_str(),
5782 Result);
5783
5784 // Build _objc_method_list for class's class methods if needed
5785 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5786 false, "CATEGORY_", FullCategoryName.c_str(),
5787 Result);
5788
5789 // Protocols referenced in class declaration?
5790 // Null CDecl is case of a category implementation with no category interface
5791 if (CDecl)
5792 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5793 FullCategoryName, Result);
5794 /* struct _objc_category {
5795 char *category_name;
5796 char *class_name;
5797 struct _objc_method_list *instance_methods;
5798 struct _objc_method_list *class_methods;
5799 struct _objc_protocol_list *protocols;
5800 // Objective-C 1.0 extensions
5801 uint32_t size; // sizeof (struct _objc_category)
5802 struct _objc_property_list *instance_properties; // category's own
5803 // @property decl.
5804 };
5805 */
5806
5807 static bool objc_category = false;
5808 if (!objc_category) {
5809 Result += "\nstruct _objc_category {\n";
5810 Result += "\tchar *category_name;\n";
5811 Result += "\tchar *class_name;\n";
5812 Result += "\tstruct _objc_method_list *instance_methods;\n";
5813 Result += "\tstruct _objc_method_list *class_methods;\n";
5814 Result += "\tstruct _objc_protocol_list *protocols;\n";
5815 Result += "\tunsigned int size;\n";
5816 Result += "\tstruct _objc_property_list *instance_properties;\n";
5817 Result += "};\n";
5818 objc_category = true;
5819 }
5820 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5821 Result += FullCategoryName;
5822 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5823 Result += IDecl->getNameAsString();
5824 Result += "\"\n\t, \"";
5825 Result += ClassDecl->getNameAsString();
5826 Result += "\"\n";
5827
5828 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5829 Result += "\t, (struct _objc_method_list *)"
5830 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5831 Result += FullCategoryName;
5832 Result += "\n";
5833 }
5834 else
5835 Result += "\t, 0\n";
5836 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5837 Result += "\t, (struct _objc_method_list *)"
5838 "&_OBJC_CATEGORY_CLASS_METHODS_";
5839 Result += FullCategoryName;
5840 Result += "\n";
5841 }
5842 else
5843 Result += "\t, 0\n";
5844
5845 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5846 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5847 Result += FullCategoryName;
5848 Result += "\n";
5849 }
5850 else
5851 Result += "\t, 0\n";
5852 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5853}
5854
5855// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5856/// class methods.
5857template<typename MethodIterator>
5858void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5859 MethodIterator MethodEnd,
5860 bool IsInstanceMethod,
5861 StringRef prefix,
5862 StringRef ClassName,
5863 std::string &Result) {
5864 if (MethodBegin == MethodEnd) return;
5865
5866 if (!objc_impl_method) {
5867 /* struct _objc_method {
5868 SEL _cmd;
5869 char *method_types;
5870 void *_imp;
5871 }
5872 */
5873 Result += "\nstruct _objc_method {\n";
5874 Result += "\tSEL _cmd;\n";
5875 Result += "\tchar *method_types;\n";
5876 Result += "\tvoid *_imp;\n";
5877 Result += "};\n";
5878
5879 objc_impl_method = true;
5880 }
5881
5882 // Build _objc_method_list for class's methods if needed
5883
5884 /* struct {
5885 struct _objc_method_list *next_method;
5886 int method_count;
5887 struct _objc_method method_list[];
5888 }
5889 */
5890 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5891 Result += "\nstatic struct {\n";
5892 Result += "\tstruct _objc_method_list *next_method;\n";
5893 Result += "\tint method_count;\n";
5894 Result += "\tstruct _objc_method method_list[";
5895 Result += utostr(NumMethods);
5896 Result += "];\n} _OBJC_";
5897 Result += prefix;
5898 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5899 Result += "_METHODS_";
5900 Result += ClassName;
5901 Result += " __attribute__ ((used, section (\"__OBJC, __";
5902 Result += IsInstanceMethod ? "inst" : "cls";
5903 Result += "_meth\")))= ";
5904 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5905
5906 Result += "\t,{{(SEL)\"";
5907 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5908 std::string MethodTypeString;
5909 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5910 Result += "\", \"";
5911 Result += MethodTypeString;
5912 Result += "\", (void *)";
5913 Result += MethodInternalNames[*MethodBegin];
5914 Result += "}\n";
5915 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5916 Result += "\t ,{(SEL)\"";
5917 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5918 std::string MethodTypeString;
5919 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5920 Result += "\", \"";
5921 Result += MethodTypeString;
5922 Result += "\", (void *)";
5923 Result += MethodInternalNames[*MethodBegin];
5924 Result += "}\n";
5925 }
5926 Result += "\t }\n};\n";
5927}
5928
5929Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5930 SourceRange OldRange = IV->getSourceRange();
5931 Expr *BaseExpr = IV->getBase();
5932
5933 // Rewrite the base, but without actually doing replaces.
5934 {
5935 DisableReplaceStmtScope S(*this);
5936 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5937 IV->setBase(BaseExpr);
5938 }
5939
5940 ObjCIvarDecl *D = IV->getDecl();
5941
5942 Expr *Replacement = IV;
5943 if (CurMethodDef) {
5944 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5945 const ObjCInterfaceType *iFaceDecl =
5946 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5947 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5948 // lookup which class implements the instance variable.
5949 ObjCInterfaceDecl *clsDeclared = 0;
5950 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5951 clsDeclared);
5952 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5953
5954 // Synthesize an explicit cast to gain access to the ivar.
5955 std::string RecName = clsDeclared->getIdentifier()->getName();
5956 RecName += "_IMPL";
5957 IdentifierInfo *II = &Context->Idents.get(RecName);
5958 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5959 SourceLocation(), SourceLocation(),
5960 II);
5961 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5962 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5963 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5964 CK_BitCast,
5965 IV->getBase());
5966 // Don't forget the parens to enforce the proper binding.
5967 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5968 OldRange.getEnd(),
5969 castExpr);
5970 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005971 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005972 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5973 IV->getLocation(),
5974 D->getType(),
5975 VK_LValue, OK_Ordinary);
5976 Replacement = ME;
5977 } else {
5978 IV->setBase(PE);
5979 }
5980 }
5981 } else { // we are outside a method.
5982 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5983
5984 // Explicit ivar refs need to have a cast inserted.
5985 // FIXME: consider sharing some of this code with the code above.
5986 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5987 const ObjCInterfaceType *iFaceDecl =
5988 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5989 // lookup which class implements the instance variable.
5990 ObjCInterfaceDecl *clsDeclared = 0;
5991 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5992 clsDeclared);
5993 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5994
5995 // Synthesize an explicit cast to gain access to the ivar.
5996 std::string RecName = clsDeclared->getIdentifier()->getName();
5997 RecName += "_IMPL";
5998 IdentifierInfo *II = &Context->Idents.get(RecName);
5999 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6000 SourceLocation(), SourceLocation(),
6001 II);
6002 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6003 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6004 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6005 CK_BitCast,
6006 IV->getBase());
6007 // Don't forget the parens to enforce the proper binding.
6008 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6009 IV->getBase()->getLocEnd(), castExpr);
6010 // Cannot delete IV->getBase(), since PE points to it.
6011 // Replace the old base with the cast. This is important when doing
6012 // embedded rewrites. For example, [newInv->_container addObject:0].
6013 IV->setBase(PE);
6014 }
6015 }
6016
6017 ReplaceStmtWithRange(IV, Replacement, OldRange);
6018 return Replacement;
6019}