blob: 036b2c88aee4a52c506ada77e961cd56160fad0b [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenekcdf81492012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000023#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/OwningPtr.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Fariborz Jahanianf4609d42010-03-01 23:36:21 +000031
Chris Lattnere99c8322007-10-11 00:43:27 +000032using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000033using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000034
Chris Lattnere99c8322007-10-11 00:43:27 +000035namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000036 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian83077422011-12-08 18:25:15 +000037 protected:
38
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000039 enum {
Nico Weber1879bca2010-11-22 10:26:41 +000040 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000041 block, ... */
42 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
43 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
44 __block variable */
Nico Weber1879bca2010-11-22 10:26:41 +000045 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000046 helpers */
Nico Weber1879bca2010-11-22 10:26:41 +000047 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000048 support routines */
49 BLOCK_BYREF_CURRENT_MAX = 256
50 };
51
52 enum {
53 BLOCK_NEEDS_FREE = (1 << 24),
54 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
55 BLOCK_HAS_CXX_OBJ = (1 << 26),
56 BLOCK_IS_GC = (1 << 27),
57 BLOCK_IS_GLOBAL = (1 << 28),
58 BLOCK_HAS_DESCRIPTOR = (1 << 29)
59 };
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000060 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahanian83077422011-12-08 18:25:15 +000061
Chris Lattner0bd1c972007-10-16 21:07:07 +000062 Rewriter Rewrite;
David Blaikie9c902b52011-09-25 23:23:43 +000063 DiagnosticsEngine &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000064 const LangOptions &LangOpts;
Chris Lattnerc6d91c02007-10-17 22:35:30 +000065 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000066 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000067 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000068 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000069 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000070 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
Fariborz Jahanian8efef602011-12-05 19:50:04 +000072 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
78 unsigned RewriteFailedDiag;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000083
Fariborz Jahanian8efef602011-12-05 19:50:04 +000084 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
Fariborz Jahanian83077422011-12-08 18:25:15 +000087 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000088 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000103 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000104 FunctionDecl *CurFunctionDef;
105 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000107 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000108 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
109 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +0000111 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
113 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000114 SmallVector<Stmt *, 32> Stmts;
115 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +0000116 // Remember all the @protocol(<expr>) expressions.
117 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000118
119 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000120
121 // Block expressions.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000122 SmallVector<BlockExpr *, 32> Blocks;
123 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000124 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000125
John McCall113bee02012-03-10 09:33:50 +0000126 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000127
Steve Naroff677ab3a2008-10-27 17:20:55 +0000128 // Block related declarations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000129 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000133 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000135 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
136
Steve Naroff677ab3a2008-10-27 17:20:55 +0000137 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
138
Steve Naroff22216db2008-12-04 23:50:32 +0000139 // This maps an original source AST to it's rewritten form. This allows
140 // us to avoid rewriting the same node twice (which is very uncommon).
141 // This is needed to support some of the exotic property rewriting.
142 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000143
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000144 // Needed for header files being rewritten
145 bool IsHeader;
146 bool SilenceRewriteMacroWarning;
147 bool objc_impl_method;
148
Steve Naroff08628db2008-12-09 12:56:34 +0000149 bool DisableReplaceStmt;
John McCallfe96e0b2011-11-06 09:01:30 +0000150 class DisableReplaceStmtScope {
151 RewriteObjC &R;
152 bool SavedValue;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000153
John McCallfe96e0b2011-11-06 09:01:30 +0000154 public:
155 DisableReplaceStmtScope(RewriteObjC &R)
156 : R(R), SavedValue(R.DisableReplaceStmt) {
157 R.DisableReplaceStmt = true;
158 }
159 ~DisableReplaceStmtScope() {
160 R.DisableReplaceStmt = SavedValue;
161 }
162 };
Fariborz Jahanian83077422011-12-08 18:25:15 +0000163 void InitializeCommon(ASTContext &context);
Mike Stump11289f42009-09-09 15:08:12 +0000164
Chris Lattnere99c8322007-10-11 00:43:27 +0000165 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000166
Chris Lattner3c799d72007-10-24 17:06:59 +0000167 // Top Level Driver code.
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000168 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000169 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000170 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
171 if (!Class->isThisDeclarationADefinition()) {
172 RewriteForwardClassDecl(D);
173 break;
174 }
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000175 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000176
Douglas Gregorf6102672012-01-01 21:23:57 +0000177 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
178 if (!Proto->isThisDeclarationADefinition()) {
179 RewriteForwardProtocolDecl(D);
180 break;
181 }
182 }
183
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000184 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000185 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000186 return true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000187 }
188 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000189 void HandleDeclInMainFile(Decl *D);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000190 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000191 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000192 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000193
194 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000195
Chris Lattnercf169832009-03-28 04:11:33 +0000196 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000197
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000198 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000199 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000200
Steve Naroff22216db2008-12-04 23:50:32 +0000201 if (ReplacingStmt)
202 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000203
Steve Naroff08628db2008-12-09 12:56:34 +0000204 if (DisableReplaceStmt)
John McCallfe96e0b2011-11-06 09:01:30 +0000205 return;
Steve Naroff08628db2008-12-09 12:56:34 +0000206
Steve Naroff22216db2008-12-04 23:50:32 +0000207 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000208 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000209 ReplacedNodes[Old] = New;
210 return;
211 }
212 if (SilenceRewriteMacroWarning)
213 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000214 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
215 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000216 }
Steve Naroff08628db2008-12-09 12:56:34 +0000217
218 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCallfe96e0b2011-11-06 09:01:30 +0000219 if (DisableReplaceStmt)
220 return;
221
Nick Lewycky508ef2c2010-10-31 21:07:24 +0000222 // Measure the old text.
Steve Naroff08628db2008-12-09 12:56:34 +0000223 int Size = Rewrite.getRangeSize(SrcRange);
224 if (Size == -1) {
225 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
226 << Old->getSourceRange();
227 return;
228 }
229 // Get the new text.
230 std::string SStr;
231 llvm::raw_string_ostream S(SStr);
Richard Smith235341b2012-08-16 03:56:14 +0000232 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000233 const std::string &Str = S.str();
234
235 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000236 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000237 ReplacedNodes[Old] = New;
238 return;
239 }
240 if (SilenceRewriteMacroWarning)
241 return;
242 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
243 << Old->getSourceRange();
244 }
245
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000246 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000247 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000248 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000249 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000250 SilenceRewriteMacroWarning)
251 return;
Mike Stump11289f42009-09-09 15:08:12 +0000252
Chris Lattner1780a852008-01-31 19:42:41 +0000253 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
254 }
Mike Stump11289f42009-09-09 15:08:12 +0000255
Chris Lattner9cc55f52008-01-31 19:51:04 +0000256 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000257 StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000258 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000259 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000260 SilenceRewriteMacroWarning)
261 return;
Mike Stump11289f42009-09-09 15:08:12 +0000262
Chris Lattner9cc55f52008-01-31 19:51:04 +0000263 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
264 }
Mike Stump11289f42009-09-09 15:08:12 +0000265
Chris Lattner3c799d72007-10-24 17:06:59 +0000266 // Syntactic Rewriting.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000267 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000268 void RewriteInclude();
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000269 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000270 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000271 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000272 const std::string &typedefString);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000273 void RewriteImplementations();
Steve Naroffc038b3a2008-12-02 17:36:43 +0000274 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
275 ObjCImplementationDecl *IMD,
276 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000277 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000278 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000279 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
280 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000281 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
282 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000283 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +0000284 ValueDecl *VD, bool def=false);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000285 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
286 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorf6102672012-01-01 21:23:57 +0000287 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000288 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000289 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000290 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000291 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000292 void RewriteBlockPointerType(std::string& Str, QualType Type);
293 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000294 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000295 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000296 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000297 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000298
Chris Lattner3c799d72007-10-24 17:06:59 +0000299 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000300 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner69534692007-10-24 16:57:36 +0000301 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCallfe96e0b2011-11-06 09:01:30 +0000302 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
303 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000304 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000305 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000306 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000307 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000308 void RewriteTryReturnStmts(Stmt *S);
309 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000310 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000311 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000312 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000313 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
314 SourceLocation OrigEnd);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000315 Stmt *RewriteBreakStmt(BreakStmt *S);
316 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000317 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian83077422011-12-08 18:25:15 +0000318
Steve Naroff677ab3a2008-10-27 17:20:55 +0000319 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000320 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000321
Mike Stump11289f42009-09-09 15:08:12 +0000322 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000323 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000324 void RewriteByRefVar(VarDecl *VD);
John McCall113bee02012-03-10 09:33:50 +0000325 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000326 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000327 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000328
329 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
330 std::string &Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +0000331
332 virtual void Initialize(ASTContext &context) = 0;
333
334 // Metadata Rewriting.
335 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
336 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
337 StringRef prefix,
338 StringRef ClassName,
339 std::string &Result) = 0;
340 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
341 std::string &Result) = 0;
342 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
343 StringRef prefix,
344 StringRef ClassName,
345 std::string &Result) = 0;
346 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
347 std::string &Result) = 0;
348
349 // Rewriting ivar access
350 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
351 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
352 std::string &Result) = 0;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000353
Benjamin Kramer474261a2012-06-02 10:20:41 +0000354 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000355 // rewriting routines on the new ASTs.
356 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
357 Expr **args, unsigned nargs,
358 SourceLocation StartLoc=SourceLocation(),
359 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +0000360 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
361 QualType msgSendType,
362 QualType returnType,
363 SmallVectorImpl<QualType> &ArgTypes,
364 SmallVectorImpl<Expr*> &MsgExprs,
365 ObjCMethodDecl *Method);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000366 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
367 SourceLocation StartLoc=SourceLocation(),
368 SourceLocation EndLoc=SourceLocation());
369
370 void SynthCountByEnumWithState(std::string &buf);
371 void SynthMsgSendFunctionDecl();
372 void SynthMsgSendSuperFunctionDecl();
373 void SynthMsgSendStretFunctionDecl();
374 void SynthMsgSendFpretFunctionDecl();
375 void SynthMsgSendSuperStretFunctionDecl();
376 void SynthGetClassFunctionDecl();
377 void SynthGetMetaClassFunctionDecl();
378 void SynthGetSuperClassFunctionDecl();
379 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000380 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000381
382 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump11289f42009-09-09 15:08:12 +0000383 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000384 StringRef funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000385 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000386 StringRef funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000387 std::string SynthesizeBlockImpl(BlockExpr *CE,
388 std::string Tag, std::string Desc);
389 std::string SynthesizeBlockDescriptor(std::string DescTag,
390 std::string ImplTag,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000391 int i, StringRef funcName,
Steve Naroff30484702009-12-06 21:14:13 +0000392 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000393 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000394 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000395 StringRef FunName);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000396 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
397 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000398 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000399
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000400 // Misc. helper routines.
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000401 QualType getProtocolType();
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000402 void WarnAboutReturnGotoStmts(Stmt *S);
403 void HasReturnStmts(Stmt *S, bool &hasReturns);
404 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
405 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
406 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
407
408 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000409 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000410 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000411 void GetInnerBlockDeclRefExprs(Stmt *S,
412 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +0000413 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000414
Steve Naroff677ab3a2008-10-27 17:20:55 +0000415 // We avoid calling Type::isBlockPointerType(), since it operates on the
416 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000417 bool isTopLevelBlockPointerType(QualType T) {
418 return isa<BlockPointerType>(T);
419 }
Mike Stump11289f42009-09-09 15:08:12 +0000420
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +0000421 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
422 /// to a function pointer type and upon success, returns true; false
423 /// otherwise.
424 bool convertBlockPointerToFunctionPointer(QualType &T) {
425 if (isTopLevelBlockPointerType(T)) {
426 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
427 T = Context->getPointerType(BPT->getPointeeType());
428 return true;
429 }
430 return false;
431 }
432
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000433 bool needToScanForQualifiers(QualType T);
434 QualType getSuperStructType();
435 QualType getConstantStringStructType();
436 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
437 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
438
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000439 void convertToUnqualifiedObjCType(QualType &T) {
440 if (T->isObjCQualifiedIdType())
441 T = Context->getObjCIdType();
442 else if (T->isObjCQualifiedClassType())
443 T = Context->getObjCClassType();
444 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +0000445 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
446 if (const ObjCObjectPointerType * OBJPT =
447 T->getAsObjCInterfacePointerType()) {
448 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
449 T = QualType(IFaceT, 0);
450 T = Context->getPointerType(T);
451 }
452 }
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000453 }
454
Steve Naroff677ab3a2008-10-27 17:20:55 +0000455 // FIXME: This predicate seems like it would be useful to add to ASTContext.
456 bool isObjCType(QualType T) {
457 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
458 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000459
Steve Naroff677ab3a2008-10-27 17:20:55 +0000460 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000461
Steve Naroff677ab3a2008-10-27 17:20:55 +0000462 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
463 OCT == Context->getCanonicalType(Context->getObjCClassType()))
464 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000465
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000466 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000467 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000468 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000469 return true;
470 }
471 return false;
472 }
473 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +0000474 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000475 void GetExtentOfArgList(const char *Name, const char *&LParen,
476 const char *&RParen);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000477
Steve Naroffd9803712009-04-29 16:37:50 +0000478 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000479 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000480 if (From[i] == '"')
481 To += "\\\"";
482 else
483 To += From[i];
484 }
485 }
John McCalldb40c7f2010-12-14 08:05:40 +0000486
487 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000488 ArrayRef<QualType> args,
John McCalldb40c7f2010-12-14 08:05:40 +0000489 bool variadic = false) {
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000490 if (result == Context->getObjCInstanceType())
491 result = Context->getObjCIdType();
John McCalldb40c7f2010-12-14 08:05:40 +0000492 FunctionProtoType::ExtProtoInfo fpi;
493 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000494 return Context->getFunctionType(result, args, fpi);
John McCalldb40c7f2010-12-14 08:05:40 +0000495 }
John McCall97513962010-01-15 18:39:57 +0000496
Fariborz Jahanian68e628e2011-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 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000504
505 StringLiteral *getStringLiteral(StringRef Str) {
506 QualType StrType = Context->getConstantArrayType(
507 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
508 0);
509 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
510 /*Pascal=*/false, StrType, SourceLocation());
511 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000512 };
Fariborz Jahanian83077422011-12-08 18:25:15 +0000513
514 class RewriteObjCFragileABI : public RewriteObjC {
515 public:
516
517 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
518 DiagnosticsEngine &D, const LangOptions &LOpts,
519 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
520 D, LOpts,
521 silenceMacroWarn) {}
522
523 ~RewriteObjCFragileABI() {}
524 virtual void Initialize(ASTContext &context);
525
526 // Rewriting metadata
527 template<typename MethodIterator>
528 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
529 MethodIterator MethodEnd,
530 bool IsInstanceMethod,
531 StringRef prefix,
532 StringRef ClassName,
533 std::string &Result);
534 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
535 StringRef prefix,
536 StringRef ClassName,
537 std::string &Result);
538 virtual void RewriteObjCProtocolListMetaData(
539 const ObjCList<ObjCProtocolDecl> &Prots,
540 StringRef prefix, StringRef ClassName, std::string &Result);
541 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
542 std::string &Result);
543 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
544 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
545 std::string &Result);
546
547 // Rewriting ivar
548 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
549 std::string &Result);
550 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
551 };
Chris Lattnere99c8322007-10-11 00:43:27 +0000552}
553
Mike Stump11289f42009-09-09 15:08:12 +0000554void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
555 NamedDecl *D) {
John McCall424cec92011-01-19 06:33:43 +0000556 if (const FunctionProtoType *fproto
Abramo Bagnara6d810632010-12-14 22:11:44 +0000557 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000558 for (FunctionProtoType::param_type_iterator I = fproto->param_type_begin(),
559 E = fproto->param_type_end();
560 I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000561 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000562 // All the args are checked/rewritten. Don't call twice!
563 RewriteBlockPointerDecl(D);
564 break;
565 }
566 }
567}
568
569void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000570 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000571 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000572 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000573}
574
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000575static bool IsHeaderFile(const std::string &Filename) {
576 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000577
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000578 if (DotPos == std::string::npos) {
579 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000580 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000581 }
Mike Stump11289f42009-09-09 15:08:12 +0000582
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000583 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
584 // C header: .h
585 // C++ header: .hh or .H;
586 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000587}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000588
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000589RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000590 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000591 bool silenceMacroWarn)
592 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
593 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000594 IsHeader = IsHeaderFile(inFile);
David Blaikie9c902b52011-09-25 23:23:43 +0000595 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000596 "rewriting sub-expression within a macro (may not be correct)");
David Blaikie9c902b52011-09-25 23:23:43 +0000597 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
598 DiagnosticsEngine::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000599 "rewriter doesn't support user-specified control flow semantics "
600 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000601}
602
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000603ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000604 raw_ostream* OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000605 DiagnosticsEngine &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000606 const LangOptions &LOpts,
607 bool SilenceRewriteMacroWarning) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000608 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000609}
Chris Lattnere99c8322007-10-11 00:43:27 +0000610
Fariborz Jahanian83077422011-12-08 18:25:15 +0000611void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000612 Context = &context;
613 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000614 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000615 MsgSendFunctionDecl = 0;
616 MsgSendSuperFunctionDecl = 0;
617 MsgSendStretFunctionDecl = 0;
618 MsgSendSuperStretFunctionDecl = 0;
619 MsgSendFpretFunctionDecl = 0;
620 GetClassFunctionDecl = 0;
621 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000622 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000623 SelGetUidFunctionDecl = 0;
624 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000625 ConstantStringClassReference = 0;
626 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000627 CurMethodDef = 0;
628 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000629 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000630 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000631 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000632 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000633 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000634 BcLabelCount = 0;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000635 SuperConstructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000636 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000637 PropParentMap = 0;
638 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000639 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000640 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000641
Chris Lattner187f6262008-01-31 19:38:44 +0000642 // Get the ID and start/end of the main file.
643 MainFileID = SM->getMainFileID();
644 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
645 MainFileStart = MainBuf->getBufferStart();
646 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000647
David Blaikiebbafb8a2012-03-11 07:00:24 +0000648 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner187f6262008-01-31 19:38:44 +0000649}
650
Chris Lattner3c799d72007-10-24 17:06:59 +0000651//===----------------------------------------------------------------------===//
652// Top Level Driver Code
653//===----------------------------------------------------------------------===//
654
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000655void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000656 if (Diags.hasErrorOccurred())
657 return;
658
Chris Lattner0bd1c972007-10-16 21:07:07 +0000659 // Two cases: either the decl could be in the main file, or it could be in a
660 // #included file. If the former, rewrite it now. If the later, check to see
661 // if we rewrote the #include/#import.
662 SourceLocation Loc = D->getLocation();
Chandler Carruth35f53202011-07-25 16:49:02 +0000663 Loc = SM->getExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000664
Chris Lattner0bd1c972007-10-16 21:07:07 +0000665 // If this is for a builtin, ignore it.
666 if (Loc.isInvalid()) return;
667
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000668 // Look for built-in declarations that we need to refer during the rewrite.
669 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000670 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000671 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000672 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000673 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000674 ConstantStringClassReference = FVD;
675 return;
676 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000677 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
678 if (ID->isThisDeclarationADefinition())
679 RewriteInterfaceDecl(ID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000680 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000681 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000682 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorf6102672012-01-01 21:23:57 +0000683 if (PD->isThisDeclarationADefinition())
684 RewriteProtocolDecl(PD);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000685 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
686 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000687 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
688 DIEnd = LSD->decls_end();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000689 DI != DIEnd; ) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000690 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
691 if (!IFace->isThisDeclarationADefinition()) {
692 SmallVector<Decl *, 8> DG;
693 SourceLocation StartLoc = IFace->getLocStart();
694 do {
695 if (isa<ObjCInterfaceDecl>(*DI) &&
696 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
697 StartLoc == (*DI)->getLocStart())
698 DG.push_back(*DI);
699 else
700 break;
701
Douglas Gregordc9166c2011-12-15 20:29:51 +0000702 ++DI;
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000703 } while (DI != DIEnd);
704 RewriteForwardClassDecl(DG);
705 continue;
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000706 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000707 }
Douglas Gregorf6102672012-01-01 21:23:57 +0000708
709 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
710 if (!Proto->isThisDeclarationADefinition()) {
711 SmallVector<Decl *, 8> DG;
712 SourceLocation StartLoc = Proto->getLocStart();
713 do {
714 if (isa<ObjCProtocolDecl>(*DI) &&
715 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
716 StartLoc == (*DI)->getLocStart())
717 DG.push_back(*DI);
718 else
719 break;
720
721 ++DI;
722 } while (DI != DIEnd);
723 RewriteForwardProtocolDecl(DG);
724 continue;
725 }
726 }
727
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000728 HandleTopLevelSingleDecl(*DI);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000729 ++DI;
730 }
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000731 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000732 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000733 if (SM->isWrittenInMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000734 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000735}
736
Chris Lattner3c799d72007-10-24 17:06:59 +0000737//===----------------------------------------------------------------------===//
738// Syntactic (non-AST) Rewriting Code
739//===----------------------------------------------------------------------===//
740
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000741void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000742 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000743 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000744 const char *MainBufStart = MainBuf.begin();
745 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000746 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000747
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000748 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000749 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
750 if (*BufPtr == '#') {
751 if (++BufPtr == MainBufEnd)
752 return;
753 while (*BufPtr == ' ' || *BufPtr == '\t')
754 if (++BufPtr == MainBufEnd)
755 return;
756 if (!strncmp(BufPtr, "import", ImportLen)) {
757 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000758 SourceLocation ImportLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000759 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000760 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000761 BufPtr += ImportLen;
762 }
763 }
764 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000765}
766
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000767static std::string getIvarAccessString(ObjCIvarDecl *OID) {
768 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000769 std::string S;
770 S = "((struct ";
771 S += ClassDecl->getIdentifier()->getName();
772 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000773 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000774 return S;
775}
776
Steve Naroffc038b3a2008-12-02 17:36:43 +0000777void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
778 ObjCImplementationDecl *IMD,
779 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000780 static bool objcGetPropertyDefined = false;
781 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000782 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000783 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000784 const char *startBuf = SM->getCharacterData(startLoc);
785 assert((*startBuf == '@') && "bogus @synthesize location");
786 const char *semiBuf = strchr(startBuf, ';');
787 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000788 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000789 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000790
791 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
792 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000793
Steve Naroff9af94912008-12-02 15:48:25 +0000794 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000795 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000796 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000797
Steve Naroff003d00e2008-12-02 16:05:55 +0000798 if (!OID)
799 return;
Bill Wendling44426052012-12-20 19:22:21 +0000800 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000801 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendling44426052012-12-20 19:22:21 +0000802 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
803 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000804 ObjCPropertyDecl::OBJC_PR_copy));
805 std::string Getr;
806 if (GenGetProperty && !objcGetPropertyDefined) {
807 objcGetPropertyDefined = true;
808 // FIXME. Is this attribute correct in all cases?
809 Getr = "\nextern \"C\" __declspec(dllimport) "
810 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000811 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000812 RewriteObjCMethodDecl(OID->getContainingInterface(),
813 PD->getGetterMethodDecl(), Getr);
814 Getr += "{ ";
815 // Synthesize an explicit cast to gain access to the ivar.
816 // See objc-act.c:objc_synthesize_new_getter() for details.
817 if (GenGetProperty) {
818 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
819 Getr += "typedef ";
820 const FunctionType *FPRetType = 0;
Alp Toker314cc812014-01-25 16:55:45 +0000821 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000822 FPRetType);
823 Getr += " _TYPE";
824 if (FPRetType) {
825 Getr += ")"; // close the precedence "scope" for "*".
826
827 // Now, emit the argument types (if any).
828 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
829 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000830 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000831 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000832 std::string ParamStr =
833 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000834 Getr += ParamStr;
835 }
836 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000837 if (FT->getNumParams())
838 Getr += ", ";
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000839 Getr += "...";
840 }
841 Getr += ")";
842 } else
843 Getr += "()";
844 }
845 Getr += ";\n";
846 Getr += "return (_TYPE)";
847 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000848 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000849 Getr += ", 1)";
850 }
851 else
852 Getr += "return " + getIvarAccessString(OID);
853 Getr += "; }";
854 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000855 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000856
857 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000858 return;
Mike Stump11289f42009-09-09 15:08:12 +0000859
Steve Naroff9af94912008-12-02 15:48:25 +0000860 // Generate the 'setter' function.
861 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +0000862 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000863 ObjCPropertyDecl::OBJC_PR_copy);
864 if (GenSetProperty && !objcSetPropertyDefined) {
865 objcSetPropertyDefined = true;
866 // FIXME. Is this attribute correct in all cases?
867 Setr = "\nextern \"C\" __declspec(dllimport) "
868 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
869 }
870
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000871 RewriteObjCMethodDecl(OID->getContainingInterface(),
872 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000873 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000874 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000875 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000876 if (GenSetProperty) {
877 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000878 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000879 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000880 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000881 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +0000882 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000883 Setr += "0, ";
884 else
885 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +0000886 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000887 Setr += "1)";
888 else
889 Setr += "0)";
890 }
891 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000892 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000893 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000894 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000895 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000896 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000897}
Chris Lattner16a0de42007-10-11 18:38:32 +0000898
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000899static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
900 std::string &typedefString) {
901 typedefString += "#ifndef _REWRITER_typedef_";
902 typedefString += ForwardDecl->getNameAsString();
903 typedefString += "\n";
904 typedefString += "#define _REWRITER_typedef_";
905 typedefString += ForwardDecl->getNameAsString();
906 typedefString += "\n";
907 typedefString += "typedef struct objc_object ";
908 typedefString += ForwardDecl->getNameAsString();
909 typedefString += ";\n#endif\n";
910}
911
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000912void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000913 const std::string &typedefString) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000914 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000915 const char *startBuf = SM->getCharacterData(startLoc);
916 const char *semiPtr = strchr(startBuf, ';');
917 // Replace the @class with typedefs corresponding to the classes.
918 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
919}
920
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000921void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000922 std::string typedefString;
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000923 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000924 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000925 if (I == D.begin()) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000926 // Translate to typedef's that forward reference structs with the same name
927 // as the class. As a convenience, we include the original declaration
928 // as a comment.
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000929 typedefString += "// @class ";
930 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000931 typedefString += ";\n";
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000932 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000933 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff574440f2007-10-24 22:48:43 +0000934 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000935 DeclGroupRef::iterator I = D.begin();
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000936 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000937}
Mike Stump11289f42009-09-09 15:08:12 +0000938
Craig Topper5603df42013-07-05 19:34:19 +0000939void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000940 std::string typedefString;
941 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000942 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000943 if (i == 0) {
944 typedefString += "// @class ";
945 typedefString += ForwardDecl->getNameAsString();
946 typedefString += ";\n";
947 }
948 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
949 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000950 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000951}
952
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000953void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000954 // When method is a synthesized one, such as a getter/setter there is
955 // nothing to rewrite.
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000956 if (Method->isImplicit())
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000957 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000958 SourceLocation LocStart = Method->getLocStart();
959 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000960
Chandler Carruthd48db212011-07-25 21:09:52 +0000961 if (SM->getExpansionLineNumber(LocEnd) >
962 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000963 InsertText(LocStart, "#if 0\n");
964 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000965 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000966 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000967 }
968}
969
Mike Stump11289f42009-09-09 15:08:12 +0000970void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000971 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000972
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000973 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000974 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000975}
976
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000977void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000978 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000979
Steve Naroff5448cf62007-10-30 13:30:57 +0000980 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000981 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000982
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000983 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
984 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +0000985 RewriteProperty(*I);
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000986
Mike Stump11289f42009-09-09 15:08:12 +0000987 for (ObjCCategoryDecl::instmeth_iterator
988 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000989 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000990 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000991 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000992 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000993 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000994 RewriteMethodDeclaration(*I);
995
Steve Naroff5448cf62007-10-30 13:30:57 +0000996 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000997 ReplaceText(CatDecl->getAtEndRange().getBegin(),
998 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000999}
1000
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001001void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +00001002 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00001003 assert(PDecl->isThisDeclarationADefinition());
1004
Steve Narofff921385f2007-10-30 16:42:30 +00001005 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001006 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001007
1008 for (ObjCProtocolDecl::instmeth_iterator
1009 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001010 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001011 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001012 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001013 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001014 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001015 RewriteMethodDeclaration(*I);
1016
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +00001017 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1018 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001019 RewriteProperty(*I);
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +00001020
Steve Narofff921385f2007-10-30 16:42:30 +00001021 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001022 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001023 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +00001024
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001025 // Must comment out @optional/@required
1026 const char *startBuf = SM->getCharacterData(LocStart);
1027 const char *endBuf = SM->getCharacterData(LocEnd);
1028 for (const char *p = startBuf; p < endBuf; p++) {
1029 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001030 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001031 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001032
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001033 }
1034 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001035 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001036 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001037
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001038 }
1039 }
Steve Narofff921385f2007-10-30 16:42:30 +00001040}
1041
Douglas Gregorf6102672012-01-01 21:23:57 +00001042void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1043 SourceLocation LocStart = (*D.begin())->getLocStart();
1044 if (LocStart.isInvalid())
1045 llvm_unreachable("Invalid SourceLocation");
1046 // FIXME: handle forward protocol that are declared across multiple lines.
1047 ReplaceText(LocStart, 0, "// ");
1048}
1049
1050void
Craig Topper5603df42013-07-05 19:34:19 +00001051RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001052 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffc17b0562007-11-14 03:37:28 +00001053 if (LocStart.isInvalid())
David Blaikie83d382b2011-09-23 05:06:16 +00001054 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001055 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001056 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001057}
1058
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001059void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1060 const FunctionType *&FPRetType) {
1061 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001062 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001063 else if (T->isFunctionPointerType() ||
1064 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001065 // needs special handling, since pointer-to-functions have special
1066 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001067 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001068 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001069 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001070 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001071 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001072 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001073 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001074 ResultStr +=
1075 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001076 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001077 }
1078 } else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001079 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001080}
1081
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001082void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1083 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001084 std::string &ResultStr) {
1085 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1086 const FunctionType *FPRetType = 0;
1087 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001088 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001089 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001090
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001091 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001092 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001093
Douglas Gregorffca3a22009-01-09 17:18:27 +00001094 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001095 NameStr += "_I_";
1096 else
1097 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001098
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001099 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001100 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001101
1102 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001103 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001104 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001105 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001106 }
Mike Stump11289f42009-09-09 15:08:12 +00001107 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001108 {
1109 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001110 int len = selString.size();
1111 for (int i = 0; i < len; i++)
1112 if (selString[i] == ':')
1113 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001114 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001115 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001116 // Remember this name for metadata emission
1117 MethodInternalNames[OMD] = NameStr;
1118 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001119
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001120 // Rewrite arguments
1121 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001122
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001123 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001124 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001125 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001126 selfTy = Context->getPointerType(selfTy);
Francois Pichet0706d202011-09-17 17:15:52 +00001127 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001128 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001129 ResultStr += "struct ";
1130 }
1131 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001132 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001133 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001134 }
1135 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001136 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregorc0b07282011-09-27 22:38:19 +00001137 Context->getPrintingPolicy());
Mike Stump11289f42009-09-09 15:08:12 +00001138
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001139 ResultStr += " self, ";
Douglas Gregorc0b07282011-09-27 22:38:19 +00001140 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001141 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001142
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001143 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001144 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1145 E = OMD->param_end(); PI != E; ++PI) {
1146 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001147 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001148 if (PDecl->getType()->isObjCQualifiedIdType()) {
1149 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001150 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001151 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001152 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001153 QualType QT = PDecl->getType();
1154 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001155 (void)convertBlockPointerToFunctionPointer(QT);
1156 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001157 ResultStr += Name;
1158 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001159 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001160 if (OMD->isVariadic())
1161 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001162 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001163
Steve Naroffb067bbd2008-07-16 14:40:40 +00001164 if (FPRetType) {
1165 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001166
Steve Naroffb067bbd2008-07-16 14:40:40 +00001167 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001168 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001169 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001170 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001171 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001172 std::string ParamStr =
1173 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Steve Naroffb067bbd2008-07-16 14:40:40 +00001174 ResultStr += ParamStr;
1175 }
1176 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001177 if (FT->getNumParams())
1178 ResultStr += ", ";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001179 ResultStr += "...";
1180 }
1181 ResultStr += ")";
1182 } else {
1183 ResultStr += "()";
1184 }
1185 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001186}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001187void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001188 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1189 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001190
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001191 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001192
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001193 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001194 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1195 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001196 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001197 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001198 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001199 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001200 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001201 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001202
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001203 const char *startBuf = SM->getCharacterData(LocStart);
1204 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001205 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001206 }
Mike Stump11289f42009-09-09 15:08:12 +00001207
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001208 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001209 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1210 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001211 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001212 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001213 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001214 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001215 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001216 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001217
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001218 const char *startBuf = SM->getCharacterData(LocStart);
1219 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001220 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001221 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001222 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001223 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001224 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001225 I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001226 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001227 }
1228
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001229 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001230}
1231
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001232void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001233 std::string ResultStr;
Douglas Gregordc9166c2011-12-15 20:29:51 +00001234 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001235 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001236 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001237 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001238 ResultStr += "\n";
1239 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001240 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001241 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001242 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001243 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001244 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001245 // Mark this typedef as having been generated.
Douglas Gregordc9166c2011-12-15 20:29:51 +00001246 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff2f55b982007-11-01 03:35:41 +00001247 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00001248 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001249
1250 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001251 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001252 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001253 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001254 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001255 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001256 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001257 for (ObjCInterfaceDecl::classmeth_iterator
1258 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001259 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001260 RewriteMethodDeclaration(*I);
1261
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001262 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001263 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1264 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001265}
1266
John McCallfe96e0b2011-11-06 09:01:30 +00001267Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1268 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001269
John McCallfe96e0b2011-11-06 09:01:30 +00001270 // We just magically know some things about the structure of this
1271 // expression.
1272 ObjCMessageExpr *OldMsg =
1273 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1274 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump11289f42009-09-09 15:08:12 +00001275
John McCallfe96e0b2011-11-06 09:01:30 +00001276 // Because the rewriter doesn't allow us to rewrite rewritten code,
1277 // we need to suppress rewriting the sub-statements.
1278 Expr *Base, *RHS;
1279 {
1280 DisableReplaceStmtScope S(*this);
1281
1282 // Rebuild the base expression if we have one.
1283 Base = 0;
1284 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1285 Base = OldMsg->getInstanceReceiver();
1286 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1287 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1288 }
1289
1290 // Rebuild the RHS.
1291 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1292 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1293 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1294 }
1295
1296 // TODO: avoid this copy.
1297 SmallVector<SourceLocation, 1> SelLocs;
1298 OldMsg->getSelectorLocs(SelLocs);
1299
Chad Rosier598f3d22012-01-06 20:05:14 +00001300 ObjCMessageExpr *NewMsg = 0;
John McCallfe96e0b2011-11-06 09:01:30 +00001301 switch (OldMsg->getReceiverKind()) {
1302 case ObjCMessageExpr::Class:
1303 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1304 OldMsg->getValueKind(),
1305 OldMsg->getLeftLoc(),
1306 OldMsg->getClassReceiverTypeInfo(),
1307 OldMsg->getSelector(),
1308 SelLocs,
1309 OldMsg->getMethodDecl(),
1310 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001311 OldMsg->getRightLoc(),
1312 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001313 break;
1314
1315 case ObjCMessageExpr::Instance:
1316 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1317 OldMsg->getValueKind(),
1318 OldMsg->getLeftLoc(),
1319 Base,
1320 OldMsg->getSelector(),
1321 SelLocs,
1322 OldMsg->getMethodDecl(),
1323 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001324 OldMsg->getRightLoc(),
1325 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001326 break;
1327
1328 case ObjCMessageExpr::SuperClass:
1329 case ObjCMessageExpr::SuperInstance:
1330 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1331 OldMsg->getValueKind(),
1332 OldMsg->getLeftLoc(),
1333 OldMsg->getSuperLoc(),
1334 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1335 OldMsg->getSuperType(),
1336 OldMsg->getSelector(),
1337 SelLocs,
1338 OldMsg->getMethodDecl(),
1339 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001340 OldMsg->getRightLoc(),
1341 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001342 break;
1343 }
1344
1345 Stmt *Replacement = SynthMessageExpr(NewMsg);
1346 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1347 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001348}
1349
John McCallfe96e0b2011-11-06 09:01:30 +00001350Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1351 SourceRange OldRange = PseudoOp->getSourceRange();
1352
1353 // We just magically know some things about the structure of this
1354 // expression.
1355 ObjCMessageExpr *OldMsg =
1356 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1357
1358 // Because the rewriter doesn't allow us to rewrite rewritten code,
1359 // we need to suppress rewriting the sub-statements.
1360 Expr *Base = 0;
1361 {
1362 DisableReplaceStmtScope S(*this);
1363
1364 // Rebuild the base expression if we have one.
1365 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1366 Base = OldMsg->getInstanceReceiver();
1367 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1368 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCallb7bd14f2010-12-02 01:19:52 +00001369 }
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001370 }
Steve Narofff326f402008-12-03 00:56:33 +00001371
John McCallfe96e0b2011-11-06 09:01:30 +00001372 // Intentionally empty.
1373 SmallVector<SourceLocation, 1> SelLocs;
1374 SmallVector<Expr*, 1> Args;
Steve Naroff1042ff32008-12-08 16:43:47 +00001375
Chad Rosier598f3d22012-01-06 20:05:14 +00001376 ObjCMessageExpr *NewMsg = 0;
John McCallfe96e0b2011-11-06 09:01:30 +00001377 switch (OldMsg->getReceiverKind()) {
1378 case ObjCMessageExpr::Class:
1379 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1380 OldMsg->getValueKind(),
1381 OldMsg->getLeftLoc(),
1382 OldMsg->getClassReceiverTypeInfo(),
1383 OldMsg->getSelector(),
1384 SelLocs,
1385 OldMsg->getMethodDecl(),
1386 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001387 OldMsg->getRightLoc(),
1388 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001389 break;
1390
1391 case ObjCMessageExpr::Instance:
1392 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1393 OldMsg->getValueKind(),
1394 OldMsg->getLeftLoc(),
1395 Base,
1396 OldMsg->getSelector(),
1397 SelLocs,
1398 OldMsg->getMethodDecl(),
1399 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001400 OldMsg->getRightLoc(),
1401 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001402 break;
1403
1404 case ObjCMessageExpr::SuperClass:
1405 case ObjCMessageExpr::SuperInstance:
1406 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1407 OldMsg->getValueKind(),
1408 OldMsg->getLeftLoc(),
1409 OldMsg->getSuperLoc(),
1410 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1411 OldMsg->getSuperType(),
1412 OldMsg->getSelector(),
1413 SelLocs,
1414 OldMsg->getMethodDecl(),
1415 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001416 OldMsg->getRightLoc(),
1417 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001418 break;
Steve Naroff1042ff32008-12-08 16:43:47 +00001419 }
John McCallfe96e0b2011-11-06 09:01:30 +00001420
1421 Stmt *Replacement = SynthMessageExpr(NewMsg);
1422 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1423 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001424}
1425
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001426/// SynthCountByEnumWithState - To print:
1427/// ((unsigned int (*)
1428/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001429/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001430/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001431/// "countByEnumeratingWithState:objects:count:"),
1432/// &enumState,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001433/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001434///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001435void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001436 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1437 "id *, unsigned int))(void *)objc_msgSend)";
1438 buf += "\n\t\t";
1439 buf += "((id)l_collection,\n\t\t";
1440 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1441 buf += "\n\t\t";
1442 buf += "&enumState, "
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001443 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001444}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001445
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001446/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1447/// statement to exit to its outer synthesized loop.
1448///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001449Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001450 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1451 return S;
1452 // replace break with goto __break_label
1453 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001454
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001455 SourceLocation startLoc = S->getLocStart();
1456 buf = "goto __break_label_";
1457 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001458 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001459
1460 return 0;
1461}
1462
1463/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1464/// statement to continue with its inner synthesized loop.
1465///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001466Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001467 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1468 return S;
1469 // replace continue with goto __continue_label
1470 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001471
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001472 SourceLocation startLoc = S->getLocStart();
1473 buf = "goto __continue_label_";
1474 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001475 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001476
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001477 return 0;
1478}
1479
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001480/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001481/// It rewrites:
1482/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001483
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001484/// Into:
1485/// {
Mike Stump11289f42009-09-09 15:08:12 +00001486/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001487/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001488/// id __rw_items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001489/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001490/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001491/// objects:__rw_items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001492/// if (limit) {
1493/// unsigned long startMutations = *enumState.mutationsPtr;
1494/// do {
1495/// unsigned long counter = 0;
1496/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001497/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001498/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001499/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001500/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001501/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001502/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001503/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001504/// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001505/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001506/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001507/// }
1508/// else
1509/// elem = nil;
1510/// }
1511///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001512Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001513 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001514 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001515 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001516 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001517 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001518 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001519
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001520 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001521 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001522 StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001523 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001524 std::string buf;
1525 buf = "\n{\n\t";
1526 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1527 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001528 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001529 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001530 if (ElementType->isObjCQualifiedIdType() ||
1531 ElementType->isObjCQualifiedInterfaceType())
1532 // Simply use 'id' for all qualified types.
1533 elementTypeAsString = "id";
1534 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001535 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001536 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001537 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001538 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001539 buf += elementName;
1540 buf += ";\n\t";
1541 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001542 else {
1543 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001544 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001545 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1546 if (VD->getType()->isObjCQualifiedIdType() ||
1547 VD->getType()->isObjCQualifiedInterfaceType())
1548 // Simply use 'id' for all qualified types.
1549 elementTypeAsString = "id";
1550 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001551 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001552 }
Mike Stump11289f42009-09-09 15:08:12 +00001553
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001554 // struct __objcFastEnumerationState enumState = { 0 };
1555 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001556 // id __rw_items[16];
1557 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001558 // id l_collection = (id)
1559 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001560 // Find start location of 'collection' the hard way!
1561 const char *startCollectionBuf = startBuf;
1562 startCollectionBuf += 3; // skip 'for'
1563 startCollectionBuf = strchr(startCollectionBuf, '(');
1564 startCollectionBuf++; // skip '('
1565 // find 'in' and skip it.
1566 while (*startCollectionBuf != ' ' ||
1567 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1568 (*(startCollectionBuf+3) != ' ' &&
1569 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1570 startCollectionBuf++;
1571 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001572
1573 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001574 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001575 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001576 SourceLocation rightParenLoc = S->getRParenLoc();
1577 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001578 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001579 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001580
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001581 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001582 // objects:__rw_items count:16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001583 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001584 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001585 // ((unsigned int (*)
1586 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001587 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001588 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001589 // "countByEnumeratingWithState:objects:count:"),
1590 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001591 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001592 buf += "unsigned long limit =\n\t\t";
1593 SynthCountByEnumWithState(buf);
1594 buf += ";\n\t";
1595 /// if (limit) {
1596 /// unsigned long startMutations = *enumState.mutationsPtr;
1597 /// do {
1598 /// unsigned long counter = 0;
1599 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001600 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001601 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001602 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001603 buf += "if (limit) {\n\t";
1604 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1605 buf += "do {\n\t\t";
1606 buf += "unsigned long counter = 0;\n\t\t";
1607 buf += "do {\n\t\t\t";
1608 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1609 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1610 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001611 buf += " = (";
1612 buf += elementTypeAsString;
1613 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001614 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001615 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001616
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001617 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001618 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001619 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001620 /// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001621 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001622 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001623 /// }
1624 /// else
1625 /// elem = nil;
1626 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001627 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001628 buf = ";\n\t";
1629 buf += "__continue_label_";
1630 buf += utostr(ObjCBcLabelNo.back());
1631 buf += ": ;";
1632 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001633 buf += "} while (counter < limit);\n\t";
1634 buf += "} while (limit = ";
1635 SynthCountByEnumWithState(buf);
1636 buf += ");\n\t";
1637 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001638 buf += " = ((";
1639 buf += elementTypeAsString;
1640 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001641 buf += "__break_label_";
1642 buf += utostr(ObjCBcLabelNo.back());
1643 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001644 buf += "}\n\t";
1645 buf += "else\n\t\t";
1646 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001647 buf += " = ((";
1648 buf += elementTypeAsString;
1649 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001650 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001651
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001652 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001653 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001654 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001655 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001656 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001657 } else {
1658 /* Need to treat single statements specially. For example:
1659 *
1660 * for (A *a in b) if (stuff()) break;
1661 * for (A *a in b) xxxyy;
1662 *
1663 * The following code simply scans ahead to the semi to find the actual end.
1664 */
1665 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1666 const char *semiBuf = strchr(stmtBuf, ';');
1667 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001668 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001669 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001670 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001671 Stmts.pop_back();
1672 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001673 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001674}
1675
Mike Stump11289f42009-09-09 15:08:12 +00001676/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001677/// This routine rewrites @synchronized(expr) stmt;
1678/// into:
1679/// objc_sync_enter(expr);
1680/// @try stmt @finally { objc_sync_exit(expr); }
1681///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001682Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001683 // Get the start location and compute the semi location.
1684 SourceLocation startLoc = S->getLocStart();
1685 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001686
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001687 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001688
1689 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001690 buf = "objc_sync_enter((id)";
1691 const char *lparenBuf = startBuf;
1692 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001693 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001694 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1695 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001696 // been rewritten! (which implies the SourceLocation's are invalid).
1697 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001698 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001699 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001700 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001701 buf = ");\n";
1702 // declare a new scope with two variables, _stack and _rethrow.
1703 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1704 buf += "int buf[18/*32-bit i386*/];\n";
1705 buf += "char *pointers[4];} _stack;\n";
1706 buf += "id volatile _rethrow = 0;\n";
1707 buf += "objc_exception_try_enter(&_stack);\n";
1708 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001709 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001710 startLoc = S->getSynchBody()->getLocEnd();
1711 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001712
Steve Naroffad7013b2008-08-19 13:04:19 +00001713 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001714 SourceLocation lastCurlyLoc = startLoc;
1715 buf = "}\nelse {\n";
1716 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001717 buf += "}\n";
1718 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001719 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001720
1721 std::string syncBuf;
1722 syncBuf += " objc_sync_exit(";
John McCall9320b872011-09-09 05:25:32 +00001723
1724 Expr *syncExpr = S->getSynchExpr();
1725 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1726 ? CK_BitCast :
1727 syncExpr->getType()->isBlockPointerType()
1728 ? CK_BlockPointerToObjCPointerCast
1729 : CK_CPointerToObjCPointerCast;
1730 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1731 CK, syncExpr);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001732 std::string syncExprBufS;
1733 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Richard Smith235341b2012-08-16 03:56:14 +00001734 syncExpr->printPretty(syncExprBuf, 0, PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001735 syncBuf += syncExprBuf.str();
1736 syncBuf += ");";
1737
1738 buf += syncBuf;
1739 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001740 buf += "}\n";
1741 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001742
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001743 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001744
1745 bool hasReturns = false;
1746 HasReturnStmts(S->getSynchBody(), hasReturns);
1747 if (hasReturns)
1748 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1749
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001750 return 0;
1751}
1752
Steve Naroffec60b432009-12-05 21:43:12 +00001753void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1754{
Steve Naroff6d6da252008-12-05 17:03:39 +00001755 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001756 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff6d6da252008-12-05 17:03:39 +00001757 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001758 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001759
Steve Naroffec60b432009-12-05 21:43:12 +00001760 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001761 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001762 TryFinallyContainsReturnDiag);
1763 }
1764 return;
1765}
1766
Steve Naroffec60b432009-12-05 21:43:12 +00001767void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1768{
1769 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001770 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001771 if (*CI)
1772 HasReturnStmts(*CI, hasReturns);
1773
1774 if (isa<ReturnStmt>(S))
1775 hasReturns = true;
1776 return;
1777}
1778
1779void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1780 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001781 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001782 if (*CI) {
1783 RewriteTryReturnStmts(*CI);
1784 }
1785 if (isa<ReturnStmt>(S)) {
1786 SourceLocation startLoc = S->getLocStart();
1787 const char *startBuf = SM->getCharacterData(startLoc);
1788
1789 const char *semiBuf = strchr(startBuf, ';');
1790 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001791 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001792
1793 std::string buf;
1794 buf = "{ objc_exception_try_exit(&_stack); return";
1795
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001796 ReplaceText(startLoc, 6, buf);
1797 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001798 }
1799 return;
1800}
1801
1802void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1803 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001804 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001805 if (*CI) {
1806 RewriteSyncReturnStmts(*CI, syncExitBuf);
1807 }
1808 if (isa<ReturnStmt>(S)) {
1809 SourceLocation startLoc = S->getLocStart();
1810 const char *startBuf = SM->getCharacterData(startLoc);
1811
1812 const char *semiBuf = strchr(startBuf, ';');
1813 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001814 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001815
1816 std::string buf;
1817 buf = "{ objc_exception_try_exit(&_stack);";
1818 buf += syncExitBuf;
1819 buf += " return";
1820
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001821 ReplaceText(startLoc, 6, buf);
1822 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001823 }
1824 return;
1825}
1826
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001827Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001828 // Get the start location and compute the semi location.
1829 SourceLocation startLoc = S->getLocStart();
1830 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001831
Steve Naroffbf478ec2007-11-07 04:08:17 +00001832 assert((*startBuf == '@') && "bogus @try location");
1833
1834 std::string buf;
1835 // declare a new scope with two variables, _stack and _rethrow.
1836 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1837 buf += "int buf[18/*32-bit i386*/];\n";
1838 buf += "char *pointers[4];} _stack;\n";
1839 buf += "id volatile _rethrow = 0;\n";
1840 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001841 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001842
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001843 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001844
Steve Naroffbf478ec2007-11-07 04:08:17 +00001845 startLoc = S->getTryBody()->getLocEnd();
1846 startBuf = SM->getCharacterData(startLoc);
1847
1848 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001849
Steve Naroffbf478ec2007-11-07 04:08:17 +00001850 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001851 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001852 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffce2dca12008-07-16 15:31:30 +00001853 buf = " /* @catch begin */ else {\n";
1854 buf += " id _caught = objc_exception_extract(&_stack);\n";
1855 buf += " objc_exception_try_enter (&_stack);\n";
1856 buf += " if (_setjmp(_stack.buf))\n";
1857 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1858 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001859
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001860 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001861 } else { /* no catch list */
1862 buf = "}\nelse {\n";
1863 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1864 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001865 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001866 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001867 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001868 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1869 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001870 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001871
Douglas Gregor96c79492010-04-23 22:50:49 +00001872 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001873 buf = "if ("; // we are generating code for the first catch clause
1874 else
1875 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001876 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001877 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001878
Steve Naroffbf478ec2007-11-07 04:08:17 +00001879 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001880
Steve Naroffbf478ec2007-11-07 04:08:17 +00001881 const char *lParenLoc = strchr(startBuf, '(');
1882
Douglas Gregor96c79492010-04-23 22:50:49 +00001883 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001884 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001885 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001886 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1887 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001888 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001889 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001890 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001891
Steve Naroffedb5bc62008-02-01 20:02:07 +00001892 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001893 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001894 } else if (catchDecl) {
1895 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001896 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001897 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001898 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall96fa4842010-05-17 21:00:27 +00001899 } else if (const ObjCObjectPointerType *Ptr =
1900 t->getAs<ObjCObjectPointerType>()) {
1901 // Should be a pointer to a class.
1902 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1903 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001904 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001905 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001906 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001907 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001908 }
1909 }
1910 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001911 lastCatchBody = Catch->getCatchBody();
1912 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001913 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1914 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1915 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1916 assert((*rParenBuf == ')') && "bogus @catch paren location");
1917 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001918
Mike Stump11289f42009-09-09 15:08:12 +00001919 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001920 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001921 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001922 } else {
David Blaikie83d382b2011-09-23 05:06:16 +00001923 llvm_unreachable("@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001924 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001925 }
1926 // Complete the catch list...
1927 if (lastCatchBody) {
1928 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001929 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1930 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001931
Steve Naroff4adbe312008-09-11 15:29:03 +00001932 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001933 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff4adbe312008-09-11 15:29:03 +00001934 buf = "} /* last catch end */\n";
1935 buf += "else {\n";
1936 buf += " _rethrow = _caught;\n";
1937 buf += " objc_exception_try_exit(&_stack);\n";
1938 buf += "} } /* @catch end */\n";
1939 if (!S->getFinallyStmt())
1940 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001941 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001942
Steve Naroffbf478ec2007-11-07 04:08:17 +00001943 // Set lastCurlyLoc
1944 lastCurlyLoc = lastCatchBody->getLocEnd();
1945 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001946 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001947 startLoc = finalStmt->getLocStart();
1948 startBuf = SM->getCharacterData(startLoc);
1949 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001950
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001951 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001952
Steve Naroffbf478ec2007-11-07 04:08:17 +00001953 Stmt *body = finalStmt->getFinallyBody();
1954 SourceLocation startLoc = body->getLocStart();
1955 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001956 assert(*SM->getCharacterData(startLoc) == '{' &&
1957 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001958 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001959 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001960
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001961 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001962 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001963 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001964 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001965
Steve Naroffbf478ec2007-11-07 04:08:17 +00001966 // Set lastCurlyLoc
1967 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001968
Steve Naroff6d6da252008-12-05 17:03:39 +00001969 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001970 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001971 } else { /* no finally clause - make sure we synthesize an implicit one */
1972 buf = "{ /* implicit finally clause */\n";
1973 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1974 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1975 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001976 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001977
1978 // Now check for any return/continue/go statements within the @try.
1979 // The implicit finally clause won't called if the @try contains any
1980 // jump statements.
1981 bool hasReturns = false;
1982 HasReturnStmts(S->getTryBody(), hasReturns);
1983 if (hasReturns)
1984 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001985 }
1986 // Now emit the final closing curly brace...
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001987 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001988 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001989 return 0;
1990}
1991
Mike Stump11289f42009-09-09 15:08:12 +00001992// This can't be done with ReplaceStmt(S, ThrowExpr), since
1993// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001994// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001995Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001996 // Get the start location and compute the semi location.
1997 SourceLocation startLoc = S->getLocStart();
1998 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001999
Steve Naroffa733c7f2007-11-07 15:32:26 +00002000 assert((*startBuf == '@') && "bogus @throw location");
2001
2002 std::string buf;
2003 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00002004 if (S->getThrowExpr())
2005 buf = "objc_exception_throw(";
2006 else // add an implicit argument
2007 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002008
Steve Naroff29788342008-07-25 15:41:30 +00002009 // handle "@ throw" correctly.
2010 const char *wBuf = strchr(startBuf, 'w');
2011 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002012 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002013
Steve Naroffa733c7f2007-11-07 15:32:26 +00002014 const char *semiBuf = strchr(startBuf, ';');
2015 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002016 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002017 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002018 return 0;
2019}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002020
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002021Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002022 // Create a new string expression.
Anders Carlssond8499822007-10-29 05:01:08 +00002023 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002024 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002025 Expr *Replacement = getStringLiteral(StrEncoding);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002026 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002027
Chris Lattner4431a1b2007-11-30 22:53:43 +00002028 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002029 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002030 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002031}
2032
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002033Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002034 if (!SelGetUidFunctionDecl)
2035 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002036 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2037 // Create a call to sel_registerName("selName").
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002038 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002039 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002040 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2041 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002042 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002043 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002044 return SelExp;
2045}
2046
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002047CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002048 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2049 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002050 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002051 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002052
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002053 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002054 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2055 VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002056
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002057 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002058 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002059 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002060 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00002061 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002062
John McCall9dd450b2009-09-21 23:43:11 +00002063 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002064
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002065 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002066 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
John McCall7decc9e2010-11-18 06:31:45 +00002067 FT->getCallResultType(*Context),
2068 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002069 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002070}
2071
Steve Naroff50d42052007-11-01 13:24:47 +00002072static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2073 const char *&startRef, const char *&endRef) {
2074 while (startBuf < endBuf) {
2075 if (*startBuf == '<')
2076 startRef = startBuf; // mark the start.
2077 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002078 if (startRef && *startRef == '<') {
2079 endRef = startBuf; // mark the end.
2080 return true;
2081 }
2082 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002083 }
2084 startBuf++;
2085 }
2086 return false;
2087}
2088
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002089static void scanToNextArgument(const char *&argRef) {
2090 int angle = 0;
2091 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2092 if (*argRef == '<')
2093 angle++;
2094 else if (*argRef == '>')
2095 angle--;
2096 argRef++;
2097 }
2098 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2099}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002100
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002101bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002102 if (T->isObjCQualifiedIdType())
2103 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002104 if (const PointerType *PT = T->getAs<PointerType>()) {
2105 if (PT->getPointeeType()->isObjCQualifiedIdType())
2106 return true;
2107 }
2108 if (T->isObjCObjectPointerType()) {
2109 T = T->getPointeeType();
2110 return T->isObjCQualifiedInterfaceType();
2111 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002112 if (T->isArrayType()) {
2113 QualType ElemTy = Context->getBaseElementType(T);
2114 return needToScanForQualifiers(ElemTy);
2115 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002116 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002117}
2118
Steve Naroff873bd842008-07-29 18:15:38 +00002119void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2120 QualType Type = E->getType();
2121 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002122 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002123
Steve Naroffdbfc6932008-11-19 21:15:47 +00002124 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2125 Loc = ECE->getLParenLoc();
2126 EndLoc = ECE->getRParenLoc();
2127 } else {
2128 Loc = E->getLocStart();
2129 EndLoc = E->getLocEnd();
2130 }
2131 // This will defend against trying to rewrite synthesized expressions.
2132 if (Loc.isInvalid() || EndLoc.isInvalid())
2133 return;
2134
Steve Naroff873bd842008-07-29 18:15:38 +00002135 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002136 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002137 const char *startRef = 0, *endRef = 0;
2138 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2139 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002140 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2141 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff873bd842008-07-29 18:15:38 +00002142 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002143 InsertText(LessLoc, "/*");
2144 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002145 }
2146 }
2147}
2148
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002149void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002150 SourceLocation Loc;
2151 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002152 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002153 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2154 Loc = VD->getLocation();
2155 Type = VD->getType();
2156 }
2157 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2158 Loc = FD->getLocation();
2159 // Check for ObjC 'id' and class types that have been adorned with protocol
2160 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002161 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002162 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002163 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002164 if (!proto)
2165 return;
Alp Toker314cc812014-01-25 16:55:45 +00002166 Type = proto->getReturnType();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002167 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002168 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2169 Loc = FD->getLocation();
2170 Type = FD->getType();
2171 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002172 else
2173 return;
Mike Stump11289f42009-09-09 15:08:12 +00002174
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002175 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002176 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002177
Steve Naroff50d42052007-11-01 13:24:47 +00002178 const char *endBuf = SM->getCharacterData(Loc);
2179 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002180 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002181 startBuf--; // scan backward (from the decl location) for return type.
2182 const char *startRef = 0, *endRef = 0;
2183 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2184 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002185 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2186 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002187 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002188 InsertText(LessLoc, "/*");
2189 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002190 }
2191 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002192 if (!proto)
2193 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002194 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002195 const char *startBuf = SM->getCharacterData(Loc);
2196 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002197 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2198 if (needToScanForQualifiers(proto->getParamType(i))) {
Steve Naroff50d42052007-11-01 13:24:47 +00002199 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002200
Steve Naroff50d42052007-11-01 13:24:47 +00002201 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002202 // scan forward (from the decl location) for argument types.
2203 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002204 const char *startRef = 0, *endRef = 0;
2205 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2206 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002207 SourceLocation LessLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002208 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002209 SourceLocation GreaterLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002210 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002211 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002212 InsertText(LessLoc, "/*");
2213 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002214 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002215 startBuf = ++endBuf;
2216 }
2217 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002218 // If the function name is derived from a macro expansion, then the
2219 // argument buffer will not follow the name. Need to speak with Chris.
2220 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002221 startBuf++; // scan forward (from the decl location) for argument types.
2222 startBuf++;
2223 }
Steve Naroff50d42052007-11-01 13:24:47 +00002224 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002225}
2226
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002227void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2228 QualType QT = ND->getType();
2229 const Type* TypePtr = QT->getAs<Type>();
2230 if (!isa<TypeOfExprType>(TypePtr))
2231 return;
2232 while (isa<TypeOfExprType>(TypePtr)) {
2233 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2234 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2235 TypePtr = QT->getAs<Type>();
2236 }
2237 // FIXME. This will not work for multiple declarators; as in:
2238 // __typeof__(a) b,c,d;
Douglas Gregorc0b07282011-09-27 22:38:19 +00002239 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002240 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2241 const char *startBuf = SM->getCharacterData(DeclLoc);
2242 if (ND->getInit()) {
2243 std::string Name(ND->getNameAsString());
2244 TypeAsString += " " + Name + " = ";
2245 Expr *E = ND->getInit();
2246 SourceLocation startLoc;
2247 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2248 startLoc = ECE->getLParenLoc();
2249 else
2250 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00002251 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002252 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002253 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002254 }
2255 else {
2256 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00002257 X = SM->getExpansionLoc(X);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002258 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002259 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002260 }
2261}
2262
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002263// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002264void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002265 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002266 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002267 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002268 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002269 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002270 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002271 SourceLocation(),
2272 SourceLocation(),
2273 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002274 SC_Extern);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002275}
2276
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002277void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002278 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002279 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002280 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002281 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002282 return;
2283 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002284 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002285}
2286
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002287void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregorc0b07282011-09-27 22:38:19 +00002288 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002289 const char *argPtr = TypeString.c_str();
2290 if (!strchr(argPtr, '^')) {
2291 Str += TypeString;
2292 return;
2293 }
2294 while (*argPtr) {
2295 Str += (*argPtr == '^' ? '*' : *argPtr);
2296 argPtr++;
2297 }
2298}
2299
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002300// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002301void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2302 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002303 QualType Type = VD->getType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002304 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002305 const char *argPtr = TypeString.c_str();
2306 int paren = 0;
2307 while (*argPtr) {
2308 switch (*argPtr) {
2309 case '(':
2310 Str += *argPtr;
2311 paren++;
2312 break;
2313 case ')':
2314 Str += *argPtr;
2315 paren--;
2316 break;
2317 case '^':
2318 Str += '*';
2319 if (paren == 1)
2320 Str += VD->getNameAsString();
2321 break;
2322 default:
2323 Str += *argPtr;
2324 break;
2325 }
2326 argPtr++;
2327 }
2328}
2329
2330
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002331void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2332 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2333 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2334 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2335 if (!proto)
2336 return;
Alp Toker314cc812014-01-25 16:55:45 +00002337 QualType Type = proto->getReturnType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002338 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002339 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002340 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002341 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002342 unsigned numArgs = proto->getNumParams();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002343 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002344 QualType ArgType = proto->getParamType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002345 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002346 if (i+1 < numArgs)
2347 FdStr += ", ";
2348 }
2349 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002350 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002351 CurFunctionDeclToDeclareForBlock = 0;
2352}
2353
Benjamin Kramer60509af2013-09-09 14:48:42 +00002354// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2355void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2356 if (SuperConstructorFunctionDecl)
Steve Naroff17978c42008-03-11 17:37:02 +00002357 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002358 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002359 SmallVector<QualType, 16> ArgTys;
Steve Naroff17978c42008-03-11 17:37:02 +00002360 QualType argT = Context->getObjCIdType();
2361 assert(!argT.isNull() && "Can't find 'id' type");
2362 ArgTys.push_back(argT);
2363 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002364 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002365 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002366 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002367 SourceLocation(),
2368 SourceLocation(),
2369 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002370 0, SC_Extern);
Steve Naroff17978c42008-03-11 17:37:02 +00002371}
2372
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002373// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002374void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002375 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002376 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002377 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002378 assert(!argT.isNull() && "Can't find 'id' type");
2379 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002380 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002381 assert(!argT.isNull() && "Can't find 'SEL' type");
2382 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002383 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002384 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002385 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002386 SourceLocation(),
2387 SourceLocation(),
2388 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002389 SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002390}
2391
Steve Naroff7fa2f042007-11-15 10:28:18 +00002392// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002393void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002394 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002395 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002396 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002397 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002398 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002399 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2400 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2401 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002402 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002403 assert(!argT.isNull() && "Can't find 'SEL' type");
2404 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002405 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002406 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002407 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002408 SourceLocation(),
2409 SourceLocation(),
2410 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002411 SC_Extern);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002412}
2413
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002414// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002415void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002416 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002417 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002418 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002419 assert(!argT.isNull() && "Can't find 'id' type");
2420 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002421 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002422 assert(!argT.isNull() && "Can't find 'SEL' type");
2423 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002424 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002425 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002426 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002427 SourceLocation(),
2428 SourceLocation(),
2429 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002430 SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002431}
2432
Mike Stump11289f42009-09-09 15:08:12 +00002433// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002434// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002435void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002436 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002437 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002438 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002439 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002440 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002441 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002442 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2443 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2444 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002445 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002446 assert(!argT.isNull() && "Can't find 'SEL' type");
2447 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002448 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002449 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002450 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002451 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002452 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002453 msgSendIdent,
2454 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002455 SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002456}
2457
Steve Naroff2e4e3852008-05-08 22:02:18 +00002458// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002459void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002460 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002461 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002462 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002463 assert(!argT.isNull() && "Can't find 'id' type");
2464 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002465 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002466 assert(!argT.isNull() && "Can't find 'SEL' type");
2467 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002468 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002469 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002470 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002471 SourceLocation(),
2472 SourceLocation(),
2473 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002474 SC_Extern);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002475}
2476
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002477// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002478void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002479 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002480 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002481 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002482 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002483 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002484 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002485 SourceLocation(),
2486 SourceLocation(),
2487 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002488 SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002489}
2490
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002491// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2492void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2493 IdentifierInfo *getSuperClassIdent =
2494 &Context->Idents.get("class_getSuperclass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002495 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002496 ArgTys.push_back(Context->getObjCClassType());
John McCalldb40c7f2010-12-14 08:05:40 +00002497 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002498 ArgTys);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002499 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002500 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002501 SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002502 getSuperClassIdent,
2503 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002504 SC_Extern);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002505}
2506
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002507// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002508void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002509 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002510 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002511 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002512 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002513 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002514 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002515 SourceLocation(),
2516 SourceLocation(),
2517 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002518 0, SC_Extern);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002519}
2520
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002521Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002522 QualType strType = getConstantStringStructType();
2523
2524 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002525
2526 std::string tmpName = InFileName;
2527 unsigned i;
2528 for (i=0; i < tmpName.length(); i++) {
2529 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002530 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002531 if (!isAlphanumeric(c))
Steve Naroffa6141f02008-05-31 03:35:42 +00002532 tmpName[i] = '_';
2533 }
2534 S += tmpName;
2535 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002536 S += utostr(NumObjCStringLiterals++);
2537
Steve Naroff00a31762008-03-27 22:29:16 +00002538 Preamble += "static __NSConstantStringImpl " + S;
2539 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2540 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002541 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002542 std::string prettyBufS;
2543 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002544 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002545 Preamble += prettyBuf.str();
2546 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002547 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002548
2549 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002550 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002551 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002552 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002553 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002554 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002555 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002556 VK_RValue, OK_Ordinary,
2557 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002558 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002559 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall9320b872011-09-09 05:25:32 +00002560 CK_CPointerToObjCPointerCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002561 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002562 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002563 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002564}
2565
Steve Naroff7fa2f042007-11-15 10:28:18 +00002566// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002567QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002568 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002569 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002570 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002571 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002572 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002573
Steve Naroff7fa2f042007-11-15 10:28:18 +00002574 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002575 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002576 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002577 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002578
Steve Naroff7fa2f042007-11-15 10:28:18 +00002579 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002580 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002581 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002582 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002583 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002584 FieldTypes[i], 0,
2585 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00002586 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002587 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002588 }
Mike Stump11289f42009-09-09 15:08:12 +00002589
Douglas Gregord5058122010-02-11 01:19:42 +00002590 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002591 }
2592 return Context->getTagDeclType(SuperStructDecl);
2593}
2594
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002595QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002596 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002597 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002598 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002599 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002600 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002601
Steve Naroffce8e8862008-03-15 00:55:56 +00002602 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002603 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002604 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002605 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002606 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002607 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002608 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002609 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002610
Steve Naroffce8e8862008-03-15 00:55:56 +00002611 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002612 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002613 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2614 ConstantStringDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002615 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00002616 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002617 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002618 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00002619 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002620 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002621 }
2622
Douglas Gregord5058122010-02-11 01:19:42 +00002623 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002624 }
2625 return Context->getTagDeclType(ConstantStringDecl);
2626}
2627
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002628CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2629 QualType msgSendType,
2630 QualType returnType,
2631 SmallVectorImpl<QualType> &ArgTypes,
2632 SmallVectorImpl<Expr*> &MsgExprs,
2633 ObjCMethodDecl *Method) {
2634 // Create a reference to the objc_msgSend_stret() declaration.
2635 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2636 false, msgSendType,
2637 VK_LValue, SourceLocation());
2638 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2639 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2640 Context->getPointerType(Context->VoidTy),
2641 CK_BitCast, STDRE);
2642 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002643 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2644 Method ? Method->isVariadic()
2645 : false);
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002646 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>();
Alp Toker314cc812014-01-25 16:55:45 +00002654 CallExpr *STCE = new (Context) CallExpr(
2655 *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002656 return STCE;
2657
2658}
2659
2660
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002661Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2662 SourceLocation StartLoc,
2663 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002664 if (!SelGetUidFunctionDecl)
2665 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002666 if (!MsgSendFunctionDecl)
2667 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002668 if (!MsgSendSuperFunctionDecl)
2669 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002670 if (!MsgSendStretFunctionDecl)
2671 SynthMsgSendStretFunctionDecl();
2672 if (!MsgSendSuperStretFunctionDecl)
2673 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002674 if (!MsgSendFpretFunctionDecl)
2675 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002676 if (!GetClassFunctionDecl)
2677 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002678 if (!GetSuperClassFunctionDecl)
2679 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002680 if (!GetMetaClassFunctionDecl)
2681 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002682
Steve Naroff7fa2f042007-11-15 10:28:18 +00002683 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002684 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2685 // May need to use objc_msgSend_stret() as well.
2686 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002687 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002688 QualType resultType = mDecl->getReturnType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002689 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002690 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002691 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002692 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002693 }
Mike Stump11289f42009-09-09 15:08:12 +00002694
Steve Naroff574440f2007-10-24 22:48:43 +00002695 // Synthesize a call to objc_msgSend().
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002696 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002697 switch (Exp->getReceiverKind()) {
2698 case ObjCMessageExpr::SuperClass: {
2699 MsgSendFlavor = MsgSendSuperFunctionDecl;
2700 if (MsgSendStretFlavor)
2701 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2702 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002703
Douglas Gregor9a129192010-04-21 00:45:42 +00002704 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002705
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002706 SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002707
Douglas Gregor9a129192010-04-21 00:45:42 +00002708 // set the receiver to self, the first argument to all methods.
2709 InitExprs.push_back(
2710 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002711 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002712 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002713 false,
John McCall7decc9e2010-11-18 06:31:45 +00002714 Context->getObjCIdType(),
2715 VK_RValue,
2716 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002717 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002718
Douglas Gregor9a129192010-04-21 00:45:42 +00002719 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002720 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002721 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002722 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2723 &ClsExprs[0],
2724 ClsExprs.size(),
2725 StartLoc,
2726 EndLoc);
2727 // (Class)objc_getClass("CurrentClass")
2728 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2729 Context->getObjCClassType(),
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002730 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002731 ClsExprs.clear();
2732 ClsExprs.push_back(ArgExpr);
2733 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2734 &ClsExprs[0], ClsExprs.size(),
2735 StartLoc, EndLoc);
2736
2737 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2738 // To turn off a warning, type-cast to 'id'
2739 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2740 NoTypeInfoCStyleCastExpr(Context,
2741 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002742 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002743 // struct objc_super
2744 QualType superType = getSuperStructType();
2745 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002746
Francois Pichet0706d202011-09-17 17:15:52 +00002747 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002748 SynthSuperConstructorFunctionDecl();
2749 // Simulate a constructor call...
2750 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002751 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002752 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002753 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002754 superType, VK_LValue,
2755 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002756 // The code for super is a little tricky to prevent collision with
2757 // the structure definition in the header. The rewriter has it's own
2758 // internal definition (__rw_objc_super) that is uses. This is why
2759 // we need the cast below. For example:
2760 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2761 //
John McCalle3027922010-08-25 11:45:40 +00002762 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002763 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002764 VK_RValue, OK_Ordinary,
2765 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002766 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2767 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002768 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002769 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002770 // (struct objc_super) { <exprs from above> }
2771 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002772 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002773 SourceLocation());
2774 TypeSourceInfo *superTInfo
2775 = Context->getTrivialTypeSourceInfo(superType);
2776 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002777 superType, VK_LValue,
2778 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002779 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002780 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002781 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002782 VK_RValue, OK_Ordinary,
2783 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002784 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002785 MsgExprs.push_back(SuperRep);
2786 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002787 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002788
2789 case ObjCMessageExpr::Class: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002790 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002791 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002792 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002793 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002794 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002795 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2796 &ClsExprs[0],
2797 ClsExprs.size(),
2798 StartLoc, EndLoc);
2799 MsgExprs.push_back(Cls);
2800 break;
2801 }
2802
2803 case ObjCMessageExpr::SuperInstance:{
2804 MsgSendFlavor = MsgSendSuperFunctionDecl;
2805 if (MsgSendStretFlavor)
2806 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2807 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2808 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002809 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002810
2811 InitExprs.push_back(
2812 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002813 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002814 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002815 false,
John McCall7decc9e2010-11-18 06:31:45 +00002816 Context->getObjCIdType(),
2817 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002818 ); // set the 'receiver'.
2819
2820 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002821 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002822 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002823 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2824 &ClsExprs[0],
2825 ClsExprs.size(),
2826 StartLoc, EndLoc);
2827 // (Class)objc_getClass("CurrentClass")
2828 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2829 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002830 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002831 ClsExprs.clear();
2832 ClsExprs.push_back(ArgExpr);
2833 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2834 &ClsExprs[0], ClsExprs.size(),
2835 StartLoc, EndLoc);
2836
2837 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2838 // To turn off a warning, type-cast to 'id'
2839 InitExprs.push_back(
2840 // set 'super class', using class_getSuperclass().
2841 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002842 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002843 // struct objc_super
2844 QualType superType = getSuperStructType();
2845 Expr *SuperRep;
2846
Francois Pichet0706d202011-09-17 17:15:52 +00002847 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002848 SynthSuperConstructorFunctionDecl();
2849 // Simulate a constructor call...
2850 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002851 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002852 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002853 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002854 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002855 // The code for super is a little tricky to prevent collision with
2856 // the structure definition in the header. The rewriter has it's own
2857 // internal definition (__rw_objc_super) that is uses. This is why
2858 // we need the cast below. For example:
2859 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2860 //
John McCalle3027922010-08-25 11:45:40 +00002861 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002862 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002863 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002864 SourceLocation());
2865 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2866 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002867 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002868 } else {
2869 // (struct objc_super) { <exprs from above> }
2870 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002871 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002872 SourceLocation());
2873 TypeSourceInfo *superTInfo
2874 = Context->getTrivialTypeSourceInfo(superType);
2875 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002876 superType, VK_RValue, ILE,
2877 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002878 }
2879 MsgExprs.push_back(SuperRep);
2880 break;
2881 }
2882
2883 case ObjCMessageExpr::Instance: {
2884 // Remove all type-casts because it may contain objc-style types; e.g.
2885 // Foo<Proto> *.
2886 Expr *recExpr = Exp->getInstanceReceiver();
2887 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2888 recExpr = CE->getSubExpr();
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002889 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2890 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2891 ? CK_BlockPointerToObjCPointerCast
2892 : CK_CPointerToObjCPointerCast;
2893
Douglas Gregor9a129192010-04-21 00:45:42 +00002894 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002895 CK, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002896 MsgExprs.push_back(recExpr);
2897 break;
2898 }
2899 }
2900
Steve Naroffa397efd2007-11-03 11:27:19 +00002901 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002902 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002903 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroff574440f2007-10-24 22:48:43 +00002904 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002905 &SelExprs[0], SelExprs.size(),
2906 StartLoc,
2907 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002908 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002909
Steve Naroff574440f2007-10-24 22:48:43 +00002910 // Now push any user supplied arguments.
2911 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002912 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002913 // Make all implicit casts explicit...ICE comes in handy:-)
2914 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2915 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahanian8f490332011-02-26 01:31:36 +00002916 QualType type = ICE->getType();
2917 if (needToScanForQualifiers(type))
2918 type = Context->getObjCIdType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002919 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002920 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian9e7dbd12011-08-04 23:58:03 +00002921 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall9320b872011-09-09 05:25:32 +00002922 CastKind CK;
2923 if (SubExpr->getType()->isIntegralType(*Context) &&
2924 type->isBooleanType()) {
2925 CK = CK_IntegralToBoolean;
2926 } else if (type->isObjCObjectPointerType()) {
2927 if (SubExpr->getType()->isBlockPointerType()) {
2928 CK = CK_BlockPointerToObjCPointerCast;
2929 } else if (SubExpr->getType()->isPointerType()) {
2930 CK = CK_CPointerToObjCPointerCast;
2931 } else {
2932 CK = CK_BitCast;
2933 }
2934 } else {
2935 CK = CK_BitCast;
2936 }
2937
2938 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002939 }
2940 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002941 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002942 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002943 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002944 userExpr = CE->getSubExpr();
John McCall9320b872011-09-09 05:25:32 +00002945 CastKind CK;
2946 if (userExpr->getType()->isIntegralType(*Context)) {
2947 CK = CK_IntegralToPointer;
2948 } else if (userExpr->getType()->isBlockPointerType()) {
2949 CK = CK_BlockPointerToObjCPointerCast;
2950 } else if (userExpr->getType()->isPointerType()) {
2951 CK = CK_CPointerToObjCPointerCast;
2952 } else {
2953 CK = CK_BitCast;
2954 }
John McCall97513962010-01-15 18:39:57 +00002955 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall9320b872011-09-09 05:25:32 +00002956 CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002957 }
Mike Stump11289f42009-09-09 15:08:12 +00002958 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002959 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002960 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2961 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002962 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002963 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002964 }
Steve Narofff36987c2007-11-04 22:37:50 +00002965 // Generate the funky cast.
2966 CastExpr *cast;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002967 SmallVector<QualType, 8> ArgTypes;
Steve Narofff36987c2007-11-04 22:37:50 +00002968 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002969
Steve Narofff36987c2007-11-04 22:37:50 +00002970 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002971 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2972 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2973 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002974 ArgTypes.push_back(Context->getObjCIdType());
2975 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002976 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002977 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002978 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2979 E = OMD->param_end(); PI != E; ++PI) {
2980 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002981 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002982 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002983 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002984 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00002985 ArgTypes.push_back(t);
2986 }
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +00002987 returnType = Exp->getType();
2988 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002989 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00002990 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002991 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002992 }
2993 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002994 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002995
Steve Narofff36987c2007-11-04 22:37:50 +00002996 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002997 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00002998 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002999
Mike Stump11289f42009-09-09 15:08:12 +00003000 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00003001 // If we don't do this cast, we get the following bizarre warning/note:
3002 // xx.m:13: warning: function called through a non-compatible type
3003 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00003004 cast = NoTypeInfoCStyleCastExpr(Context,
3005 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003006 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00003007
Steve Narofff36987c2007-11-04 22:37:50 +00003008 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003009 // If we don't have a method decl, force a variadic cast.
3010 const ObjCMethodDecl *MD = Exp->getMethodDecl();
John McCalldb40c7f2010-12-14 08:05:40 +00003011 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003012 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Steve Narofff36987c2007-11-04 22:37:50 +00003013 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003014 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003015 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003016
3017 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003018 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003019
John McCall9dd450b2009-09-21 23:43:11 +00003020 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003021 CallExpr *CE = new (Context)
3022 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003023 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003024 if (MsgSendStretFlavor) {
3025 // We have the method which returns a struct/union. Must also generate
3026 // call to objc_msgSend_stret and hang both varieties on a conditional
3027 // expression which dictate which one to envoke depending on size of
3028 // method's return type.
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00003029
3030 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3031 msgSendType, returnType,
3032 ArgTypes, MsgExprs,
3033 Exp->getMethodDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003034
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003035 // Build sizeof(returnType)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003036 UnaryExprOrTypeTraitExpr *sizeofExpr =
3037 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3038 Context->getTrivialTypeSourceInfo(returnType),
3039 Context->getSizeType(), SourceLocation(),
3040 SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003041 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3042 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3043 // For X86 it is more complicated and some kind of target specific routine
3044 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003045 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003046 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003047 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3048 llvm::APInt(IntSize, 8),
3049 Context->IntTy,
3050 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00003051 BinaryOperator *lessThanExpr =
3052 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00003053 VK_RValue, OK_Ordinary, SourceLocation(),
3054 false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003055 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003056 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003057 new (Context) ConditionalOperator(lessThanExpr,
3058 SourceLocation(), CE,
John McCallc07a0c72011-02-17 10:25:35 +00003059 SourceLocation(), STCE,
John McCall4bc41ae2010-11-18 19:01:18 +00003060 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003061 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3062 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003063 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003064 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003065 return ReplacingStmt;
3066}
3067
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003068Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003069 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3070 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003071
Steve Naroff574440f2007-10-24 22:48:43 +00003072 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003073 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003074
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003075 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003076 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003077}
3078
Steve Naroffd9803712009-04-29 16:37:50 +00003079// typedef struct objc_object Protocol;
3080QualType RewriteObjC::getProtocolType() {
3081 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003082 TypeSourceInfo *TInfo
3083 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003084 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003085 SourceLocation(), SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003086 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003087 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003088 }
3089 return Context->getTypeDeclType(ProtocolTypeDecl);
3090}
3091
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003092/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003093/// a synthesized/forward data reference (to the protocol's metadata).
3094/// The forward references (and metadata) are generated in
3095/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003096Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003097 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3098 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003099 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003100 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003101 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003102 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3103 VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003104 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003105 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003106 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003107 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003108 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003109 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003110 ReplaceStmt(Exp, castExpr);
Douglas Gregor33b24292012-01-01 18:09:12 +00003111 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003112 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003113 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003114
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003115}
3116
Mike Stump11289f42009-09-09 15:08:12 +00003117bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003118 const char *endBuf) {
3119 while (startBuf < endBuf) {
3120 if (*startBuf == '#') {
3121 // Skip whitespace.
3122 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3123 ;
3124 if (!strncmp(startBuf, "if", strlen("if")) ||
3125 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3126 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3127 !strncmp(startBuf, "define", strlen("define")) ||
3128 !strncmp(startBuf, "undef", strlen("undef")) ||
3129 !strncmp(startBuf, "else", strlen("else")) ||
3130 !strncmp(startBuf, "elif", strlen("elif")) ||
3131 !strncmp(startBuf, "endif", strlen("endif")) ||
3132 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3133 !strncmp(startBuf, "include", strlen("include")) ||
3134 !strncmp(startBuf, "import", strlen("import")) ||
3135 !strncmp(startBuf, "include_next", strlen("include_next")))
3136 return true;
3137 }
3138 startBuf++;
3139 }
3140 return false;
3141}
3142
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003143/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003144/// an objective-c class with ivars.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003145void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003146 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003147 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003148 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003149 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003150 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003151 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003152 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003153 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003154 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003155 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor16408322011-12-15 22:34:59 +00003156 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump11289f42009-09-09 15:08:12 +00003157
Steve Naroffdde78982007-11-14 19:25:57 +00003158 const char *startBuf = SM->getCharacterData(LocStart);
3159 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003160
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003161 // If no ivars and no root or if its root, directly or indirectly,
3162 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregordc9166c2011-12-15 20:29:51 +00003163 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003164 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003165 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003166 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003167 return;
3168 }
Mike Stump11289f42009-09-09 15:08:12 +00003169
3170 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003171 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003172 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003173 Result += CDecl->getNameAsString();
Francois Pichet0706d202011-09-17 17:15:52 +00003174 if (LangOpts.MicrosoftExt)
Steve Naroffa1e115e2008-03-10 23:16:54 +00003175 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003176
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003177 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003178 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003179 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003180 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003181 // If the buffer contains preprocessor directives, we do more fine-grained
3182 // rewrites. This is intended to fix code that looks like (which occurs in
3183 // NSURL.h, for example):
3184 //
3185 // #ifdef XYZ
3186 // @interface Foo : NSObject
3187 // #else
3188 // @interface FooBar : NSObject
3189 // #endif
3190 // {
3191 // int i;
3192 // }
3193 // @end
3194 //
3195 // This clause is segregated to avoid breaking the common case.
3196 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003197 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00003198 CDecl->getAtStartLoc();
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003199 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003200 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003201
Chris Lattnerf5b77512009-02-20 18:18:36 +00003202 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003203 // advance to the end of the referenced protocols.
3204 while (endHeader < cursor && *endHeader != '>') endHeader++;
3205 endHeader++;
3206 }
3207 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003208 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003209 } else {
3210 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003211 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003212 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003213 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003214 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003215 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003216 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003217 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003218 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003219
Steve Naroffdde78982007-11-14 19:25:57 +00003220 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003221 SourceLocation OnePastCurly =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003222 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003223 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003224 }
3225 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003226
Steve Naroffdde78982007-11-14 19:25:57 +00003227 // Now comment out any visibility specifiers.
3228 while (cursor < endBuf) {
3229 if (*cursor == '@') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003230 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003231 // Skip whitespace.
3232 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3233 /*scan*/;
3234
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003235 // FIXME: presence of @public, etc. inside comment results in
3236 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003237 if (!strncmp(cursor, "public", strlen("public")) ||
3238 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003239 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003240 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003241 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003242 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003243 // FIXME: If there are cases where '<' is used in ivar declaration part
3244 // of user code, then scan the ivar list and use needToScanForQualifiers
3245 // for type checking.
3246 else if (*cursor == '<') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003247 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003248 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003249 cursor = strchr(cursor, '>');
3250 cursor++;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003251 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003252 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003253 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003254 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003255 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003256 }
Steve Naroffdde78982007-11-14 19:25:57 +00003257 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003258 }
Steve Naroffdde78982007-11-14 19:25:57 +00003259 // Don't forget to add a ';'!!
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003260 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003261 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003262 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003263 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003264 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003265 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003266 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003267 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003268 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003269 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003270 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003271 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikie83d382b2011-09-23 05:06:16 +00003272 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003273}
3274
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003275//===----------------------------------------------------------------------===//
3276// Meta Data Emission
3277//===----------------------------------------------------------------------===//
3278
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003279
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003280/// RewriteImplementations - This routine rewrites all method implementations
3281/// and emits meta-data.
3282
Steve Narofff8cfd162008-11-13 20:07:04 +00003283void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003284 int ClsDefCount = ClassImplementation.size();
3285 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003286
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003287 // Rewrite implemented methods
3288 for (int i = 0; i < ClsDefCount; i++)
3289 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003290
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003291 for (int i = 0; i < CatDefCount; i++)
3292 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003293}
Mike Stump11289f42009-09-09 15:08:12 +00003294
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003295void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3296 const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003297 ValueDecl *VD, bool def) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003298 assert(BlockByRefDeclNo.count(VD) &&
3299 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003300 if (def)
3301 ResultStr += "struct ";
3302 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003303 "_" + utostr(BlockByRefDeclNo[VD]) ;
3304}
3305
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003306static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3307 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3308 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3309 return false;
3310}
3311
Steve Naroff677ab3a2008-10-27 17:20:55 +00003312std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003313 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003314 std::string Tag) {
3315 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00003316 QualType RT = AFT->getReturnType();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003317 std::string StructRef = "struct " + Tag;
Douglas Gregorc0b07282011-09-27 22:38:19 +00003318 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00003319 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003320
Steve Naroff677ab3a2008-10-27 17:20:55 +00003321 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003322
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003323 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003324 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003325 // block (to reference imported block decl refs).
3326 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003327 } else if (BD->param_empty()) {
3328 S += "(" + StructRef + " *__cself)";
3329 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003330 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003331 assert(FT && "SynthesizeBlockFunc: No function proto");
3332 S += '(';
3333 // first add the implicit argument.
3334 S += StructRef + " *__cself, ";
3335 std::string ParamStr;
3336 for (BlockDecl::param_iterator AI = BD->param_begin(),
3337 E = BD->param_end(); AI != E; ++AI) {
3338 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003339 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003340 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00003341 (void)convertBlockPointerToFunctionPointer(QT);
3342 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003343 S += ParamStr;
3344 }
3345 if (FT->isVariadic()) {
3346 if (!BD->param_empty()) S += ", ";
3347 S += "...";
3348 }
3349 S += ')';
3350 }
3351 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003352
Steve Naroff677ab3a2008-10-27 17:20:55 +00003353 // Create local declarations to avoid rewriting all closure decl ref exprs.
3354 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00003355 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003356 E = BlockByRefDecls.end(); I != E; ++I) {
3357 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003358 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003359 std::string TypeString;
3360 RewriteByRefString(TypeString, Name, (*I));
3361 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003362 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003363 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003364 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003365 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003366 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003367 E = BlockByCopyDecls.end(); I != E; ++I) {
3368 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003369 // Handle nested closure invocation. For example:
3370 //
3371 // void (^myImportedClosure)(void);
3372 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003373 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003374 // void (^anotherClosure)(void);
3375 // anotherClosure = ^(void) {
3376 // myImportedClosure(); // import and invoke the closure
3377 // };
3378 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003379 if (isTopLevelBlockPointerType((*I)->getType())) {
3380 RewriteBlockPointerTypeVariable(S, (*I));
3381 S += " = (";
3382 RewriteBlockPointerType(S, (*I)->getType());
3383 S += ")";
3384 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3385 }
3386 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00003387 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003388 QualType QT = (*I)->getType();
3389 if (HasLocalVariableExternalStorage(*I))
3390 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003391 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003392 S += Name + " = __cself->" +
3393 (*I)->getNameAsString() + "; // bound by copy\n";
3394 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003395 }
3396 std::string RewrittenStr = RewrittenBlockExprs[CE];
3397 const char *cstr = RewrittenStr.c_str();
3398 while (*cstr++ != '{') ;
3399 S += cstr;
3400 S += "\n";
3401 return S;
3402}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003403
Steve Naroff677ab3a2008-10-27 17:20:55 +00003404std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003405 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003406 std::string Tag) {
3407 std::string StructRef = "struct " + Tag;
3408 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003409
Steve Naroff677ab3a2008-10-27 17:20:55 +00003410 S += funcName;
3411 S += "_block_copy_" + utostr(i);
3412 S += "(" + StructRef;
3413 S += "*dst, " + StructRef;
3414 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003415 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003416 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003417 ValueDecl *VD = (*I);
Steve Naroff61d879e2008-12-16 15:50:30 +00003418 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003419 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003420 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003421 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003422 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003423 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003424 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003425 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003426 else
3427 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003428 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003429 S += "}\n";
3430
Steve Naroff677ab3a2008-10-27 17:20:55 +00003431 S += "\nstatic void __";
3432 S += funcName;
3433 S += "_block_dispose_" + utostr(i);
3434 S += "(" + StructRef;
3435 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003436 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003437 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003438 ValueDecl *VD = (*I);
Steve Naroff61d879e2008-12-16 15:50:30 +00003439 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003440 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003441 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003442 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003443 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003444 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003445 else
3446 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003447 }
Mike Stump11289f42009-09-09 15:08:12 +00003448 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003449 return S;
3450}
3451
Steve Naroff30484702009-12-06 21:14:13 +00003452std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3453 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003454 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003455 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003456
Steve Naroff677ab3a2008-10-27 17:20:55 +00003457 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003458 S += " struct " + Desc;
3459 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003460
Steve Naroff30484702009-12-06 21:14:13 +00003461 Constructor += "(void *fp, "; // Invoke function pointer.
3462 Constructor += "struct " + Desc; // Descriptor pointer.
3463 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003464
Steve Naroff677ab3a2008-10-27 17:20:55 +00003465 if (BlockDeclRefs.size()) {
3466 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003467 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003468 E = BlockByCopyDecls.end(); I != E; ++I) {
3469 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003470 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003471 std::string ArgName = "_" + FieldName;
3472 // Handle nested closure invocation. For example:
3473 //
3474 // void (^myImportedBlock)(void);
3475 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003476 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003477 // void (^anotherBlock)(void);
3478 // anotherBlock = ^(void) {
3479 // myImportedBlock(); // import and invoke the closure
3480 // };
3481 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003482 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003483 S += "struct __block_impl *";
3484 Constructor += ", void *" + ArgName;
3485 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003486 QualType QT = (*I)->getType();
3487 if (HasLocalVariableExternalStorage(*I))
3488 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003489 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3490 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003491 Constructor += ", " + ArgName;
3492 }
3493 S += FieldName + ";\n";
3494 }
3495 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003496 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003497 E = BlockByRefDecls.end(); I != E; ++I) {
3498 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003499 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003500 std::string ArgName = "_" + FieldName;
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003501 {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003502 std::string TypeString;
3503 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003504 TypeString += " *";
3505 FieldName = TypeString + FieldName;
3506 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003507 Constructor += ", " + ArgName;
3508 }
3509 S += FieldName + "; // by ref\n";
3510 }
3511 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003512 Constructor += ", int flags=0)";
3513 // Initialize all "by copy" arguments.
3514 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00003515 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003516 E = BlockByCopyDecls.end(); I != E; ++I) {
3517 std::string Name = (*I)->getNameAsString();
3518 if (firsTime) {
3519 Constructor += " : ";
3520 firsTime = false;
3521 }
3522 else
3523 Constructor += ", ";
3524 if (isTopLevelBlockPointerType((*I)->getType()))
3525 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3526 else
3527 Constructor += Name + "(_" + Name + ")";
3528 }
3529 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00003530 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003531 E = BlockByRefDecls.end(); I != E; ++I) {
3532 std::string Name = (*I)->getNameAsString();
3533 if (firsTime) {
3534 Constructor += " : ";
3535 firsTime = false;
3536 }
3537 else
3538 Constructor += ", ";
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003539 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003540 }
3541
3542 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003543 if (GlobalVarDecl)
3544 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3545 else
3546 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003547 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003548
Steve Naroff30484702009-12-06 21:14:13 +00003549 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003550 } else {
3551 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003552 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003553 if (GlobalVarDecl)
3554 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3555 else
3556 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003557 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3558 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003559 }
3560 Constructor += " ";
3561 Constructor += "}\n";
3562 S += Constructor;
3563 S += "};\n";
3564 return S;
3565}
3566
Steve Naroff30484702009-12-06 21:14:13 +00003567std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3568 std::string ImplTag, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003569 StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00003570 unsigned hasCopy) {
3571 std::string S = "\nstatic struct " + DescTag;
3572
3573 S += " {\n unsigned long reserved;\n";
3574 S += " unsigned long Block_size;\n";
3575 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003576 S += " void (*copy)(struct ";
3577 S += ImplTag; S += "*, struct ";
3578 S += ImplTag; S += "*);\n";
3579
3580 S += " void (*dispose)(struct ";
3581 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003582 }
3583 S += "} ";
3584
3585 S += DescTag + "_DATA = { 0, sizeof(struct ";
3586 S += ImplTag + ")";
3587 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00003588 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3589 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00003590 }
3591 S += "};\n";
3592 return S;
3593}
3594
Steve Naroff677ab3a2008-10-27 17:20:55 +00003595void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003596 StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003597 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00003598 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003599 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003600 bool RewriteSC = (GlobalVarDecl &&
3601 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00003602 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003603 GlobalVarDecl->getType().getCVRQualifiers());
3604 if (RewriteSC) {
3605 std::string SC(" void __");
3606 SC += GlobalVarDecl->getNameAsString();
3607 SC += "() {}";
3608 InsertText(FunLocStart, SC);
3609 }
3610
Steve Naroff677ab3a2008-10-27 17:20:55 +00003611 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003612 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3613 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003614 // Need to copy-in the inner copied-in variables not actually used in this
3615 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003616 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00003617 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003618 ValueDecl *VD = Exp->getDecl();
3619 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00003620 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003621 BlockByCopyDeclsPtrSet.insert(VD);
3622 BlockByCopyDecls.push_back(VD);
3623 }
John McCall113bee02012-03-10 09:33:50 +00003624 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003625 BlockByRefDeclsPtrSet.insert(VD);
3626 BlockByRefDecls.push_back(VD);
3627 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003628 // imported objects in the inner blocks not used in the outer
3629 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00003630 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003631 VD->getType()->isObjCObjectPointerType() ||
3632 VD->getType()->isBlockPointerType())
3633 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003634 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003635
Daniel Dunbar56df9772010-08-17 22:39:59 +00003636 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3637 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003638
Steve Naroff30484702009-12-06 21:14:13 +00003639 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003640
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003641 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003642
Steve Naroff30484702009-12-06 21:14:13 +00003643 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00003644
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003645 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003646
3647 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00003648 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003649 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003650 }
Steve Naroff30484702009-12-06 21:14:13 +00003651 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3652 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003653 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00003654
Steve Naroff677ab3a2008-10-27 17:20:55 +00003655 BlockDeclRefs.clear();
3656 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003657 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003658 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003659 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003660 ImportedBlockDecls.clear();
3661 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003662 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003663 // Must insert any 'const/volatile/static here. Since it has been
3664 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003665 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00003666 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003667 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003668 if (GlobalVarDecl->getType().isConstQualified())
3669 SC += "const ";
3670 if (GlobalVarDecl->getType().isVolatileQualified())
3671 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003672 if (GlobalVarDecl->getType().isRestrictQualified())
3673 SC += "restrict ";
3674 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003675 }
3676
Steve Naroff677ab3a2008-10-27 17:20:55 +00003677 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003678 InnerDeclRefsCount.clear();
3679 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003680 RewrittenBlockExprs.clear();
3681}
3682
3683void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3684 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003685 StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00003686
Steve Naroff677ab3a2008-10-27 17:20:55 +00003687 SynthesizeBlockLiterals(FunLocStart, FuncName);
3688}
3689
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003690static void BuildUniqueMethodName(std::string &Name,
3691 ObjCMethodDecl *MD) {
3692 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00003693 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003694 Name += "__" + MD->getSelector().getAsString();
3695 // Convert colons to underscores.
3696 std::string::size_type loc = 0;
3697 while ((loc = Name.find(":", loc)) != std::string::npos)
3698 Name.replace(loc, 1, "_");
3699}
3700
Steve Naroff677ab3a2008-10-27 17:20:55 +00003701void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003702 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3703 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00003704 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003705 std::string FuncName;
3706 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00003707 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003708}
3709
3710void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00003711 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff677ab3a2008-10-27 17:20:55 +00003712 if (*CI) {
3713 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3714 GetBlockDeclRefExprs(CBE->getBody());
3715 else
3716 GetBlockDeclRefExprs(*CI);
3717 }
3718 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003719 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3720 if (DRE->refersToEnclosingLocal()) {
3721 // FIXME: Handle enums.
3722 if (!isa<FunctionDecl>(DRE->getDecl()))
3723 BlockDeclRefs.push_back(DRE);
3724 if (HasLocalVariableExternalStorage(DRE->getDecl()))
3725 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003726 }
John McCall113bee02012-03-10 09:33:50 +00003727 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003728
Steve Naroff677ab3a2008-10-27 17:20:55 +00003729 return;
3730}
3731
Craig Topper5603df42013-07-05 19:34:19 +00003732void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3733 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003734 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall8322c3a2011-02-13 04:07:26 +00003735 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003736 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003737 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3738 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003739 GetInnerBlockDeclRefExprs(CBE->getBody(),
3740 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003741 InnerContexts);
3742 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003743 else
3744 GetInnerBlockDeclRefExprs(*CI,
3745 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003746 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003747
3748 }
3749 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003750 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3751 if (DRE->refersToEnclosingLocal()) {
3752 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3753 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3754 InnerBlockDeclRefs.push_back(DRE);
3755 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3756 if (Var->isFunctionOrMethodVarDecl())
3757 ImportedLocalExternalDecls.insert(Var);
3758 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003759 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003760
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003761 return;
3762}
3763
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003764/// convertFunctionTypeOfBlocks - This routine converts a function type
3765/// whose result type may be a block pointer or whose argument type(s)
Chris Lattner57540c52011-04-15 05:22:18 +00003766/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003767/// all block pointers to function pointers.
3768QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3769 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3770 // FTP will be null for closures that don't take arguments.
3771 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003772 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00003773 QualType Res = FT->getReturnType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003774 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003775
3776 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00003777 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
3778 E = FTP->param_type_end();
3779 I && (I != E); ++I) {
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003780 QualType t = *I;
3781 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003782 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003783 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003784 ArgTypes.push_back(t);
3785 }
3786 }
3787 QualType FuncType;
3788 // FIXME. Does this work if block takes no argument but has a return type
3789 // which is of block type?
3790 if (HasBlockType)
Jordan Rose5c382722013-03-08 21:51:21 +00003791 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003792 else FuncType = QualType(FT, 0);
3793 return FuncType;
3794}
3795
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003796Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003797 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003798 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003799
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003800 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003801 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003802 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003803 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003804 }
3805 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3806 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3807 }
3808 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3809 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3810 else if (const ConditionalOperator *CEXPR =
3811 dyn_cast<ConditionalOperator>(BlockExp)) {
3812 Expr *LHSExp = CEXPR->getLHS();
3813 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3814 Expr *RHSExp = CEXPR->getRHS();
3815 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3816 Expr *CONDExp = CEXPR->getCond();
3817 ConditionalOperator *CondExpr =
3818 new (Context) ConditionalOperator(CONDExp,
3819 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003820 SourceLocation(), cast<Expr>(RHSStmt),
John McCall4bc41ae2010-11-18 19:01:18 +00003821 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003822 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00003823 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3824 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCallfe96e0b2011-11-06 09:01:30 +00003825 } else if (const PseudoObjectExpr *POE
3826 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3827 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003828 } else {
3829 assert(1 && "RewriteBlockClass: Bad type");
3830 }
3831 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00003832 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003833 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003834 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003835 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003836
Abramo Bagnara6150c882010-05-11 21:36:43 +00003837 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003838 SourceLocation(), SourceLocation(),
Steve Naroff350b6652008-10-30 10:07:53 +00003839 &Context->Idents.get("__block_impl"));
3840 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00003841
Steve Naroff350b6652008-10-30 10:07:53 +00003842 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003843 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003844
Steve Naroff350b6652008-10-30 10:07:53 +00003845 // Push the block argument type.
3846 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003847 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00003848 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
3849 E = FTP->param_type_end();
3850 I && (I != E); ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003851 QualType t = *I;
3852 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003853 if (!convertBlockPointerToFunctionPointer(t))
3854 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00003855 ArgTypes.push_back(t);
3856 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003857 }
Steve Naroff350b6652008-10-30 10:07:53 +00003858 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003859 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Mike Stump11289f42009-09-09 15:08:12 +00003860
Steve Naroff350b6652008-10-30 10:07:53 +00003861 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00003862
John McCall97513962010-01-15 18:39:57 +00003863 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00003864 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003865 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00003866 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003867 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3868 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00003869 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00003870
Douglas Gregor91f84212008-12-11 16:49:14 +00003871 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003872 SourceLocation(),
3873 &Context->Idents.get("FuncPtr"),
3874 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00003875 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003876 ICIS_NoInit);
Ted Kremenek5a201952009-02-07 01:47:29 +00003877 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003878 FD->getType(), VK_LValue,
3879 OK_Ordinary);
Mike Stump11289f42009-09-09 15:08:12 +00003880
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003881
John McCall97513962010-01-15 18:39:57 +00003882 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCallf608deb2010-11-15 09:46:46 +00003883 CK_BitCast, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00003884 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00003885
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003886 SmallVector<Expr*, 8> BlkExprs;
Steve Naroff350b6652008-10-30 10:07:53 +00003887 // Add the implicit argument.
3888 BlkExprs.push_back(BlkCast);
3889 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003890 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003891 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003892 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003893 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00003894 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCall7decc9e2010-11-18 06:31:45 +00003895 Exp->getType(), VK_RValue,
3896 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00003897 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003898}
3899
Steve Naroffd9803712009-04-29 16:37:50 +00003900// We need to return the rewritten expression to handle cases where the
3901// BlockDeclRefExpr is embedded in another expression being rewritten.
3902// For example:
3903//
3904// int main() {
3905// __block Foo *f;
3906// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00003907//
Steve Naroffd9803712009-04-29 16:37:50 +00003908// void (^myblock)() = ^() {
3909// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3910// i = 77;
3911// };
3912//}
John McCall113bee02012-03-10 09:33:50 +00003913Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00003914 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003915 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00003916 ValueDecl *VD = DeclRefExp->getDecl();
3917 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003918
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003919 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003920 SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003921 &Context->Idents.get("__forwarding"),
3922 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00003923 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003924 ICIS_NoInit);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003925 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3926 FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003927 FD->getType(), VK_LValue,
3928 OK_Ordinary);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003929
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003930 StringRef Name = VD->getName();
Abramo Bagnaradff19302011-03-08 08:55:46 +00003931 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003932 &Context->Idents.get(Name),
3933 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00003934 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003935 ICIS_NoInit);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003936 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003937 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003938
3939
3940
Steve Narofff26a1d42009-02-02 17:19:26 +00003941 // Need parens to enforce precedence.
Fariborz Jahanian5bba75f2011-04-01 19:19:28 +00003942 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3943 DeclRefExp->getExprLoc(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003944 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003945 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00003946 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003947}
3948
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003949// Rewrites the imported local variable V with external storage
3950// (static, extern, etc.) as *V
3951//
3952Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3953 ValueDecl *VD = DRE->getDecl();
3954 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3955 if (!ImportedLocalExternalDecls.count(Var))
3956 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00003957 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3958 VK_LValue, OK_Ordinary,
3959 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003960 // Need parens to enforce precedence.
3961 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3962 Exp);
3963 ReplaceStmt(DRE, PE);
3964 return PE;
3965}
3966
Steve Naroffc989a7b2008-11-03 23:29:32 +00003967void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3968 SourceLocation LocStart = CE->getLParenLoc();
3969 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00003970
3971 // Need to avoid trying to rewrite synthesized casts.
3972 if (LocStart.isInvalid())
3973 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00003974 // Need to avoid trying to rewrite casts contained in macros.
3975 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3976 return;
Mike Stump11289f42009-09-09 15:08:12 +00003977
Steve Naroff677ab3a2008-10-27 17:20:55 +00003978 const char *startBuf = SM->getCharacterData(LocStart);
3979 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003980 QualType QT = CE->getType();
3981 const Type* TypePtr = QT->getAs<Type>();
3982 if (isa<TypeOfExprType>(TypePtr)) {
3983 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3984 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3985 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00003986 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003987 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003988 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003989 return;
3990 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003991 // advance the location to startArgList.
3992 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00003993
Steve Naroff677ab3a2008-10-27 17:20:55 +00003994 while (*argPtr++ && (argPtr < endBuf)) {
3995 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00003996 case '^':
3997 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003998 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003999 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004000 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004001 }
4002 }
4003 return;
4004}
4005
4006void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4007 SourceLocation DeclLoc = FD->getLocation();
4008 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004009
Steve Naroff677ab3a2008-10-27 17:20:55 +00004010 // We have 1 or more arguments that have closure pointers.
4011 const char *startBuf = SM->getCharacterData(DeclLoc);
4012 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004013
Steve Naroff677ab3a2008-10-27 17:20:55 +00004014 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004015
Steve Naroff677ab3a2008-10-27 17:20:55 +00004016 parenCount++;
4017 // advance the location to startArgList.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004018 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004019 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004020
Steve Naroff677ab3a2008-10-27 17:20:55 +00004021 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004022
Steve Naroff677ab3a2008-10-27 17:20:55 +00004023 while (*argPtr++ && parenCount) {
4024 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004025 case '^':
4026 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004027 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004028 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004029 break;
4030 case '(':
4031 parenCount++;
4032 break;
4033 case ')':
4034 parenCount--;
4035 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004036 }
4037 }
4038 return;
4039}
4040
4041bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004042 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004043 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004044 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004045 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004046 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004047 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004048 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004049 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004050 }
4051 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004052 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4053 E = FTP->param_type_end();
4054 I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004055 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004056 return true;
4057 }
4058 return false;
4059}
4060
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004061bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4062 const FunctionProtoType *FTP;
4063 const PointerType *PT = QT->getAs<PointerType>();
4064 if (PT) {
4065 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4066 } else {
4067 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4068 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4069 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4070 }
4071 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004072 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4073 E = FTP->param_type_end();
4074 I != E; ++I) {
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004075 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004076 return true;
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004077 if ((*I)->isObjCObjectPointerType() &&
4078 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4079 return true;
4080 }
4081
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004082 }
4083 return false;
4084}
4085
Ted Kremenek5a201952009-02-07 01:47:29 +00004086void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4087 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004088 const char *argPtr = strchr(Name, '(');
4089 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004090
Steve Naroff677ab3a2008-10-27 17:20:55 +00004091 LParen = argPtr; // output the start.
4092 argPtr++; // skip past the left paren.
4093 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004094
Steve Naroff677ab3a2008-10-27 17:20:55 +00004095 while (*argPtr && parenCount) {
4096 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004097 case '(': parenCount++; break;
4098 case ')': parenCount--; break;
4099 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004100 }
4101 if (parenCount) argPtr++;
4102 }
4103 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4104 RParen = argPtr; // output the end
4105}
4106
4107void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4108 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4109 RewriteBlockPointerFunctionArgs(FD);
4110 return;
Mike Stump11289f42009-09-09 15:08:12 +00004111 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004112 // Handle Variables and Typedefs.
4113 SourceLocation DeclLoc = ND->getLocation();
4114 QualType DeclT;
4115 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4116 DeclT = VD->getType();
Richard Smithdda56e42011-04-15 14:24:37 +00004117 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004118 DeclT = TDD->getUnderlyingType();
4119 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4120 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004121 else
David Blaikie83d382b2011-09-23 05:06:16 +00004122 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004123
Steve Naroff677ab3a2008-10-27 17:20:55 +00004124 const char *startBuf = SM->getCharacterData(DeclLoc);
4125 const char *endBuf = startBuf;
4126 // scan backward (from the decl location) for the end of the previous decl.
4127 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4128 startBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004129 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004130 std::string buf;
4131 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004132 // *startBuf != '^' if we are dealing with a pointer to function that
4133 // may take block argument types (which will be handled below).
4134 if (*startBuf == '^') {
4135 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004136 buf = '*';
4137 startBuf++;
4138 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004139 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004140 while (*startBuf != ')') {
4141 buf += *startBuf;
4142 startBuf++;
4143 OrigLength++;
4144 }
4145 buf += ')';
4146 OrigLength++;
4147
4148 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4149 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004150 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004151 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00004152 DeclLoc = ND->getLocation();
4153 startBuf = SM->getCharacterData(DeclLoc);
4154 const char *argListBegin, *argListEnd;
4155 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4156 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004157 if (*argListBegin == '^')
4158 buf += '*';
4159 else if (*argListBegin == '<') {
4160 buf += "/*";
4161 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004162 OrigLength++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004163 while (*argListBegin != '>') {
4164 buf += *argListBegin++;
4165 OrigLength++;
4166 }
4167 buf += *argListBegin;
4168 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004169 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004170 else
4171 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004172 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004173 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004174 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004175 buf += ')';
4176 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004177 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004178 ReplaceText(Start, OrigLength, buf);
4179
Steve Naroff677ab3a2008-10-27 17:20:55 +00004180 return;
4181}
4182
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004183
4184/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4185/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4186/// struct Block_byref_id_object *src) {
4187/// _Block_object_assign (&_dest->object, _src->object,
4188/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4189/// [|BLOCK_FIELD_IS_WEAK]) // object
4190/// _Block_object_assign(&_dest->object, _src->object,
4191/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4192/// [|BLOCK_FIELD_IS_WEAK]) // block
4193/// }
4194/// And:
4195/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4196/// _Block_object_dispose(_src->object,
4197/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4198/// [|BLOCK_FIELD_IS_WEAK]) // object
4199/// _Block_object_dispose(_src->object,
4200/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4201/// [|BLOCK_FIELD_IS_WEAK]) // block
4202/// }
4203
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004204std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4205 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004206 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004207 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004208 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004209 CopyDestroyCache.insert(flag);
4210 S = "static void __Block_byref_id_object_copy_";
4211 S += utostr(flag);
4212 S += "(void *dst, void *src) {\n";
4213
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004214 // offset into the object pointer is computed as:
4215 // void * + void* + int + int + void* + void *
4216 unsigned IntSize =
4217 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4218 unsigned VoidPtrSize =
4219 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4220
Ken Dyckd9c83e62011-04-30 16:08:27 +00004221 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004222 S += " _Block_object_assign((char*)dst + ";
4223 S += utostr(offset);
4224 S += ", *(void * *) ((char*)src + ";
4225 S += utostr(offset);
4226 S += "), ";
4227 S += utostr(flag);
4228 S += ");\n}\n";
4229
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004230 S += "static void __Block_byref_id_object_dispose_";
4231 S += utostr(flag);
4232 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004233 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4234 S += utostr(offset);
4235 S += "), ";
4236 S += utostr(flag);
4237 S += ");\n}\n";
4238 return S;
4239}
4240
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004241/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4242/// the declaration into:
4243/// struct __Block_byref_ND {
4244/// void *__isa; // NULL for everything except __weak pointers
4245/// struct __Block_byref_ND *__forwarding;
4246/// int32_t __flags;
4247/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004248/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4249/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004250/// typex ND;
4251/// };
4252///
4253/// It then replaces declaration of ND variable with:
4254/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4255/// __size=sizeof(struct __Block_byref_ND),
4256/// ND=initializer-if-any};
4257///
4258///
4259void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004260 // Insert declaration for the function in which block literal is
4261 // used.
4262 if (CurFunctionDeclToDeclareForBlock)
4263 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004264 int flag = 0;
4265 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004266 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00004267 if (DeclLoc.isInvalid())
4268 // If type location is missing, it is because of missing type (a warning).
4269 // Use variable's location which is good for this case.
4270 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004271 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004272 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00004273 X = SM->getExpansionLoc(X);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004274 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004275 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004276 std::string ByrefType;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004277 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004278 ByrefType += " {\n";
4279 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004280 RewriteByRefString(ByrefType, Name, ND);
4281 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004282 ByrefType += " int __flags;\n";
4283 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004284 // Add void *__Block_byref_id_object_copy;
4285 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004286 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004287 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004288 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004289 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4290 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004291 }
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004292
4293 QualType T = Ty;
4294 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregorc0b07282011-09-27 22:38:19 +00004295 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004296
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004297 ByrefType += " " + Name + ";\n";
4298 ByrefType += "};\n";
4299 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004300 SourceLocation FunLocStart;
4301 if (CurFunctionDef)
4302 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4303 else {
4304 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4305 FunLocStart = CurMethodDef->getLocStart();
4306 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004307 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004308 if (Ty.isObjCGCWeak()) {
4309 flag |= BLOCK_FIELD_IS_WEAK;
4310 isa = 1;
4311 }
4312
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004313 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004314 flag = BLOCK_BYREF_CALLER;
4315 QualType Ty = ND->getType();
4316 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4317 if (Ty->isBlockPointerType())
4318 flag |= BLOCK_FIELD_IS_BLOCK;
4319 else
4320 flag |= BLOCK_FIELD_IS_OBJECT;
4321 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004322 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004323 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004324 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004325
4326 // struct __Block_byref_ND ND =
4327 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4328 // initializer-if-any};
4329 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004330 unsigned flags = 0;
4331 if (HasCopyAndDispose)
4332 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004333 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004334 ByrefType.clear();
4335 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004336 std::string ForwardingCastType("(");
4337 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004338 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004339 ByrefType += " " + Name + " = {(void*)";
4340 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004341 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004342 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004343 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004344 ByrefType += "sizeof(";
4345 RewriteByRefString(ByrefType, Name, ND);
4346 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004347 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004348 ByrefType += ", __Block_byref_id_object_copy_";
4349 ByrefType += utostr(flag);
4350 ByrefType += ", __Block_byref_id_object_dispose_";
4351 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004352 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004353 ByrefType += "};\n";
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004354 unsigned nameSize = Name.size();
4355 // for block or function pointer declaration. Name is aleady
4356 // part of the declaration.
4357 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4358 nameSize = 1;
4359 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004360 }
4361 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004362 SourceLocation startLoc;
4363 Expr *E = ND->getInit();
4364 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4365 startLoc = ECE->getLParenLoc();
4366 else
4367 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00004368 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004369 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004370 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004371 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004372 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004373 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004374 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004375 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004376 ByrefType += "sizeof(";
4377 RewriteByRefString(ByrefType, Name, ND);
4378 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004379 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004380 ByrefType += "__Block_byref_id_object_copy_";
4381 ByrefType += utostr(flag);
4382 ByrefType += ", __Block_byref_id_object_dispose_";
4383 ByrefType += utostr(flag);
4384 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004385 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004386 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004387
4388 // Complete the newly synthesized compound expression by inserting a right
4389 // curly brace before the end of the declaration.
4390 // FIXME: This approach avoids rewriting the initializer expression. It
4391 // also assumes there is only one declarator. For example, the following
4392 // isn't currently supported by this routine (in general):
4393 //
4394 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4395 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00004396 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4397 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00004398 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4399 SourceLocation semiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004400 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00004401
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004402 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004403 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004404 return;
4405}
4406
Mike Stump11289f42009-09-09 15:08:12 +00004407void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004408 // Add initializers for any closure decl refs.
4409 GetBlockDeclRefExprs(Exp->getBody());
4410 if (BlockDeclRefs.size()) {
4411 // Unique all "by copy" declarations.
4412 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004413 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004414 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4415 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4416 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4417 }
4418 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004419 // Unique all "by ref" declarations.
4420 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004421 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004422 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4423 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4424 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4425 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004426 }
4427 // Find any imported blocks...they will need special attention.
4428 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004429 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004430 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00004431 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00004432 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00004433 }
4434}
4435
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004436FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004437 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004438 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004439 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4440 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004441 false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004442}
4443
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004444Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00004445 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004446 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofff4b992a2008-10-28 20:29:00 +00004447 Blocks.push_back(Exp);
4448
4449 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004450
4451 // Add inner imported variables now used in current block.
4452 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004453 if (!InnerBlockDeclRefs.empty()) {
4454 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00004455 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004456 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00004457 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004458 // We need to save the copied-in variables in nested
4459 // blocks because it is needed at the end for some of the API generations.
4460 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004461 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4462 BlockDeclRefs.push_back(Exp);
4463 BlockByCopyDeclsPtrSet.insert(VD);
4464 BlockByCopyDecls.push_back(VD);
4465 }
John McCall113bee02012-03-10 09:33:50 +00004466 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004467 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4468 BlockDeclRefs.push_back(Exp);
4469 BlockByRefDeclsPtrSet.insert(VD);
4470 BlockByRefDecls.push_back(VD);
4471 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004472 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004473 // Find any imported blocks...they will need special attention.
4474 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004475 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004476 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4477 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4478 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004479 }
4480 InnerDeclRefsCount.push_back(countOfInnerDecls);
4481
Steve Narofff4b992a2008-10-28 20:29:00 +00004482 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004483
Steve Narofff4b992a2008-10-28 20:29:00 +00004484 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004485 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004486 else if (CurMethodDef)
4487 BuildUniqueMethodName(FuncName, CurMethodDef);
4488 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004489 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004490
Steve Narofff4b992a2008-10-28 20:29:00 +00004491 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004492
Steve Narofff4b992a2008-10-28 20:29:00 +00004493 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4494 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004495
Steve Narofff4b992a2008-10-28 20:29:00 +00004496 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004497 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4498 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00004499
4500 FunctionDecl *FD;
4501 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004502
Benjamin Kramer60509af2013-09-09 14:48:42 +00004503 // Simulate a constructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00004504 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00004505 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCall7decc9e2010-11-18 06:31:45 +00004506 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004507
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004508 SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004509
Steve Naroffe2514232008-10-29 21:23:59 +00004510 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00004511 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00004512 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4513 VK_LValue, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004514 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004515 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004516 InitExprs.push_back(castExpr);
4517
Steve Naroff30484702009-12-06 21:14:13 +00004518 // Initialize the block descriptor.
4519 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004520
Abramo Bagnaradff19302011-03-08 08:55:46 +00004521 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4522 SourceLocation(), SourceLocation(),
4523 &Context->Idents.get(DescData.c_str()),
4524 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004525 SC_Static);
John McCall7decc9e2010-11-18 06:31:45 +00004526 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00004527 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCall7decc9e2010-11-18 06:31:45 +00004528 Context->VoidPtrTy,
4529 VK_LValue,
4530 SourceLocation()),
4531 UO_AddrOf,
4532 Context->getPointerType(Context->VoidPtrTy),
4533 VK_RValue, OK_Ordinary,
4534 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00004535 InitExprs.push_back(DescRefExpr);
4536
Steve Narofff4b992a2008-10-28 20:29:00 +00004537 // Add initializers for any closure decl refs.
4538 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004539 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004540 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004541 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004542 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004543 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004544 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00004545 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004546 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004547 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004548 if (HasLocalVariableExternalStorage(*I)) {
4549 QualType QT = (*I)->getType();
4550 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004551 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4552 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004553 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00004554 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004555 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004556 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004557 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004558 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004559 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004560 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004561 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004562 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004563 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004564 if (HasLocalVariableExternalStorage(*I)) {
4565 QualType QT = (*I)->getType();
4566 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004567 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4568 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004569 }
4570
Steve Narofff4b992a2008-10-28 20:29:00 +00004571 }
Mike Stump11289f42009-09-09 15:08:12 +00004572 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004573 }
4574 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004575 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004576 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004577 ValueDecl *ND = (*I);
4578 std::string Name(ND->getNameAsString());
4579 std::string RecName;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004580 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004581 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4582 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00004583 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004584 SourceLocation(), SourceLocation(),
4585 II);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004586 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4587 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4588
Daniel Dunbar56df9772010-08-17 22:39:59 +00004589 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004590 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004591 SourceLocation());
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004592 bool isNestedCapturedVar = false;
4593 if (block)
4594 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4595 ce = block->capture_end(); ci != ce; ++ci) {
4596 const VarDecl *variable = ci->getVariable();
4597 if (variable == ND && ci->isNested()) {
4598 assert (ci->isByRef() &&
4599 "SynthBlockInitExpr - captured block variable is not byref");
4600 isNestedCapturedVar = true;
4601 break;
4602 }
4603 }
4604 // captured nested byref variable has its address passed. Do not take
4605 // its address again.
4606 if (!isNestedCapturedVar)
4607 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00004608 Context->getPointerType(Exp->getType()),
4609 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004610 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004611 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004612 }
4613 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004614 if (ImportedBlockDecls.size()) {
4615 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4616 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004617 unsigned IntSize =
4618 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004619 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4620 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004621 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004622 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004623 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00004624 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00004625 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004626 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00004627 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004628 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004629 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004630 BlockDeclRefs.clear();
4631 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004632 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004633 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004634 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004635 ImportedBlockDecls.clear();
4636 return NewRep;
4637}
4638
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004639bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4640 if (const ObjCForCollectionStmt * CS =
4641 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4642 return CS->getElement() == DS;
4643 return false;
4644}
4645
Steve Narofff4b992a2008-10-28 20:29:00 +00004646//===----------------------------------------------------------------------===//
4647// Function Body / Expression rewriting
4648//===----------------------------------------------------------------------===//
4649
4650Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004651 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004652 isa<DoStmt>(S) || isa<ForStmt>(S))
4653 Stmts.push_back(S);
4654 else if (isa<ObjCForCollectionStmt>(S)) {
4655 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004656 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004657 }
Mike Stump11289f42009-09-09 15:08:12 +00004658
John McCallfe96e0b2011-11-06 09:01:30 +00004659 // Pseudo-object operations and ivar references need special
4660 // treatment because we're going to recursively rewrite them.
4661 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4662 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4663 return RewritePropertyOrImplicitSetter(PseudoOp);
4664 } else {
4665 return RewritePropertyOrImplicitGetter(PseudoOp);
4666 }
4667 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4668 return RewriteObjCIvarRefExpr(IvarRefExpr);
4669 }
4670
Steve Narofff4b992a2008-10-28 20:29:00 +00004671 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004672
Steve Narofff4b992a2008-10-28 20:29:00 +00004673 // Perform a bottom up rewrite of all children.
John McCall8322c3a2011-02-13 04:07:26 +00004674 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofff4b992a2008-10-28 20:29:00 +00004675 if (*CI) {
John McCallfe96e0b2011-11-06 09:01:30 +00004676 Stmt *childStmt = (*CI);
4677 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004678 if (newStmt) {
John McCallfe96e0b2011-11-06 09:01:30 +00004679 *CI = newStmt;
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004680 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00004681 }
Mike Stump11289f42009-09-09 15:08:12 +00004682
Steve Narofff4b992a2008-10-28 20:29:00 +00004683 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00004684 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004685 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4686 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004687 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004688 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004689 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00004690 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004691 Stmt *SaveCurrentBody = CurrentBody;
4692 CurrentBody = BE->getBody();
4693 PropParentMap = 0;
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004694 // block literal on rhs of a property-dot-sytax assignment
4695 // must be replaced by its synthesize ast so getRewrittenText
4696 // works as expected. In this case, what actually ends up on RHS
4697 // is the blockTranscribed which is the helper function for the
4698 // block literal; as in: self.c = ^() {[ace ARR];};
4699 bool saveDisableReplaceStmt = DisableReplaceStmt;
4700 DisableReplaceStmt = false;
Steve Narofff4b992a2008-10-28 20:29:00 +00004701 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004702 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004703 CurrentBody = SaveCurrentBody;
4704 PropParentMap = 0;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004705 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004706 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004707 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004708 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004709
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004710 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4711
Steve Narofff4b992a2008-10-28 20:29:00 +00004712 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004713 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004714 return blockTranscribed;
4715 }
4716 // Handle specific things.
4717 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4718 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004719
Steve Narofff4b992a2008-10-28 20:29:00 +00004720 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4721 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004722
Steve Narofff4b992a2008-10-28 20:29:00 +00004723 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4724 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004725
Steve Narofff4b992a2008-10-28 20:29:00 +00004726 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004727#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004728 // Before we rewrite it, put the original message expression in a comment.
4729 SourceLocation startLoc = MessExpr->getLocStart();
4730 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004731
Steve Narofff4b992a2008-10-28 20:29:00 +00004732 const char *startBuf = SM->getCharacterData(startLoc);
4733 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004734
Steve Narofff4b992a2008-10-28 20:29:00 +00004735 std::string messString;
4736 messString += "// ";
4737 messString.append(startBuf, endBuf-startBuf+1);
4738 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004739
4740 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004741 // InsertText(clang::SourceLocation, char const*, unsigned int).
4742 // InsertText(startLoc, messString.c_str(), messString.size());
4743 // Tried this, but it didn't work either...
4744 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004745#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004746 return RewriteMessageExpr(MessExpr);
4747 }
Mike Stump11289f42009-09-09 15:08:12 +00004748
Steve Narofff4b992a2008-10-28 20:29:00 +00004749 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4750 return RewriteObjCTryStmt(StmtTry);
4751
4752 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4753 return RewriteObjCSynchronizedStmt(StmtTry);
4754
4755 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4756 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004757
Steve Narofff4b992a2008-10-28 20:29:00 +00004758 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4759 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004760
4761 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004762 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004763 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004764 OrigStmtRange.getEnd());
4765 if (BreakStmt *StmtBreakStmt =
4766 dyn_cast<BreakStmt>(S))
4767 return RewriteBreakStmt(StmtBreakStmt);
4768 if (ContinueStmt *StmtContinueStmt =
4769 dyn_cast<ContinueStmt>(S))
4770 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004771
4772 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004773 // and cast exprs.
4774 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4775 // FIXME: What we're doing here is modifying the type-specifier that
4776 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004777 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004778 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4779 // the context of an ObjCForCollectionStmt. For example:
4780 // NSArray *someArray;
4781 // for (id <FooProtocol> index in someArray) ;
4782 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4783 // and it depends on the original text locations/positions.
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004784 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004785 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004786
Steve Narofff4b992a2008-10-28 20:29:00 +00004787 // Blocks rewrite rules.
4788 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4789 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004790 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004791 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004792 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004793 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004794 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004795 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004796 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004797 if (VD->hasAttr<BlocksAttr>()) {
4798 static unsigned uniqueByrefDeclCount = 0;
4799 assert(!BlockByRefDeclNo.count(ND) &&
4800 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4801 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004802 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004803 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004804 else
4805 RewriteTypeOfDecl(VD);
4806 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004807 }
Richard Smithdda56e42011-04-15 14:24:37 +00004808 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004809 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004810 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004811 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004812 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4813 }
4814 }
4815 }
Mike Stump11289f42009-09-09 15:08:12 +00004816
Steve Narofff4b992a2008-10-28 20:29:00 +00004817 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4818 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004819
4820 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004821 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4822 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004823 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4824 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004825 && "Statement stack mismatch");
4826 Stmts.pop_back();
4827 }
4828 // Handle blocks rewriting.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004829 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4830 ValueDecl *VD = DRE->getDecl();
4831 if (VD->hasAttr<BlocksAttr>())
4832 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004833 if (HasLocalVariableExternalStorage(VD))
4834 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004835 }
4836
Steve Narofff4b992a2008-10-28 20:29:00 +00004837 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004838 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004839 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004840 ReplaceStmt(S, BlockCall);
4841 return BlockCall;
4842 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004843 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004844 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004845 RewriteCastExpr(CE);
4846 }
4847#if 0
4848 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004849 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4850 ICE->getSubExpr(),
4851 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004852 // Get the new text.
4853 std::string SStr;
4854 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004855 Replacement->printPretty(Buf);
Steve Narofff4b992a2008-10-28 20:29:00 +00004856 const std::string &Str = Buf.str();
4857
4858 printf("CAST = %s\n", &Str[0]);
4859 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4860 delete S;
4861 return Replacement;
4862 }
4863#endif
4864 // Return this stmt unmodified.
4865 return S;
4866}
4867
Steve Naroffe70a52a2009-12-05 15:55:59 +00004868void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4869 for (RecordDecl::field_iterator i = RD->field_begin(),
4870 e = RD->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004871 FieldDecl *FD = *i;
Steve Naroffe70a52a2009-12-05 15:55:59 +00004872 if (isTopLevelBlockPointerType(FD->getType()))
4873 RewriteBlockPointerDecl(FD);
4874 if (FD->getType()->isObjCQualifiedIdType() ||
4875 FD->getType()->isObjCQualifiedInterfaceType())
4876 RewriteObjCQualifiedInterfaceTypes(FD);
4877 }
4878}
4879
Steve Narofff4b992a2008-10-28 20:29:00 +00004880/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4881/// main file of the input.
4882void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004883 switch (D->getKind()) {
4884 case Decl::Function: {
4885 FunctionDecl *FD = cast<FunctionDecl>(D);
4886 if (FD->isOverloadedOperator())
4887 return;
Mike Stump11289f42009-09-09 15:08:12 +00004888
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004889 // Since function prototypes don't have ParmDecl's, we check the function
4890 // prototype. This enables us to rewrite function declarations and
4891 // definitions using the same code.
4892 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004893
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00004894 if (!FD->isThisDeclarationADefinition())
4895 break;
4896
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004897 // FIXME: If this should support Obj-C++, support CXXTryStmt
4898 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4899 CurFunctionDef = FD;
4900 CurFunctionDeclToDeclareForBlock = FD;
4901 CurrentBody = Body;
4902 Body =
4903 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4904 FD->setBody(Body);
4905 CurrentBody = 0;
4906 if (PropParentMap) {
4907 delete PropParentMap;
4908 PropParentMap = 0;
4909 }
4910 // This synthesizes and inserts the block "impl" struct, invoke function,
4911 // and any copy/dispose helper functions.
4912 InsertBlockLiteralsWithinFunction(FD);
4913 CurFunctionDef = 0;
4914 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff1042ff32008-12-08 16:43:47 +00004915 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004916 break;
Mike Stump11289f42009-09-09 15:08:12 +00004917 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004918 case Decl::ObjCMethod: {
4919 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4920 if (CompoundStmt *Body = MD->getCompoundBody()) {
4921 CurMethodDef = MD;
4922 CurrentBody = Body;
4923 Body =
4924 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4925 MD->setBody(Body);
4926 CurrentBody = 0;
4927 if (PropParentMap) {
4928 delete PropParentMap;
4929 PropParentMap = 0;
4930 }
4931 InsertBlockLiteralsWithinMethod(MD);
4932 CurMethodDef = 0;
Steve Naroff1042ff32008-12-08 16:43:47 +00004933 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004934 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004935 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004936 case Decl::ObjCImplementation: {
4937 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4938 ClassImplementation.push_back(CI);
4939 break;
4940 }
4941 case Decl::ObjCCategoryImpl: {
4942 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4943 CategoryImplementation.push_back(CI);
4944 break;
4945 }
4946 case Decl::Var: {
4947 VarDecl *VD = cast<VarDecl>(D);
4948 RewriteObjCQualifiedInterfaceTypes(VD);
4949 if (isTopLevelBlockPointerType(VD->getType()))
4950 RewriteBlockPointerDecl(VD);
4951 else if (VD->getType()->isFunctionPointerType()) {
4952 CheckFunctionPointerDecl(VD->getType(), VD);
4953 if (VD->getInit()) {
4954 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4955 RewriteCastExpr(CE);
4956 }
4957 }
4958 } else if (VD->getType()->isRecordType()) {
4959 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4960 if (RD->isCompleteDefinition())
4961 RewriteRecordBody(RD);
4962 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004963 if (VD->getInit()) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004964 GlobalVarDecl = VD;
4965 CurrentBody = VD->getInit();
4966 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4967 CurrentBody = 0;
4968 if (PropParentMap) {
4969 delete PropParentMap;
4970 PropParentMap = 0;
4971 }
4972 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4973 GlobalVarDecl = 0;
4974
4975 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004976 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004977 RewriteCastExpr(CE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004978 }
4979 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004980 break;
4981 }
4982 case Decl::TypeAlias:
4983 case Decl::Typedef: {
4984 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4985 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4986 RewriteBlockPointerDecl(TD);
4987 else if (TD->getUnderlyingType()->isFunctionPointerType())
4988 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4989 }
4990 break;
4991 }
4992 case Decl::CXXRecord:
4993 case Decl::Record: {
4994 RecordDecl *RD = cast<RecordDecl>(D);
4995 if (RD->isCompleteDefinition())
Steve Naroffe70a52a2009-12-05 15:55:59 +00004996 RewriteRecordBody(RD);
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004997 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004998 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004999 default:
5000 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00005001 }
5002 // Nothing yet.
5003}
5004
Chris Lattnercf169832009-03-28 04:11:33 +00005005void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005006 if (Diags.hasErrorOccurred())
5007 return;
Mike Stump11289f42009-09-09 15:08:12 +00005008
Steve Narofff4b992a2008-10-28 20:29:00 +00005009 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005010
Steve Naroffd9803712009-04-29 16:37:50 +00005011 // Here's a great place to add any extra declarations that may be needed.
5012 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005013 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005014 E = ProtocolExprDecls.end(); I != E; ++I)
5015 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5016
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005017 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005018 if (ClassImplementation.size() || CategoryImplementation.size())
5019 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005020
Steve Narofff4b992a2008-10-28 20:29:00 +00005021 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5022 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005023 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005024 Rewrite.getRewriteBufferFor(MainFileID)) {
5025 //printf("Changed:\n");
5026 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5027 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005028 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005029 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005030
Steve Naroffd9803712009-04-29 16:37:50 +00005031 if (ClassImplementation.size() || CategoryImplementation.size() ||
5032 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005033 // Rewrite Objective-c meta data*
5034 std::string ResultStr;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00005035 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005036 // Emit metadata.
5037 *OutFile << ResultStr;
5038 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005039 OutFile->flush();
5040}
Fariborz Jahanian83077422011-12-08 18:25:15 +00005041
5042void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5043 InitializeCommon(context);
5044
5045 // declaring objc_selector outside the parameter list removes a silly
5046 // scope related warning...
5047 if (IsHeader)
5048 Preamble = "#pragma once\n";
5049 Preamble += "struct objc_selector; struct objc_class;\n";
5050 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5051 Preamble += "struct objc_object *superClass; ";
5052 if (LangOpts.MicrosoftExt) {
5053 // Add a constructor for creating temporary objects.
5054 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5055 ": ";
5056 Preamble += "object(o), superClass(s) {} ";
5057 }
5058 Preamble += "};\n";
5059 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5060 Preamble += "typedef struct objc_object Protocol;\n";
5061 Preamble += "#define _REWRITER_typedef_Protocol\n";
5062 Preamble += "#endif\n";
5063 if (LangOpts.MicrosoftExt) {
5064 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5065 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5066 } else
5067 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5068 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5069 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5070 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5071 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5072 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5073 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5074 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5075 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5076 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5077 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5078 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5079 Preamble += "(const char *);\n";
5080 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5081 Preamble += "(struct objc_class *);\n";
5082 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5083 Preamble += "(const char *);\n";
5084 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5085 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5086 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5087 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5088 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5089 Preamble += "(struct objc_class *, struct objc_object *);\n";
5090 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00005091 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5092 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahanian83077422011-12-08 18:25:15 +00005093 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5094 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5095 Preamble += "struct __objcFastEnumerationState {\n\t";
5096 Preamble += "unsigned long state;\n\t";
5097 Preamble += "void **itemsPtr;\n\t";
5098 Preamble += "unsigned long *mutationsPtr;\n\t";
5099 Preamble += "unsigned long extra[5];\n};\n";
5100 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5101 Preamble += "#define __FASTENUMERATIONSTATE\n";
5102 Preamble += "#endif\n";
5103 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5104 Preamble += "struct __NSConstantStringImpl {\n";
5105 Preamble += " int *isa;\n";
5106 Preamble += " int flags;\n";
5107 Preamble += " char *str;\n";
5108 Preamble += " long length;\n";
5109 Preamble += "};\n";
5110 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5111 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5112 Preamble += "#else\n";
5113 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5114 Preamble += "#endif\n";
5115 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5116 Preamble += "#endif\n";
5117 // Blocks preamble.
5118 Preamble += "#ifndef BLOCK_IMPL\n";
5119 Preamble += "#define BLOCK_IMPL\n";
5120 Preamble += "struct __block_impl {\n";
5121 Preamble += " void *isa;\n";
5122 Preamble += " int Flags;\n";
5123 Preamble += " int Reserved;\n";
5124 Preamble += " void *FuncPtr;\n";
5125 Preamble += "};\n";
5126 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5127 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5128 Preamble += "extern \"C\" __declspec(dllexport) "
5129 "void _Block_object_assign(void *, const void *, const int);\n";
5130 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5131 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5132 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5133 Preamble += "#else\n";
5134 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5135 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5136 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5137 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5138 Preamble += "#endif\n";
5139 Preamble += "#endif\n";
5140 if (LangOpts.MicrosoftExt) {
5141 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5142 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5143 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5144 Preamble += "#define __attribute__(X)\n";
5145 Preamble += "#endif\n";
5146 Preamble += "#define __weak\n";
5147 }
5148 else {
5149 Preamble += "#define __block\n";
5150 Preamble += "#define __weak\n";
5151 }
5152 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5153 // as this avoids warning in any 64bit/32bit compilation model.
5154 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5155}
5156
5157/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5158/// ivar offset.
5159void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5160 std::string &Result) {
5161 if (ivar->isBitField()) {
5162 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5163 // place all bitfields at offset 0.
5164 Result += "0";
5165 } else {
5166 Result += "__OFFSETOFIVAR__(struct ";
5167 Result += ivar->getContainingInterface()->getNameAsString();
5168 if (LangOpts.MicrosoftExt)
5169 Result += "_IMPL";
5170 Result += ", ";
5171 Result += ivar->getNameAsString();
5172 Result += ")";
5173 }
5174}
5175
5176/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5177void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5178 ObjCProtocolDecl *PDecl, StringRef prefix,
5179 StringRef ClassName, std::string &Result) {
5180 static bool objc_protocol_methods = false;
5181
5182 // Output struct protocol_methods holder of method selector and type.
Douglas Gregore6e48b12012-01-01 19:29:29 +00005183 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005184 /* struct protocol_methods {
5185 SEL _cmd;
5186 char *method_types;
5187 }
5188 */
5189 Result += "\nstruct _protocol_methods {\n";
5190 Result += "\tstruct objc_selector *_cmd;\n";
5191 Result += "\tchar *method_types;\n";
5192 Result += "};\n";
5193
5194 objc_protocol_methods = true;
5195 }
5196 // Do not synthesize the protocol more than once.
Douglas Gregor33b24292012-01-01 18:09:12 +00005197 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005198 return;
5199
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00005200 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5201 PDecl = Def;
5202
Fariborz Jahanian83077422011-12-08 18:25:15 +00005203 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5204 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5205 PDecl->instmeth_end());
5206 /* struct _objc_protocol_method_list {
5207 int protocol_method_count;
5208 struct protocol_methods protocols[];
5209 }
5210 */
5211 Result += "\nstatic struct {\n";
5212 Result += "\tint protocol_method_count;\n";
5213 Result += "\tstruct _protocol_methods protocol_methods[";
5214 Result += utostr(NumMethods);
5215 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5216 Result += PDecl->getNameAsString();
5217 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5218 "{\n\t" + utostr(NumMethods) + "\n";
5219
5220 // Output instance methods declared in this protocol.
5221 for (ObjCProtocolDecl::instmeth_iterator
5222 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5223 I != E; ++I) {
5224 if (I == PDecl->instmeth_begin())
5225 Result += "\t ,{{(struct objc_selector *)\"";
5226 else
5227 Result += "\t ,{(struct objc_selector *)\"";
5228 Result += (*I)->getSelector().getAsString();
5229 std::string MethodTypeString;
5230 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5231 Result += "\", \"";
5232 Result += MethodTypeString;
5233 Result += "\"}\n";
5234 }
5235 Result += "\t }\n};\n";
5236 }
5237
5238 // Output class methods declared in this protocol.
5239 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5240 PDecl->classmeth_end());
5241 if (NumMethods > 0) {
5242 /* struct _objc_protocol_method_list {
5243 int protocol_method_count;
5244 struct protocol_methods protocols[];
5245 }
5246 */
5247 Result += "\nstatic struct {\n";
5248 Result += "\tint protocol_method_count;\n";
5249 Result += "\tstruct _protocol_methods protocol_methods[";
5250 Result += utostr(NumMethods);
5251 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5252 Result += PDecl->getNameAsString();
5253 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5254 "{\n\t";
5255 Result += utostr(NumMethods);
5256 Result += "\n";
5257
5258 // Output instance methods declared in this protocol.
5259 for (ObjCProtocolDecl::classmeth_iterator
5260 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5261 I != E; ++I) {
5262 if (I == PDecl->classmeth_begin())
5263 Result += "\t ,{{(struct objc_selector *)\"";
5264 else
5265 Result += "\t ,{(struct objc_selector *)\"";
5266 Result += (*I)->getSelector().getAsString();
5267 std::string MethodTypeString;
5268 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5269 Result += "\", \"";
5270 Result += MethodTypeString;
5271 Result += "\"}\n";
5272 }
5273 Result += "\t }\n};\n";
5274 }
5275
5276 // Output:
5277 /* struct _objc_protocol {
5278 // Objective-C 1.0 extensions
5279 struct _objc_protocol_extension *isa;
5280 char *protocol_name;
5281 struct _objc_protocol **protocol_list;
5282 struct _objc_protocol_method_list *instance_methods;
5283 struct _objc_protocol_method_list *class_methods;
5284 };
5285 */
5286 static bool objc_protocol = false;
5287 if (!objc_protocol) {
5288 Result += "\nstruct _objc_protocol {\n";
5289 Result += "\tstruct _objc_protocol_extension *isa;\n";
5290 Result += "\tchar *protocol_name;\n";
5291 Result += "\tstruct _objc_protocol **protocol_list;\n";
5292 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5293 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5294 Result += "};\n";
5295
5296 objc_protocol = true;
5297 }
5298
5299 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5300 Result += PDecl->getNameAsString();
5301 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5302 "{\n\t0, \"";
5303 Result += PDecl->getNameAsString();
5304 Result += "\", 0, ";
5305 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5306 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5307 Result += PDecl->getNameAsString();
5308 Result += ", ";
5309 }
5310 else
5311 Result += "0, ";
5312 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5313 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5314 Result += PDecl->getNameAsString();
5315 Result += "\n";
5316 }
5317 else
5318 Result += "0\n";
5319 Result += "};\n";
5320
5321 // Mark this protocol as having been generated.
Douglas Gregor33b24292012-01-01 18:09:12 +00005322 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005323 llvm_unreachable("protocol already synthesized");
5324
5325}
5326
5327void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5328 const ObjCList<ObjCProtocolDecl> &Protocols,
5329 StringRef prefix, StringRef ClassName,
5330 std::string &Result) {
5331 if (Protocols.empty()) return;
5332
5333 for (unsigned i = 0; i != Protocols.size(); i++)
5334 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5335
5336 // Output the top lovel protocol meta-data for the class.
5337 /* struct _objc_protocol_list {
5338 struct _objc_protocol_list *next;
5339 int protocol_count;
5340 struct _objc_protocol *class_protocols[];
5341 }
5342 */
5343 Result += "\nstatic struct {\n";
5344 Result += "\tstruct _objc_protocol_list *next;\n";
5345 Result += "\tint protocol_count;\n";
5346 Result += "\tstruct _objc_protocol *class_protocols[";
5347 Result += utostr(Protocols.size());
5348 Result += "];\n} _OBJC_";
5349 Result += prefix;
5350 Result += "_PROTOCOLS_";
5351 Result += ClassName;
5352 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5353 "{\n\t0, ";
5354 Result += utostr(Protocols.size());
5355 Result += "\n";
5356
5357 Result += "\t,{&_OBJC_PROTOCOL_";
5358 Result += Protocols[0]->getNameAsString();
5359 Result += " \n";
5360
5361 for (unsigned i = 1; i != Protocols.size(); i++) {
5362 Result += "\t ,&_OBJC_PROTOCOL_";
5363 Result += Protocols[i]->getNameAsString();
5364 Result += "\n";
5365 }
5366 Result += "\t }\n};\n";
5367}
5368
5369void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5370 std::string &Result) {
5371 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5372
5373 // Explicitly declared @interface's are already synthesized.
5374 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregordc9166c2011-12-15 20:29:51 +00005375 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahanian83077422011-12-08 18:25:15 +00005376 // produce correct synthesis as yet.
5377 RewriteObjCInternalStruct(CDecl, Result);
5378 }
5379
5380 // Build _objc_ivar_list metadata for classes ivars if needed
5381 unsigned NumIvars = !IDecl->ivar_empty()
5382 ? IDecl->ivar_size()
5383 : (CDecl ? CDecl->ivar_size() : 0);
5384 if (NumIvars > 0) {
5385 static bool objc_ivar = false;
5386 if (!objc_ivar) {
5387 /* struct _objc_ivar {
5388 char *ivar_name;
5389 char *ivar_type;
5390 int ivar_offset;
5391 };
5392 */
5393 Result += "\nstruct _objc_ivar {\n";
5394 Result += "\tchar *ivar_name;\n";
5395 Result += "\tchar *ivar_type;\n";
5396 Result += "\tint ivar_offset;\n";
5397 Result += "};\n";
5398
5399 objc_ivar = true;
5400 }
5401
5402 /* struct {
5403 int ivar_count;
5404 struct _objc_ivar ivar_list[nIvars];
5405 };
5406 */
5407 Result += "\nstatic struct {\n";
5408 Result += "\tint ivar_count;\n";
5409 Result += "\tstruct _objc_ivar ivar_list[";
5410 Result += utostr(NumIvars);
5411 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5412 Result += IDecl->getNameAsString();
5413 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5414 "{\n\t";
5415 Result += utostr(NumIvars);
5416 Result += "\n";
5417
5418 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5419 SmallVector<ObjCIvarDecl *, 8> IVars;
5420 if (!IDecl->ivar_empty()) {
5421 for (ObjCInterfaceDecl::ivar_iterator
5422 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5423 IV != IVEnd; ++IV)
David Blaikie40ed2972012-06-06 20:45:41 +00005424 IVars.push_back(*IV);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005425 IVI = IDecl->ivar_begin();
5426 IVE = IDecl->ivar_end();
5427 } else {
5428 IVI = CDecl->ivar_begin();
5429 IVE = CDecl->ivar_end();
5430 }
5431 Result += "\t,{{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005432 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005433 Result += "\", \"";
5434 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005435 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005436 QuoteDoublequotes(TmpString, StrEncoding);
5437 Result += StrEncoding;
5438 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005439 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005440 Result += "}\n";
5441 for (++IVI; IVI != IVE; ++IVI) {
5442 Result += "\t ,{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005443 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005444 Result += "\", \"";
5445 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005446 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005447 QuoteDoublequotes(TmpString, StrEncoding);
5448 Result += StrEncoding;
5449 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005450 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005451 Result += "}\n";
5452 }
5453
5454 Result += "\t }\n};\n";
5455 }
5456
5457 // Build _objc_method_list for class's instance methods if needed
5458 SmallVector<ObjCMethodDecl *, 32>
5459 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5460
5461 // If any of our property implementations have associated getters or
5462 // setters, produce metadata for them as well.
5463 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5464 PropEnd = IDecl->propimpl_end();
5465 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005466 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005467 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005468 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005469 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005470 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005471 if (!PD)
5472 continue;
5473 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5474 if (!Getter->isDefined())
5475 InstanceMethods.push_back(Getter);
5476 if (PD->isReadOnly())
5477 continue;
5478 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5479 if (!Setter->isDefined())
5480 InstanceMethods.push_back(Setter);
5481 }
5482 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5483 true, "", IDecl->getName(), Result);
5484
5485 // Build _objc_method_list for class's class methods if needed
5486 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5487 false, "", IDecl->getName(), Result);
5488
5489 // Protocols referenced in class declaration?
5490 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5491 "CLASS", CDecl->getName(), Result);
5492
5493 // Declaration of class/meta-class metadata
5494 /* struct _objc_class {
5495 struct _objc_class *isa; // or const char *root_class_name when metadata
5496 const char *super_class_name;
5497 char *name;
5498 long version;
5499 long info;
5500 long instance_size;
5501 struct _objc_ivar_list *ivars;
5502 struct _objc_method_list *methods;
5503 struct objc_cache *cache;
5504 struct objc_protocol_list *protocols;
5505 const char *ivar_layout;
5506 struct _objc_class_ext *ext;
5507 };
5508 */
5509 static bool objc_class = false;
5510 if (!objc_class) {
5511 Result += "\nstruct _objc_class {\n";
5512 Result += "\tstruct _objc_class *isa;\n";
5513 Result += "\tconst char *super_class_name;\n";
5514 Result += "\tchar *name;\n";
5515 Result += "\tlong version;\n";
5516 Result += "\tlong info;\n";
5517 Result += "\tlong instance_size;\n";
5518 Result += "\tstruct _objc_ivar_list *ivars;\n";
5519 Result += "\tstruct _objc_method_list *methods;\n";
5520 Result += "\tstruct objc_cache *cache;\n";
5521 Result += "\tstruct _objc_protocol_list *protocols;\n";
5522 Result += "\tconst char *ivar_layout;\n";
5523 Result += "\tstruct _objc_class_ext *ext;\n";
5524 Result += "};\n";
5525 objc_class = true;
5526 }
5527
5528 // Meta-class metadata generation.
5529 ObjCInterfaceDecl *RootClass = 0;
5530 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5531 while (SuperClass) {
5532 RootClass = SuperClass;
5533 SuperClass = SuperClass->getSuperClass();
5534 }
5535 SuperClass = CDecl->getSuperClass();
5536
5537 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5538 Result += CDecl->getNameAsString();
5539 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5540 "{\n\t(struct _objc_class *)\"";
5541 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5542 Result += "\"";
5543
5544 if (SuperClass) {
5545 Result += ", \"";
5546 Result += SuperClass->getNameAsString();
5547 Result += "\", \"";
5548 Result += CDecl->getNameAsString();
5549 Result += "\"";
5550 }
5551 else {
5552 Result += ", 0, \"";
5553 Result += CDecl->getNameAsString();
5554 Result += "\"";
5555 }
5556 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5557 // 'info' field is initialized to CLS_META(2) for metaclass
5558 Result += ", 0,2, sizeof(struct _objc_class), 0";
5559 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5560 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5561 Result += IDecl->getNameAsString();
5562 Result += "\n";
5563 }
5564 else
5565 Result += ", 0\n";
5566 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5567 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5568 Result += CDecl->getNameAsString();
5569 Result += ",0,0\n";
5570 }
5571 else
5572 Result += "\t,0,0,0,0\n";
5573 Result += "};\n";
5574
5575 // class metadata generation.
5576 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5577 Result += CDecl->getNameAsString();
5578 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5579 "{\n\t&_OBJC_METACLASS_";
5580 Result += CDecl->getNameAsString();
5581 if (SuperClass) {
5582 Result += ", \"";
5583 Result += SuperClass->getNameAsString();
5584 Result += "\", \"";
5585 Result += CDecl->getNameAsString();
5586 Result += "\"";
5587 }
5588 else {
5589 Result += ", 0, \"";
5590 Result += CDecl->getNameAsString();
5591 Result += "\"";
5592 }
5593 // 'info' field is initialized to CLS_CLASS(1) for class
5594 Result += ", 0,1";
5595 if (!ObjCSynthesizedStructs.count(CDecl))
5596 Result += ",0";
5597 else {
5598 // class has size. Must synthesize its size.
5599 Result += ",sizeof(struct ";
5600 Result += CDecl->getNameAsString();
5601 if (LangOpts.MicrosoftExt)
5602 Result += "_IMPL";
5603 Result += ")";
5604 }
5605 if (NumIvars > 0) {
5606 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5607 Result += CDecl->getNameAsString();
5608 Result += "\n\t";
5609 }
5610 else
5611 Result += ",0";
5612 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5613 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5614 Result += CDecl->getNameAsString();
5615 Result += ", 0\n\t";
5616 }
5617 else
5618 Result += ",0,0";
5619 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5620 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5621 Result += CDecl->getNameAsString();
5622 Result += ", 0,0\n";
5623 }
5624 else
5625 Result += ",0,0,0\n";
5626 Result += "};\n";
5627}
5628
5629void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5630 int ClsDefCount = ClassImplementation.size();
5631 int CatDefCount = CategoryImplementation.size();
5632
5633 // For each implemented class, write out all its meta data.
5634 for (int i = 0; i < ClsDefCount; i++)
5635 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5636
5637 // For each implemented category, write out all its meta data.
5638 for (int i = 0; i < CatDefCount; i++)
5639 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5640
5641 // Write objc_symtab metadata
5642 /*
5643 struct _objc_symtab
5644 {
5645 long sel_ref_cnt;
5646 SEL *refs;
5647 short cls_def_cnt;
5648 short cat_def_cnt;
5649 void *defs[cls_def_cnt + cat_def_cnt];
5650 };
5651 */
5652
5653 Result += "\nstruct _objc_symtab {\n";
5654 Result += "\tlong sel_ref_cnt;\n";
5655 Result += "\tSEL *refs;\n";
5656 Result += "\tshort cls_def_cnt;\n";
5657 Result += "\tshort cat_def_cnt;\n";
5658 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5659 Result += "};\n\n";
5660
5661 Result += "static struct _objc_symtab "
5662 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5663 Result += "\t0, 0, " + utostr(ClsDefCount)
5664 + ", " + utostr(CatDefCount) + "\n";
5665 for (int i = 0; i < ClsDefCount; i++) {
5666 Result += "\t,&_OBJC_CLASS_";
5667 Result += ClassImplementation[i]->getNameAsString();
5668 Result += "\n";
5669 }
5670
5671 for (int i = 0; i < CatDefCount; i++) {
5672 Result += "\t,&_OBJC_CATEGORY_";
5673 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5674 Result += "_";
5675 Result += CategoryImplementation[i]->getNameAsString();
5676 Result += "\n";
5677 }
5678
5679 Result += "};\n\n";
5680
5681 // Write objc_module metadata
5682
5683 /*
5684 struct _objc_module {
5685 long version;
5686 long size;
5687 const char *name;
5688 struct _objc_symtab *symtab;
5689 }
5690 */
5691
5692 Result += "\nstruct _objc_module {\n";
5693 Result += "\tlong version;\n";
5694 Result += "\tlong size;\n";
5695 Result += "\tconst char *name;\n";
5696 Result += "\tstruct _objc_symtab *symtab;\n";
5697 Result += "};\n\n";
5698 Result += "static struct _objc_module "
5699 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5700 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5701 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5702 Result += "};\n\n";
5703
5704 if (LangOpts.MicrosoftExt) {
5705 if (ProtocolExprDecls.size()) {
5706 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5707 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5708 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5709 E = ProtocolExprDecls.end(); I != E; ++I) {
5710 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5711 Result += (*I)->getNameAsString();
5712 Result += " = &_OBJC_PROTOCOL_";
5713 Result += (*I)->getNameAsString();
5714 Result += ";\n";
5715 }
5716 Result += "#pragma data_seg(pop)\n\n";
5717 }
5718 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5719 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5720 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5721 Result += "&_OBJC_MODULES;\n";
5722 Result += "#pragma data_seg(pop)\n\n";
5723 }
5724}
5725
5726/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5727/// implementation.
5728void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5729 std::string &Result) {
5730 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5731 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005732 ObjCCategoryDecl *CDecl
5733 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005734
5735 std::string FullCategoryName = ClassDecl->getNameAsString();
5736 FullCategoryName += '_';
5737 FullCategoryName += IDecl->getNameAsString();
5738
5739 // Build _objc_method_list for class's instance methods if needed
5740 SmallVector<ObjCMethodDecl *, 32>
5741 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5742
5743 // If any of our property implementations have associated getters or
5744 // setters, produce metadata for them as well.
5745 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5746 PropEnd = IDecl->propimpl_end();
5747 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005748 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005749 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005750 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005751 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005752 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005753 if (!PD)
5754 continue;
5755 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5756 InstanceMethods.push_back(Getter);
5757 if (PD->isReadOnly())
5758 continue;
5759 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5760 InstanceMethods.push_back(Setter);
5761 }
5762 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5763 true, "CATEGORY_", FullCategoryName.c_str(),
5764 Result);
5765
5766 // Build _objc_method_list for class's class methods if needed
5767 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5768 false, "CATEGORY_", FullCategoryName.c_str(),
5769 Result);
5770
5771 // Protocols referenced in class declaration?
5772 // Null CDecl is case of a category implementation with no category interface
5773 if (CDecl)
5774 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5775 FullCategoryName, Result);
5776 /* struct _objc_category {
5777 char *category_name;
5778 char *class_name;
5779 struct _objc_method_list *instance_methods;
5780 struct _objc_method_list *class_methods;
5781 struct _objc_protocol_list *protocols;
5782 // Objective-C 1.0 extensions
5783 uint32_t size; // sizeof (struct _objc_category)
5784 struct _objc_property_list *instance_properties; // category's own
5785 // @property decl.
5786 };
5787 */
5788
5789 static bool objc_category = false;
5790 if (!objc_category) {
5791 Result += "\nstruct _objc_category {\n";
5792 Result += "\tchar *category_name;\n";
5793 Result += "\tchar *class_name;\n";
5794 Result += "\tstruct _objc_method_list *instance_methods;\n";
5795 Result += "\tstruct _objc_method_list *class_methods;\n";
5796 Result += "\tstruct _objc_protocol_list *protocols;\n";
5797 Result += "\tunsigned int size;\n";
5798 Result += "\tstruct _objc_property_list *instance_properties;\n";
5799 Result += "};\n";
5800 objc_category = true;
5801 }
5802 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5803 Result += FullCategoryName;
5804 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5805 Result += IDecl->getNameAsString();
5806 Result += "\"\n\t, \"";
5807 Result += ClassDecl->getNameAsString();
5808 Result += "\"\n";
5809
5810 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5811 Result += "\t, (struct _objc_method_list *)"
5812 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5813 Result += FullCategoryName;
5814 Result += "\n";
5815 }
5816 else
5817 Result += "\t, 0\n";
5818 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5819 Result += "\t, (struct _objc_method_list *)"
5820 "&_OBJC_CATEGORY_CLASS_METHODS_";
5821 Result += FullCategoryName;
5822 Result += "\n";
5823 }
5824 else
5825 Result += "\t, 0\n";
5826
5827 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5828 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5829 Result += FullCategoryName;
5830 Result += "\n";
5831 }
5832 else
5833 Result += "\t, 0\n";
5834 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5835}
5836
5837// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5838/// class methods.
5839template<typename MethodIterator>
5840void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5841 MethodIterator MethodEnd,
5842 bool IsInstanceMethod,
5843 StringRef prefix,
5844 StringRef ClassName,
5845 std::string &Result) {
5846 if (MethodBegin == MethodEnd) return;
5847
5848 if (!objc_impl_method) {
5849 /* struct _objc_method {
5850 SEL _cmd;
5851 char *method_types;
5852 void *_imp;
5853 }
5854 */
5855 Result += "\nstruct _objc_method {\n";
5856 Result += "\tSEL _cmd;\n";
5857 Result += "\tchar *method_types;\n";
5858 Result += "\tvoid *_imp;\n";
5859 Result += "};\n";
5860
5861 objc_impl_method = true;
5862 }
5863
5864 // Build _objc_method_list for class's methods if needed
5865
5866 /* struct {
5867 struct _objc_method_list *next_method;
5868 int method_count;
5869 struct _objc_method method_list[];
5870 }
5871 */
5872 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5873 Result += "\nstatic struct {\n";
5874 Result += "\tstruct _objc_method_list *next_method;\n";
5875 Result += "\tint method_count;\n";
5876 Result += "\tstruct _objc_method method_list[";
5877 Result += utostr(NumMethods);
5878 Result += "];\n} _OBJC_";
5879 Result += prefix;
5880 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5881 Result += "_METHODS_";
5882 Result += ClassName;
5883 Result += " __attribute__ ((used, section (\"__OBJC, __";
5884 Result += IsInstanceMethod ? "inst" : "cls";
5885 Result += "_meth\")))= ";
5886 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5887
5888 Result += "\t,{{(SEL)\"";
5889 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5890 std::string MethodTypeString;
5891 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5892 Result += "\", \"";
5893 Result += MethodTypeString;
5894 Result += "\", (void *)";
5895 Result += MethodInternalNames[*MethodBegin];
5896 Result += "}\n";
5897 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5898 Result += "\t ,{(SEL)\"";
5899 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5900 std::string MethodTypeString;
5901 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5902 Result += "\", \"";
5903 Result += MethodTypeString;
5904 Result += "\", (void *)";
5905 Result += MethodInternalNames[*MethodBegin];
5906 Result += "}\n";
5907 }
5908 Result += "\t }\n};\n";
5909}
5910
5911Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5912 SourceRange OldRange = IV->getSourceRange();
5913 Expr *BaseExpr = IV->getBase();
5914
5915 // Rewrite the base, but without actually doing replaces.
5916 {
5917 DisableReplaceStmtScope S(*this);
5918 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5919 IV->setBase(BaseExpr);
5920 }
5921
5922 ObjCIvarDecl *D = IV->getDecl();
5923
5924 Expr *Replacement = IV;
5925 if (CurMethodDef) {
5926 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5927 const ObjCInterfaceType *iFaceDecl =
5928 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5929 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5930 // lookup which class implements the instance variable.
5931 ObjCInterfaceDecl *clsDeclared = 0;
5932 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5933 clsDeclared);
5934 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5935
5936 // Synthesize an explicit cast to gain access to the ivar.
5937 std::string RecName = clsDeclared->getIdentifier()->getName();
5938 RecName += "_IMPL";
5939 IdentifierInfo *II = &Context->Idents.get(RecName);
5940 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5941 SourceLocation(), SourceLocation(),
5942 II);
5943 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5944 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5945 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5946 CK_BitCast,
5947 IV->getBase());
5948 // Don't forget the parens to enforce the proper binding.
5949 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5950 OldRange.getEnd(),
5951 castExpr);
5952 if (IV->isFreeIvar() &&
Douglas Gregor0b144e12011-12-15 00:29:59 +00005953 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005954 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5955 IV->getLocation(),
5956 D->getType(),
5957 VK_LValue, OK_Ordinary);
5958 Replacement = ME;
5959 } else {
5960 IV->setBase(PE);
5961 }
5962 }
5963 } else { // we are outside a method.
5964 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5965
5966 // Explicit ivar refs need to have a cast inserted.
5967 // FIXME: consider sharing some of this code with the code above.
5968 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5969 const ObjCInterfaceType *iFaceDecl =
5970 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5971 // lookup which class implements the instance variable.
5972 ObjCInterfaceDecl *clsDeclared = 0;
5973 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5974 clsDeclared);
5975 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5976
5977 // Synthesize an explicit cast to gain access to the ivar.
5978 std::string RecName = clsDeclared->getIdentifier()->getName();
5979 RecName += "_IMPL";
5980 IdentifierInfo *II = &Context->Idents.get(RecName);
5981 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5982 SourceLocation(), SourceLocation(),
5983 II);
5984 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5985 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5986 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5987 CK_BitCast,
5988 IV->getBase());
5989 // Don't forget the parens to enforce the proper binding.
5990 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5991 IV->getBase()->getLocEnd(), castExpr);
5992 // Cannot delete IV->getBase(), since PE points to it.
5993 // Replace the old base with the cast. This is important when doing
5994 // embedded rewrites. For example, [newInv->_container addObject:0].
5995 IV->setBase(PE);
5996 }
5997 }
5998
5999 ReplaceStmtWithRange(IV, Replacement, OldRange);
6000 return Replacement;
6001}